使用库组件/片段排除Webpack外部

Dmi*_*lin 8 javascript node.js webpack

Webpack对于我们编写同构Javascript非常有用,并且npm在捆绑时交换浏览器全局变量的包.

所以,如果我想node-fetch npm在Node.js 上使用该包但在捆绑时将其排除,并且只使用本机浏览器fetch全局,我可以在我的中提及webpack.config.js:

{
  externals: {
    'node-fetch': 'fetch',
    'urlutils': 'URL',
    'webcrypto': 'crypto', // etc
  }
}
Run Code Online (Sandbox Code Playgroud)

然后我的CommonJS要求const fetch = require('node-fetch')将被转换为const fetch = window.fetch(或无论它做什么).

到现在为止还挺好.这是我的问题:当需要整个模块时,这很容易,但是当我需要一个导出模块的子模块/单个属性时呢?

例如,假设我想使用WhatWG URL标准,同构.我可以使用整个URL类的urlutils npm模块module.exports,所以我的要求如下:

const URL = require('urlutils')
Run Code Online (Sandbox Code Playgroud)

然后我可以urlutils在我的externals部分列出,没有概率.但是,当我想要使用更新的(并且更受支持的)npm软件包时whatwg-url,我不知道如何对其进行Webpack,因为我的要求如下:

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

如何告诉Webpack替换require('whatwg-url').URL浏览器全局的出现URL

Osk*_*kar 1

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

webpack.config.js

  module.exports = {
    target: "web",
    entry: "./entry.js",
    output: {
      path: __dirname,
      filename: "bundle.js"
    }
  };
Run Code Online (Sandbox Code Playgroud)

entry.js

  var URL = require("./content.js");
  document.write('Check console');
  console.log('URL function from content.js', URL);
Run Code Online (Sandbox Code Playgroud)

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;
  }
Run Code Online (Sandbox Code Playgroud)

index.html

  <html>
    <head>
      <meta charset="utf-8">
    </head>
    <body>
      <script type="text/javascript" src="bundle.js" charset="utf-8"></script>
    </body>
  </html>
Run Code Online (Sandbox Code Playgroud)

正如我在评论中所说,它将为 Web 捆绑包捆绑两个库 - 浪费空间。

现在,对于 NodeJS,您将targetfrom更改webnode,它应该采用其他库。https://webpack.github.io/docs/configuration.html#target

我找到了“同构”应用程序的模块:https ://github.com/halt-hammerzeit/universal-webpack

我认为您可以尝试使用两个单独的中间content.js文件作为模块的参数。第一个包含urlutis,第二个包含whatwg-url。然后它会动态地识别它编译文件的目的并使用正确的模块。

希望能帮助到你。