const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
mode: 'development',
entry: {
index: './src/index.js', // index 自己定义的入口名称
another: './src/another-module.js' // 同样是自己定义的入口名称,可以随便取
// index: {
// import: './src/index.js',
// dependOn: 'shared', // 使用entry手动去重(多个页面引入相同的模块时,抽离出公共模块,单独生成一个bundle)
// },
// another: {
// import: './src/another-module.js',
// dependOn: 'shared'
// },
// shared: 'lodash' , // 这个是公共模块,单独抽离出来
},
output: {
filename: '[name].[contenthash].js', // 输出的文件名 contenthash根据内容生成唯一的hash值,如果内容发生改变则会重新生成一个hash值
path: path.resolve(__dirname, 'dist'),
clean: true // 清空dist文件夹后再重新生成
},
module: {
rules: [
{
test: /\.css$/i, // 匹配的文件类型
use: ['style-loader', 'css-loader'] // 使用的加载器loader进行解析
},
{
test: /\.(png|svg|jpg|jpeg|gif)$/i,
type:'asset/resource' // 使用webpack内置的模块进行解析
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/i,
type: 'asset/resource'
}
]
},
plugins: [
new HtmlWebpackPlugin({ // 生成一个html文件,例如index.html,会自动把需要的已经生成好的bundle引进去
title: 'Development'
})
],
// 避免在生产中使用 inline-*** 和 eval-***,因为它们会增加 bundle 体积大小,并降低整体性能
// devtool: 'inline-source-map', // 当页面出错时,可以定位到源文件的具体行(如果不使用的话,只能定位到打包后的文件中的具体行,就不容易找问题了),但是runtimeChunk不能单独抽离出来
devtool: 'source-map', // 源码映射,也是定位到源文件的具体行,在生产环境使用source-map比inline-source-map的体积小
devServer: { /// 这是webpack-dev-server,开启了一个web server, localhost:8080, 文件将通过这个域名进行访问
contentBase: './dist' // 可访问文件路径
},
optimization: { // 优化选项
moduleIds: 'deterministic', // 增加或减少一个本地依赖,生成的vendor 哈希文件名不会改变,有利于缓存
runtimeChunk: 'single', // 将runtime代码拆分为一个单独的chunk
splitChunks: { // 使用splitChunks自动去重,重复的模块可以放在其中的一个chunk中或者在一个单独的chunk中
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/, // 代表node_modules目录下需要用到的模块都打包到同一个chunk中,因为node_modules目录下的模块代码很少改动,可以利用浏览器的缓存
name: 'vendors', // chunk名字叫vendors,
chunks: 'all'
}
}
}
}
}