萌新自己学习webpack做的简单配置,如有错误请多包含,也可指点,谢谢.
# 抽离公共代码
# 懒加载
# es6 jsonp实现动态加载文件
# 热更新
# 使用devServer的hot属性开启热更新
# 使用webpack自带的NamedModulesPlugin插件打印被更新的模块路径
# 使用webpack自带的HotModuleReplacementPlugin插件开启热更新监控
# 在入口文件中判断一下是否开启了热更新,并且指定需要检查的文件.
# 如果开启了热更新,对应文件改动就不会刷新页面.
# index.js
# if (module.hot) {
# module.hot.accept('./source.js',()=>{
# console.log('文件更新了');
# let str = require('./source')
# console.log('新的',str);
# })
# }
webpack.config.js
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const webpack = require('webpack')
module.exports = {
mode: 'development',
devServer: {
hot: true, // 启用热更新
},
optimization: {
splitChunks: { // 分割代码块,只有多入口才需要把公用的资源抽出来
cacheGroups: { // 缓存组
common: { // 公共模块
minSize: 0,
minChunks: 2,
chunks: 'initial',
},
vender: {
priority: 1, // 权重,设置先抽离这里的文件,然后再抽离其它的
test: /node_modules/, // 只会抽离指定文件夹中符合要求的模块
minSize: 0,
minChunks: 2,
chunks: 'initial',
}
}
}
},
// 多入口
entry: {
home: './src/index.js',
other: './src/other.js'
},
output: {
// [name] home,other
filename: '[name].js',
path: path.resolve(__dirname,'dist')
},
plugins: [ // 数组 存放所有的webpack插件
new HtmlWebpackPlugin({
template: './index.html', // 模板
filename: 'home.html', // 打包后文件名
chunks: ['home'], // 配置引用资源
}),
new HtmlWebpackPlugin({
template: './index.html', // 模板
filename: 'other.html', // 打包后文件名
chunks: ['other'], // 配置引用资源
}),
new webpack.NamedModulesPlugin(), // 打印更新的模块路径
new webpack.HotModuleReplacementPlugin() // 热更新插件
],
}
index.js
console.log('hello home')
import './a'
import './b'
console.log('index.js');
import $ from 'jquery'
console.log($);
// 懒加载
// let btn = document.createElement('button')
// btn.innerText="小夫,在吗"
// btn.addEventListener('click',()=>{
// console.log('小夫,我要进来了哦');
// // es6 jsonp实现动态加载文件
// import('./source.js').then(data=>{
// console.log(data.default);
// })
// })
// document.body.appendChild(btn)
import str from './source'
console.log(str);
// css-loader style-loader vue-loader 已经实现了自动热更新的配置 无需像下面一样判断是否开启了热更新
if (module.hot) {
module.hot.accept('./source.js',()=>{
console.log('文件更新了');
let str = require('./source')
console.log('新的',str);
})
}