# externals
項目中所有使用到的代碼都會被打包到項目中。
但實際開發時,我們有很多項目中用到的模塊是不希望被打包到代碼中的。比如,我們常使用 `jquery` 這個庫,這個庫我們一般都放到 CDN 上然后通過 script 標簽引入來使用,這時我們就可以配置 `externals` 屬性。
webpack 在打包時,externals 中的模塊不會被打包到最終的代碼中。
配置文件
~~~json
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { resolve } = require('path');
module.exports = {
mode: 'production',
entry: './src/index.js',
output: {
path: resolve(__dirname, './dist'),
filename: 'index_bundle.js'
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html'
})
],
externals: {
'jquery': '$'
}
}
~~~
配置了 externals 之后,當我們在項目中引入 jquery 時:
~~~
import $ from 'jquery'
~~~
jquery 是不會被打包到最終代碼中的。
我們一般需要單獨通過 script 標簽引入 jquery:
~~~
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js" />
~~~