How to use webpack dynamic import module with npm publish?

Viewed 318

When use Webpack build import() function, It will be build to promise object And publish it to npm,

Use npm i package-name

The dynamic import module will not found, because it path relative 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.

1 Answers

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.

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