用库组件/碎片排除Webpack外部

Webpack在写同构的Javascript中对我们非常有用,在捆绑的时候为浏览器全局replacenpm包。

所以,如果我想在Node.js上使用node-fetch npm包,但在捆绑时排除它,只使用本地浏览器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 ,我不知道如何使用它,因为我的需求如下所示:

 const { URL } = require('whatwg-url') // or, if you don't like destructuring assignment const URL = require('whatwg-url').URL 

如何告诉Webpack使用浏览器全局URLreplacerequire('whatwg-url').URL出现?

起初我想强调一下,我不是一个webpack专家。 我认为在构build期间捆绑有更好的方法。 无论如何,这是我的想法:

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 。 然后它会dynamic地识别它编译你的文件,并使用正确的模块。

希望能帮助到你。