Webpack 在编写同构 Javascript 以及在捆绑时将npm
包换成浏览器全局
时非常有用。因此,如果我想在 Node 上使用node-fetch
npm
包.js但在捆绑时将其排除,而只使用全局fetch
本机浏览器,我可以在我的webpack.config.js
中提及它:
{
externals: {
'node-fetch': 'fetch',
'urlutils': 'URL',
'webcrypto': 'crypto', // etc
}
}
然后我的 CommonJS 要求const fetch = require('node-fetch')
将被转换为const fetch = window.fetch
(或它所做的任何事情)。
目前为止,一切都好。这是我的问题:当需要整个模块时,这很容易,但是当我需要导出模块的子模块/单个属性时呢?
例如,假设我想同构地使用 WhatWG URL 标准。我可以使用urlutils
npm
模块,该模块module.exports
整个URL类,因此我的要求如下所示:
const URL = require('urlutils')
然后我可以在我的externals
部分列出urlutils
,没有概率。但是当我想使用更新的(并且更受支持的)npm
包时,比如说,whatwg-url
,我不知道如何 Webpack 它,因为我的需求如下所示:
const { URL } = require('whatwg-url')
// or, if you don't like destructuring assignment
const URL = require('whatwg-url').URL
如何告诉 Webpack 将出现的require('whatwg-url').URL
替换为浏览器全局URL
?
首先,我想强调一下,我不是 webpack 专家。我认为在构建时有更好的捆绑方法。无论如何,这是我的想法:
webpack.config.js
module.exports = {
target: "web",
entry: "./entry.js",
output: {
path: __dirname,
filename: "bundle.js"
}
};
entry.js
var URL = require("./content.js");
document.write('Check console');
console.log('URL function from content.js', URL);
content.js
let config = require('./webpack.config.js');
let urlutils = require('urlutils');
let whatwgUrl = require('whatwg-url');
console.log('urlutils:', urlutils);
console.log('whatwgUrl', whatwgUrl);
module.exports = {
URL: undefined
};
if (config.target === 'web') {
module.exports.URL = urlutils;
} else {
module.exports.URL = whatwgUrl.URL;
}
index.html
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<script type="text/javascript" src="bundle.js" charset="utf-8"></script>
</body>
</html>
正如我在评论中所说,它将为 Web 捆绑两个库 - 浪费空间。
现在,对于 NodeJS,您将target
从web
更改为node
,它应该采用其他库。 https://webpack.github.io/docs/configuration.html#target
我找到了一个"同构"应用程序的模块:https://github.com/halt-hammerzeit/universal-webpack
我认为您可以尝试使用两个单独的中间content.js
文件作为模块的参数。一个包含urlutis
,第二个包含whatwg-url
。然后它会动态识别它编译文件的内容并使用正确的模块。
希望对您有所帮助。