修改输出资源的名称和路径
1. 配置
const path = require("path");module.exports = {entry: "./src/main.js",output: {// 所有文件的输出目录path: path.resolve(__dirname, "dist"),// 入口文件打包输出的文件名filename: "static/js/main.js", // 将 js 文件输出到 static/js 目录中},module: {rules: [{// 用来匹配 .css 结尾的文件test: /.css$/,// use 数组里面 Loader 执行顺序是从右到左use: ["style-loader", "css-loader"],},{test: /.less$/,use: ["style-loader", "css-loader", "less-loader"],},{test: /.s[ac]ss$/,use: ["style-loader", "css-loader", "sass-loader"],},{test: /.styl$/,use: ["style-loader", "css-loader", "stylus-loader"],},{test: /.(png|jpe?g|gif|webp)$/,type: "asset",parser: {dataUrlCondition: {maxSize: 10 * 1024, // 小于10kb的图片会被base64处理},},generator: {// 输出图片名称// 将图片文件输出到 static/imgs 目录中// 将图片文件命名 [hash:8][ext][query]// [hash:8]: hash值取8位// [ext]: 使用之前的文件扩展名// [query]: 添加之前的query参数filename: "static/imgs/[hash:8][ext][query]",},},],},plugins: [],mode: "development",};
2. 修改 index.html
webpack5 Hello Webpack5
3. 运行指令
npx webpack
- 此时输出文件目录:
(注意:需要将上次打包生成的文件清空,再重新打包才有效果)
├── dist└── static ├── imgs │└── 7003350e.png └── js└── main.js
自动清空上次打包资源
1. 配置
const path = require("path");module.exports = {entry: "./src/main.js",output: {path: path.resolve(__dirname, "dist"),filename: "static/js/main.js",clean: true, // 自动将上次打包目录资源清空},module: {rules: [{// 用来匹配 .css 结尾的文件test: /.css$/,// use 数组里面 Loader 执行顺序是从右到左use: ["style-loader", "css-loader"],},{test: /.less$/,use: ["style-loader", "css-loader", "less-loader"],},{test: /.s[ac]ss$/,use: ["style-loader", "css-loader", "sass-loader"],},{test: /.styl$/,use: ["style-loader", "css-loader", "stylus-loader"],},{test: /.(png|jpe?g|gif|webp)$/,type: "asset",parser: {dataUrlCondition: {maxSize: 40 * 1024, // 小于40kb的图片会被base64处理},},generator: {// 将图片文件输出到 static/imgs 目录中// 将图片文件命名 [hash:8][ext][query]// [hash:8]: hash值取8位// [ext]: 使用之前的文件扩展名// [query]: 添加之前的query参数filename: "static/imgs/[hash:8][ext][query]",},},],},plugins: [],mode: "development",};
2. 运行指令
npx webpack
观察 dist 目录资源情况