Webpack externals 告訴 Webpack 從 bundle 中排除某個導(dǎo)入。external 通常用于排除將通過 CDN 加載的導(dǎo)入。
例如,假設(shè)您使用 Vue 和 Express 實現(xiàn)服務(wù)器端渲染,但客戶端代碼通過 CDN 導(dǎo)入 Vue。假設(shè)您有以下 component.js 文件:
const Vue = require('vue')
module.exports = Vue.component('hello', {
props: ['name'],
template: '<h1>Hello, {{name}}</h1>'
})
以上 component.js 在 Node.js 中使用服務(wù)器端渲染效果非常好。但是,如何將上述組件與以下的 index.html 文件一起使用呢?
<html>
<body>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="content"></div>
<script src="dist/component.min.js"></script>
<script>
new Vue({ template: '<hello name="World" />' })
.mount(document.querySelector('#content'))
</script>
</body>
</html>
下面的 webpack.config.js 將 vue 添加為 externals,這意味著 Webpack 不會捆綁 Vue。相反,當(dāng) component.js 調(diào)用 require('vue') 時,Webpack 將返回 global.Vue。
module.exports = {
entry: {
component: `${__dirname}/component.js`
},
output: {
path: `${__dirname}/dist`,
filename: '[name].min.js'
},
target: 'web',
externals: {
// 去掉 require('vue'),返回 global.Vue
vue: 'Vue'
}
}
排除 Node.js Polyfills
externals 的另一個用例是需要在 Node.js 中使用 polyfill 的瀏覽器 API,比如 FormData。如果您正在測試需要在 Node.js 中使用 FormData 的代碼,您需要使用類似 form-data npm 模塊的 polyfill。
const axios = require('axios')
const FormData = require('form-data')
const form = new FormData()
form.append('key', 'value')
const res = await axios.post('https://example.com/post', form)
console.log(res.data)
而 FormData 又是一個瀏覽器 API,所以在編譯上述代碼時不需要捆綁。因此,您可以將 form-data 添加到 externals:
module.exports = {
entry: {
http: `${__dirname}/http.js`
},
output: {
path: `${__dirname}/dist`,
filename: '[name].min.js'
},
target: 'web',
externals: {
// 去掉 require('form-data'),返回 global.FormData
'form-data': 'FormData'
}
}