关于 webpack4 的 webpack.ProvidePlugin 结合 treeshaking 的问题?

新手上路,请多包涵

我的配置文件是这样的,按照 官方指南 的方法,提供了 ['lodash-es','chunk'] 的数组形式的参数值,但是为什么还是将整个 lodash 打包了,我期望的是只打包 lodashchunk 方法,请问这是怎么回事?

#################### webpack.config.js ####################

const path = require('path')
const CleanWebpackPlugin = require('clean-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const webpack = require('webpack')

module.exports = {
    mode:"production",
    entry: './src/index.js',
    output: {
        filename: '[name].bundle.js',
        path: path.resolve(__dirname, 'dist')
    },
    plugins: [
        new CleanWebpackPlugin('dist'),
        new HtmlWebpackPlugin({
            filename:"index.html",
            template:'index.html'
        }),
        new webpack.ProvidePlugin({
            _chunk:['lodash-es','chunk']
        })
    ]
}
#################### index.js ####################

console.log(_chunk(['a', 'b', 'c', 'd', 'e'], 2))
  • 这里看打包后的 main 文件,明显是将整个 lodash 打包了,WTF?

clipboard.png

阅读 3.6k
1 个回答

所以最后是怎么解决的,我来自问自答一遍,
因为tree shaking 利用的是 es 的模块系统。而 lodash.js 没有使用 CommonJS 或者 ES6 的写法。所以,安装库对应的模块系统即可。
单独打包所引用的函数需要安装的模块是lodash-es,

npm i lodash-es --save

然后打包就是了,但是不能用到new webpack. ProvidePlugin({_:'loadash'})配置全局引入,否则失效,官网的行不通。唉?

纠正一下,new webpack. ProvidePlugin({_:'loadash'}),是提供全局变量引用,不用到处import。

另外附上https://github.com/Formidable...

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进