gpt4 book ai didi

javascript - 包含 JavaScript 代码而不打包为模块

转载 作者:数据小太阳 更新时间:2023-10-29 05:39:15 26 4
gpt4 key购买 nike

如何使用 webpack 获取未打包为 UMD 兼容模块(AMD、CommonJS)的 JavaScript 库?

我不希望库通过加载程序。我只想将它包含在 <script> 中需要时标记,并让 webpack 管理此依赖项。

我不想简单地将它放在我的 index.html 中的脚本标记中,因为我想利用 webpack 的代码拆分,并且只在必要时包含它。

我读过有关“外部因素”的内容,我不确定这是否与它有任何关系。文档不够清楚。

谢谢:)


更新问题

此外,这个问题专门针对前端库,只需通过 <script> 包含即可。标记工作。

最佳答案

您可以将 amd 支持添加到您的库中,然后使用 webpack 加载它。一些可以帮助您实现的链接是:

基本上要做的是,在库的顶部,您可以检查它是 commonjs 环境还是 AMD 环境。因此,您可以导出您的图书馆。

一个例子可以是这个(取自 1st link)

(function (root, factory) {
if(typeof define === "function" && define.amd) {
// Now we're wrapping the factory and assigning the return
// value to the root (window) and returning it as well to
// the AMD loader.
define(["postal"], function(postal){
return (root.myModule = factory(postal));
});
} else if(typeof module === "object" && module.exports) {
// I've not encountered a need for this yet, since I haven't
// run into a scenario where plain modules depend on CommonJS
// *and* I happen to be loading in a CJS browser environment
// but I'm including it for the sake of being thorough
module.exports = (root.myModule = factory(require("postal")));
} else {
root.myModule = factory(root.postal);
}
}(this, function(postal) {
// module code here....
return myModule;
}));

关于javascript - 包含 JavaScript 代码而不打包为模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34527056/

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