【问题标题】:Import ES Modules from CommonJS dynamically从 CommonJS 动态导入 ES 模块
【发布时间】:2020-07-28 01:26:04
【问题描述】:

是否可以从 CommonJS 动态导入 ES 模块而无需将文件扩展名更改为 mjs 并且如果可能的话使用旧的 Node 版本(早于 V13)?我正在创建一个 CLI 库,它将从用户项目中动态导入文件,以根据这些文件自动生成一些代码。

// bin.ts
// This file will be transpiled to CommonJS
const loadResourceFile = async (url: string) => {
  const resource = await import(url);
  return resource.default;
}
...
// rollup.config.js
import typescript from 'rollup-plugin-typescript2';
import pkg from './package.json';

const commonOutputOptions = {
  banner: '#!/usr/bin/env node',
  preferConst: true,
  sourcemap: true,
};

export default {
  input: 'src/bin.ts',
  output: [
    {
      ...commonOutputOptions,
      file: pkg.main,
      format: 'cjs',
    },
    {
      ...commonOutputOptions,
      file: pkg.module,
      format: 'esm',
    },
  ],
  external: [...Object.keys(pkg.dependencies || {})],
  plugins: [typescript()],
  inlineDynamicImports: true,
};

// resource.js
// This file will be a ES module
import a from './a';

export default {
   a,
   b: 'y',
}

提前谢谢你!

【问题讨论】:

    标签: javascript node.js typescript rollup


    【解决方案1】:

    这是可能的,使用vm(特别是this)和fs虽然我建议不要走这条路,因为如果你不小心,它很快就会变得无法维护。

    由于您的目标是同时支持较旧的 nodejs 版本,我建议您制作两个单独的包,这样您就不会混合 CommonJS 和 ES 模块。

    【讨论】:

      猜你喜欢
      • 2021-11-20
      • 2021-12-02
      • 2021-04-07
      • 2020-10-06
      • 2021-08-24
      • 2018-06-22
      • 2020-09-13
      • 1970-01-01
      • 2022-01-20
      相关资源
      最近更新 更多