最基本的webpack配置文件
const path = require('path');
// html-webpack-plugin 为应用程序生成一个 HTML 文件
const HtmlWebpackPlugin = require('html-webpack-plugin'); // 通过 npm 安装
module.exports = {
// 这里使用 npx webpack --env NODE_ENV=local --env production --progress 能接收到数值,前提是将module转变成函数
// console.log('NODE_ENV: ', env.NODE_ENV); // 'local'
// console.log('Production: ', env.production); // true
// mode 模式
mode: 'development',
// 入口文件
entry: './src/index.js',
// entry: {
// index: './src/index.js',
// another: './src/another-module.js'
// 多个引入的模块共享
// index: {
// import: './src/index.js',
// dependOn: 'shared',
// },
// another: {
// import: './src/another-module.js',
// dependOn: 'shared',
// },
// // 共享插件名为lodash
// shared: 'lodash',
// },
// SplitChunksPlugin插件 提取lodash生成一个新的lodash模块
// optimization: {
// splitChunks: {
// chunks: 'all',
// }
// },
optimization: {
moduleIds: 'deterministic',
runtimeChunk: 'single',
splitChunks: {
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all',
},
},
},
},
// 追踪错误 source map
// 测试:print.js中,如果有错误,会提示到正确的行数
devtool: 'inline-source-map',
// 开启开发环境,以dist目录
devServer: {
contentBase: './dist',
},
// 出口文件
output: {
path: path.resolve(__dirname, 'dist'),
// filename: 'bundle.js',
// filename: '[name].bundle.js',
// 动态hash去除浏览器的缓存
filename: '[name].[contenthash].js',
// 在构建dist文件的时候,清理dist文件夹内容,重新构建dist文件夹内容
clean: true,
// publicPath: '/'
},
// loader 装载器
module: {
// 规则 test 正则寻找文件名称的匹配
// use 遇到匹配的文件,使用什么样的插件
// “嘿,webpack 编译器,当你碰到「在 require()/import 语句中被解析为 '.txt' 的路径」时,在你对它打包之前,先 use(使用) raw-loader 转换一下。”
rules: [
{ test: /\.css$/i, use: ['style-loader', 'css-loader'] },
{test: /\.(png|svg|jpg|jpeg|gif)$/i, type: 'asset/resource'},
// {test: /\.(woff|woff2|eot|ttf|otf)$/i, type: 'asset/resource',}
],
},
// plugin 插件
// 1. 携带模板 (常用)
// plugins: [new HtmlWebpackPlugin({ template: './src/index.html' })]
// 2. 不携带模板 (不常用)
plugins: [new HtmlWebpackPlugin({title: '管理'})]
};