Shimming解决的问题
引入webpack.ProvidePlugin()解决:如果使用了一些版本比较老的模块如jquery、lodash,这些老模块的用法不是ES Module的使用方式,如果用webpack打包用这种模块会报错,为了解决这样的错误就要用到webpack.ProvidePlugin()
概念
这个插件就相当于一个垫片
问题
一个模块中的this指向的是模块自身而不是window,解决这个问题可以用imports-loader
配置
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: {
main: './src/index.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: [{
loader: 'babel-loader'
}, {
loader: 'imports-loader?this=>window'
}],
}, {
test: /\.(jpg|png|gif)$/,
use: {
loader: 'url-loader',
options: {
name: '[name]_[hash].[ext]',
outputPath: 'images/',
limit: 2048
}
}
}, {
test: /\.(eot|ttf|svg|woff|woff2)$/,
use: {
loader: 'file-loader'
}
}]
},
output: {
path: path.resolve(__dirname, '../dist')
},
plugins: [
new HtmlWebpackPlugin({
template: 'src/index.html'
}),
new CleanWebpackPlugin(),
new webpack.ProvidePlugin({
$: 'jquery',
_join: ['lodash', 'join']
//如果一个模块中使用了$字符串,就会在模块中自动得引用jquery
})
],
optimization: {
usedExports: true,
splitChunks: {
chunks: "all",
cacheGroups: {//当打包同步代码时,上面的参数生效
vendors: {
test: /[\\/]node_modules[\\/]/,
priority: -10,
filename: 'vendors.[contenthash].js'
}
}
}
},
performance: false
}