整理开发模式以及生产模式的配置文件
首先在项目根目录下新建一个config文件夹
然后将webpack.config.js配置文件移动到该文件夹中并修改名称为webpack.dev.js
然后将webpack.dev.js复制一份也放在这个文件夹中并重命名为webpack.prod.js(生产模式的配置)
修改开发模式的配置文件内容为:
- 修改绝对路径地址
- 将output中的path删掉,开发模式不需要输出文件
const path = require('path') const ESLintPlugin = require('eslint-webpack-plugin') const HtmlWebpackPlugin = require('html-webpack-plugin') module.exports = { entry: './src/main.js', output: { filename: 'static/js/main.js', clean: true }, module: { rules: [ { test: /\.css$/, // 正则表达式,用于匹配需要加载的文件 use: [ "style-loader", "css-loader"] // 使用的加载器插件模块,从右向左调用插件 }, { test: /\.png$/, type: "asset", parser: { dataUrlCondition: { maxSize: 10 * 1024 } }, generator: { filename: "static/images/[hash][ext][query]" } }, { test: /\.(ttf|woff2?)$/, type: "asset/resource", generator: { filename: "static/media/[hash:10][ext][query]" } }, { test: /\.js$/, // exclude排除node_modules文件,即不对该文件夹内的文件进行处理 exclude: /node_modules/, use: { loader: 'babel-loader' } } ] }, plugins: [ new ESLintPlugin({ context: path.resolve(__dirname, '../src') }), new HtmlWebpackPlugin({ // 指定html模板,会保留该模板的结构 // 依据该模板创建新的html文件 template: path.resolve(__dirname, '../public/index.html') }) ], devServer: { host: 'localhost', port: 3000, open: true }, mode: 'development' }
修改生产模式配置文件内容为:
- 修改绝对路径地址
- 删除devServer对象
- 将mode值修改为production
const path = require('path') const ESLintPlugin = require('eslint-webpack-plugin') const HtmlWebpackPlugin = require('html-webpack-plugin') module.exports = { entry: './src/main.js', output: { path: path.resolve(__dirname, '../dist'), filename: 'static/js/main.js', clean: true }, module: { rules: [ { test: /\.css$/, // 正则表达式,用于匹配需要加载的文件 use: [ "style-loader", "css-loader"] // 使用的加载器插件模块,从右向左调用插件 }, { test: /\.png$/, type: "asset", parser: { dataUrlCondition: { maxSize: 10 * 1024 } }, generator: { filename: "static/images/[hash][ext][query]" } }, { test: /\.(ttf|woff2?)$/, type: "asset/resource", generator: { filename: "static/media/[hash:10][ext][query]" } }, { test: /\.js$/, // exclude排除node_modules文件,即不对该文件夹内的文件进行处理 exclude: /node_modules/, use: { loader: 'babel-loader' } } ] }, plugins: [ new ESLintPlugin({ context: path.resolve(__dirname, '../src') }), new HtmlWebpackPlugin({ // 指定html模板,会保留该模板的结构 // 依据该模板创建新的html文件 template: path.resolve(__dirname, '../public/index.html') }) ], mode: 'production' }
然后在package.json中修改scripts
"scripts": { "serve": "npx webpack --config config/webpack.dev.js", "build": "npx webpack --config config/webpack.prod.js" }
最后分别运行
npm run serve
以及npm run build
测试命令是否能执行成功npm run serve将会打开浏览器
npm run build将会在项目根目录下生成一个dist文件夹