externals 配置项主要用于防止将某些 import 的包(package)打包到 bundle 中,而是在运行时(runtime)再从外部获取这些扩展依赖(external dependencies)。这样做的主要目的是为了解决打包文件过大的问题。
优化前
webpack.config.jsconst config = {entry: './src/index.js',output: {filename: 'main.js'},mode: 'development',
}module.exports = config;
src/index.js
import $ from 'jquery'
$(document).ready(() => {$('body').css({width: '100%',height: '100%','background-color': 'red'})
})
优化后
webpack.config.jsconst HtmlWebpackPlugin = require('html-webpack-plugin');const config = {entry: './src/index.js',output: {filename: 'main.js'},mode: 'development',externals: {$: 'jQuery'},plugins: [new HtmlWebpackPlugin({template: './index.html',})]
}module.exports = config;
src/index.js
$(document).ready(() => {$('body').css({width: '100%',height: '100%','background-color': 'red'})
})
index.html
<!DOCTYPE html>
<html lang="en">
<body><script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
</body>
</html>
可以看到将jquery排除在打包内,节省了319-177=144ms