项目结构
webpackResolve
│ package-lock.json
│ package.json
│ webpack.config.js
└─assets
│ index.css
└─static
│ icon.png
└─src
index.js
安装依赖
在webpackResolve目录下运行
npm i webpack webpack-cli html-webpack-plugin css-loader style-loader --save-dev
webpack.config.js配置文件
import { resolve } from 'path';
import HtmlWebpackPlugin from 'html-webpack-plugin';
module.exports = {
mode:'development',
context:resolve(__dirname,'src'),
entry:'./index.build.js',
output:{
filename:'index.js',
path:resolve(__dirname,'dist')
},
module:{
rules:[
{
test:/\.png$/g,
use:'asset'
}
]
},
resolve:{
alias:{
assets:resolve(__dirname,'assets'),
static:resolve(__diranme,'static')
}
},
plugins:[new HtmlWebpackPlugin()]
}
index.js
import 'assets/index.css';
import icon from 'static/icon.png';
// 其他业务逻辑
webpack在解析路径的时候对解析的路径进行匹配,
index.js中assets实际上会被解析成path.resolve(__dirname,‘asstes’) + ‘/index.css’,
而同理icon会被解析成path.resolve(__dirname,‘static’)+‘/icon.png’
与在index.js中使用相对路径或绝对路径加载的路径是一致的;
需要注意的是,alias中的属性尾部不要加$ 符,加上$ 符解析的规则则会变成精准匹配,可以参考文档中的规则
打包命令
- 方式一:在webpackResolve目录下运行
webpack --config ./webapck.config.js
- 方式二:在package.json文件的scripts属性新增如下命令
{
...
"scripts":{
"build":"webpack --config ./webpack.config.js"
}
...
}
修改保存后,在webpackResolve目录下运行如下命令:
npm run build
打包后的目录
webpackResolve
│ package-lock.json
│ package.json
│ webpack.config.js
├─dist
│ index.build.js
│ index.html
└─assets
│ index.css
└─static
│ icon.png
└─src
index.js