webpack5搭建svg环境
svg是矢量图。使用svg画的图片,不会怎么放大,都不失真
1: svg可以通过img标签加载
2: svg可以作为字体图标
3: svg 可以用在大屏可视化上做各种标记点。
进阶:将svg 做成icon 组件,并使用webpack 搭建环境 …
目录结构
开发实例代码如下
- 在根目录创建src文件夹,并创建user.svg,index.js
// 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 is run');
const div = document.createElement("div");
div.style.width = '300px';
div.style.height = '300px';
div.style.border = '3px solid red';
div.style.background = `url(${user})`;
var body = document.querySelector("body");
body.appendChild(div);
const img = document.createElement('img');
img.src = user;
body.appendChild(img);
- 在根目录创建空的html
<!--创建html-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.icon-user {
position: relative;
left: 200px;
top: 80px;
background-color: red;
}
</style>
</head>
<body>
<!-- svg 是一个画布 -->
<svg class="icon-user" verison="1.1" xmlns="http://www.w3.org/2000/svg" width="424" height="424">
<!-- circle 画一个圆 -->
<circle cx="12" cy="12" r="10" />
<circle cx='300' cy="300" r="50" fill="blue" stroke-width="10" stroke="pink" />
<!-- line 直线 -->
<line x1='100' y1='50' x2='300' y2='50' style="stroke-width:5; stroke:pink" />
<!-- polygon 多边形 -->
<polygon points="100,10 40,198 190,78 10,78 160,198"
style="fill:rgb(11, 181, 233);stroke:rgb(192, 39, 19);stroke-width:5;fill-rule:nonzero;" />
</svg>
<img src="./src/user.svg">
</body>
</html>
初始项目
- npm init
初始化安装依赖
- webpack
- webpack-cli
- html-webpack-plugin
初始化webpack.config.js文件
module.exports = {
mode:'development',
entry:'./src/index.js',
output:{
path:path.resolve(__dirname,"dist"),
filename:'[name].js',
},
}
配置 svg-loader,plugin
const path = require('path');
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
mode:'development',
entry:'./src/index.js',
output:{
path:path.resolve(__dirname,"dist"),
filename:'[name].js',
// assetModuleFilename:'images/[hash][ext][query]'
},
module:{
rules:[
{
test:/\.svg$/i,
type:'asset/inline',
// webpack 5以下版本不支持以下写法
// use:["svg-inline-loader"]
}
]
},
plugins:[
new HtmlWebpackPlugin({
template:'./index.html',
filename:'index.html',
chunks:['main']
})
]
}
运行 webpack
- npx webpack