External extension (Externals) configuration
What are Externals in Webpack
Webpack's Externals configuration allows developers to exclude certain dependencies from the output bundle. These dependencies are instead fetched externally at runtime. This approach is particularly useful for libraries loaded via CDN or dependencies already introduced into the runtime environment through other means.
// webpack.config.js
module.exports = {
externals: {
jquery: 'jQuery'
}
};
Basic Usage of Externals
The most common way to configure externals is using the object syntax. The key represents the module name to exclude, and the value specifies the global variable to be used at runtime.
externals: {
lodash: '_',
react: 'React',
'react-dom': 'ReactDOM'
}
When these modules are required or imported in the code, Webpack will not bundle them but will treat them as external dependencies:
import _ from 'lodash'; // Will actually use the global _ variable
Various Configuration Forms of Externals
String Form
The simplest form is to directly specify the global variable name:
externals: {
jquery: 'jQuery'
}
Array Form
When both the module name and global variable need to be specified:
externals: {
subtract: ['./math', 'subtract']
}
Object Form
Provides more granular control:
externals: {
react: {
root: 'React',
commonjs: 'react',
commonjs2: 'react',
amd: 'react'
}
}
Function Form
The most flexible approach, allowing custom logic:
externals: [
function(context, request, callback) {
if (/^yourregex$/.test(request)) {
return callback(null, 'commonjs ' + request);
}
callback();
}
]
Externals in Different Module Systems
CommonJS Externals
externals: {
fs: 'commonjs fs',
path: 'commonjs path'
}
AMD Externals
externals: {
jquery: {
amd: 'jQuery'
}
}
UMD Externals
externals: {
moment: {
root: 'moment',
commonjs: 'moment',
commonjs2: 'moment',
amd: 'moment'
}
}
Practical Application Scenarios
Excluding CDN-Loaded Libraries
<!-- index.html -->
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
// webpack.config.js
externals: {
jquery: 'jQuery'
}
Shared Dependencies in Micro-Frontend Architecture
In a micro-frontend architecture, the main application and sub-applications can share certain libraries:
// Sub-application's Webpack configuration
externals: {
react: 'react',
'react-dom': 'reactDOM'
}
Built-in Modules in Node.js Environment
When building Node.js applications, built-in modules can be excluded:
externals: {
fs: 'commonjs fs',
path: 'commonjs path'
}
Advanced Configuration Techniques
Regular Expression Matching
externals: [
/^[a-z\-0-9]+$/ // Excludes all modules matching this pattern
]
Conditional Exclusion
externals: [
function({ context, request }, callback) {
if (request.includes('node_modules')) {
return callback(null, `commonjs ${request}`);
}
callback();
}
]
Dynamically Generating Externals
const nodeExternals = require('webpack-node-externals');
module.exports = {
externals: [nodeExternals()],
// Other configurations...
};
Common Issues and Solutions
Undefined Global Variable Error
Ensure the external dependency is indeed available at runtime:
externals: {
jquery: {
root: 'jQuery',
commonjs: 'jquery',
commonjs2: 'jquery',
amd: 'jquery'
}
}
Working with DLLPlugin
externals: {
'react': 'React',
'react-dom': 'ReactDOM'
},
plugins: [
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./manifest.json')
})
]
Type Definitions in TypeScript
Type definition packages must also be installed:
npm install --save-dev @types/jquery
Performance Optimization Considerations
Proper use of externals can significantly reduce bundle size:
// Before
asset main.js 1.5 MiB [emitted] (name: main)
// After
asset main.js 350 KiB [emitted] (name: main)
Coordination with Other Configurations
Working with output.libraryTarget
output: {
libraryTarget: 'umd'
},
externals: {
react: 'react'
}
Relationship with SplitChunksPlugin
Modules configured in externals will not participate in the split chunks optimization process.
Testing and Validation
Verify if the externals configuration is effective:
// Inspect the bundle after building
// Should not see code from excluded modules
Use webpack-bundle-analyzer for analysis:
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
module.exports = {
plugins: [new BundleAnalyzerPlugin()]
};
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:动态导入与懒加载实现