webpack5搭建svg环境
svg 是矢量图。使用svg画的图片,不会怎么放大,都不失真
1: svg 可以通过 img标签加载
2: svg 可以作为字体图标
3: svg 可以用在大屏可视化上 做各种标记点。
进阶:将svg 做成 icon 组件,并使用webpack 搭建环境 … 编辑中…
开发实例代码如下
// user.svg
<svg verison="1.1" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"
stroke="#000">
<circle cx="12" cy="12" r="10" fill="yellow"/>
</svg>
// index.js
import user from'./user.svg';
console.log('index.js run');
console.log(user)
const div = document.createElement("div");
div.style.width = '300px';
div.style.height = '300px';
div.style.border = '3px solid red';
// svg 作为背景图片
div.style.background = `url(${user})`;
var body = document.querySelector('body');
body.appendChild(div)
const img = document.createElement('img');
img.src = user;
body.appendChild(img)
创建空的 index.html
初始项目
npm init -y
初始化安装依赖
npm i --save-dev webpack@5.45.1 webpack-cli@4.7.2 html-webpack-plugin
初始化webpack.config.js文件
const path = require('path');
module.exports = {
mode: "development",
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, 'dist'),
filename: "[name].js",
},
}
1配置 svg 2打包 html
module.exports = {
mode: "development",
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, 'dist'),
filename: "[name].js",
},
module: {
rules: [
{
test: /\.svg/,
type: 'asset/inline',
// webpack5 以下版本才支持这个写法
// use:['svg-inline-loader']
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './index.html',
filename: 'index.html'
})
]
}
运行 webpack
npm run build
实际上运行: npx webpack