gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 04:20:13 27 4
gpt4 key购买 nike

Webpack 在编写同构 Javascript 以及在捆绑时将 npm 包换成浏览器全局变量方面对我们非常有用。

因此,如果我想在 Node.js 上使用 node-fetch npm 包,但在捆绑时将其排除并仅使用 native 浏览器 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 standard ,同构。我可以使用 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 bundle 捆绑两个库 - 浪费空间。

现在,对于 NodeJS,您将 targetweb 更改为 node,它应该使用另一个库。 https://webpack.github.io/docs/configuration.html#target

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

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

希望对您有所帮助。

关于javascript - 使用库组件/片段排除 Webpack 外部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43101644/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com