webpack: Use externals configuration to exclude the use of a certain dependency after packaging & plug-in IgnorePlugin

background

Suppose we write a library and use webpack to package the output bundle, but this library depends on a third-party package, such as lodash. At this time, we do not want to package this library into the bundle because the volume will become larger, and in our main project This lodash has already been installed, so just rely on the lodash in the main project.

So how should we remove the packaged lodash?

Use externals

module.exports = {
    
    
  //...
  externals: {
    
    
    jquery: 'jQuery',
    lodash: 'lodash',
    './echarts': 'echarts'
  },
};

As you can see, the configuration here is key: valuein the form.

  • key represents the value in require
  • value represents which global variable is used to replace it.

Example 1

src/index.js

require('jquery')

webpack.config.js

module.exports = {
    
    
  //...
  externals: {
    
    
    jquery: 'jQuery'
  },
};

Here we have excluded jquery, so which variable in the main project do we rely on as the jquery we exclude?
The key (jquery) in this refers to require('jquery')the jquery in , and the value (jQuery) means to find the jQuery variable in the main project (that is, the global variable) instead.

Example 2

src/index.js

require('./echarts')

webpack.config.js

module.exports = {
    
    
  //...
  externals: {
    
    
    './echarts': 'echarts'
  },
};

In the same way, it is not difficult to understand. When encountering an import './echarts', go to the global variables to find echarts.

webpack pluginIgnorePlugin

It's a bit similar to the externals function, but allows for more detailed control, such as not packaging a certain folder of a certain third-party package.

plugins:[
	new Webpack.IgnorePlugin(/\.\/locale/,/moment/),//moment这个库中,如果引用了./locale/目录的内容,就忽略掉,不会打包进去
]

Although we ignored the file directory containing the './locale/' field path according to the above method, it also prevented us from displaying the Chinese language when we used it. We can manually introduce it if necessary.

import moment from 'moment'

//设置语言

//手动引入所需要的语言包
import 'moment/locale/zh-cn';

moment.locale('zh-cn');

let r = moment().endOf('day').fromNow();
console.log(r);

Guess you like

Origin blog.csdn.net/weixin_43972437/article/details/133271934