简体   繁体   English

如何在 npm 发布中使用 webpack 动态导入模块?

[英]How to use webpack dynamic import module with npm publish?

When use Webpack build import() function, It will be build to promise object And publish it to npm,当使用 Webpack 构建 import() 函数时,它会构建到 promise 对象并发布到 npm,

Use npm i package-name使用 npm i 包名

The dynamic import module will not found, because it path relative node_modules/pacage-name找不到动态导入模块,因为它路径相对 node_modules/pacage-name

How to resolve this question?如何解决这个问题?

I hope the import function don't transform to promise, but still build the dynamic module.我希望 import 函数不要转换为 promise,但仍然构建动态模块。

I stated in the comments that you probably have the wrong approach and should look at ES modules to ensure your final build is tree shakable instead, but alongside that you might still want to lazy load some parts of your package in a project.我在评论中指出,您可能采用了错误的方法,应该查看 ES 模块以确保您的最终构建是可摇动树的,但除此之外,您可能仍然希望在项目中延迟加载包的某些部分。

You can still do that on the consumer of the package:您仍然可以对包的使用者执行此操作:

// 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";

And on your consumer project (the one that controls the bundler)以及您的消费者项目(控制打包程序的项目)

// 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM