【问题标题】:How to use webpack dynamic import module with npm publish?如何在 npm publish 中使用 webpack 动态导入模块?
【发布时间】:2021-09-22 04:35:12
【问题描述】:

当使用 Webpack 构建 import() 函数时,它会被构建为 promise 对象 并将其发布到 npm,

使用 npm i 包名

找不到动态导入模块,因为它的路径相对于 node_modules/pacage-name

如何解决这个问题?

希望导入功能不要转成promise,还是要构建动态模块。

【问题讨论】:

  • 你能用例子或回购改进你的问题吗?
  • 我认为您的想法有误。如果你正在做一个包,你不应该在你的最终构建中做任何应该知道捆绑器的事情,相反你应该确保你的代码是可摇树的,你可以通过将它变成一个 ES 模块来实现这一点。这篇文章解释的很好dev.to/lukasbombach/…

标签: node.js webpack frontend


【解决方案1】:

我在 cmets 中指出,您可能采用了错误的方法,应该查看 ES 模块以确保您的最终构建是可摇树的,但除此之外,您可能仍希望在项目中延迟加载包的某些部分。

您仍然可以对包的使用者执行此操作:

// sum method
export function sum(a, b) {
 return a + b;
}
// subtract method
export function subtract(a, b) {
 return a - b;
}
// entry file of my-lib
export { sum } from "./location/of/sum";
export { subtract } from "./location/of/subtract";

在您的消费者项目(控制捆绑器的项目)上

// lazySum.js
export function lazySum(...args) {
  return import("my-lib/location/of/sum")
    .then(({ sum }) => {
      return sum(...args)
    })
    .catch((error) => "An error occurred while loading the sum method");
}
// index.js
import { lazySum } from "./lazySum";

const a = lazySum(1, 2);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-21
    • 2016-04-21
    • 2020-02-14
    • 2021-10-14
    • 2019-09-04
    • 2020-02-16
    • 1970-01-01
    • 2019-02-19
    相关资源
    最近更新 更多