babel-plugin-transform-dynamic-import

raw JSON →
2.1.0 verified Sat Apr 25 auth: no javascript

Babel plugin that transpiles dynamic import() expressions to deferred require() calls for Node.js environments. v2.1.0 is the latest stable version, with occasional updates. It matches the proposed spec and requires Babylon >= v6.12.0 to parse dynamic imports correctly. Unlike other Babel dynamic import plugins, this one specifically targets Node.js (not browsers) and defers the require() call to maintain lazy loading semantics.

error SyntaxError: Support for the experimental syntax 'import()' isn't currently enabled
cause Missing or misconfigured Babel plugin for dynamic imports.
fix
Add 'transform-dynamic-import' to your Babel plugins list.
error TypeError: (intermediate value)(...) is not a function
cause Using the plugin with an older version of @babel/core that doesn't support the visitor.
fix
Upgrade @babel/core to version >=7.0.0.
error Error: Cannot find module 'babel-plugin-transform-dynamic-import'
cause Plugin not installed or not in node_modules.
fix
Run 'npm install babel-plugin-transform-dynamic-import --save-dev'
breaking The plugin no longer supports @babel/core versions below 7.0.0 as of v2.0.0.
fix Upgrade @babel/core to version 7.0.0 or later.
deprecated Option 'allowTopLevelThis' has been deprecated in v2.1.0.
fix Remove the option from plugin configuration.
gotcha Dynamic import() is only transformed to require() for Node.js; in browser targets you need a different plugin like @babel/plugin-syntax-dynamic-import or webpack.
fix Use @babel/plugin-transform-modules-commonjs alongside this plugin for full CommonJS transformation.
gotcha The plugin does not polyfill dynamic import; it only transforms syntax. If you use dynamic import in browsers without a bundler, you'll get a runtime error.
fix Use with Webpack or Parcel that handle dynamic imports natively, or include a polyfill like dynamic-import-polyfill.
npm install babel-plugin-transform-dynamic-import
yarn add babel-plugin-transform-dynamic-import
pnpm add babel-plugin-transform-dynamic-import

Configures Babel to transform dynamic import() into deferred require() calls for Node.js.

// .babelrc
{
  "plugins": ["transform-dynamic-import"]
}

// input.js
async function loadModule() {
  const { default: module } = await import('./module');
  return module;
}

// output.js (transpiled for Node)
function loadModule() {
  return Promise.resolve().then(function () {
    return _interopRequireWildcard(require('./module'));
  });
}