首页 > 解决方案 > 为什么汇总会抛出“必须使用导入来加载 ES 模块”?

问题描述

我有以下代码适用于汇总...

// rollup.config.js
import pkg from './package.json';

export default [{
  input: pkg.src,
  external: ['ms'],
  output: [
    {
        file: pkg.main,
        format: 'esm'
    }
  ]
}];

我创建了一个项目来制作简单的 UMD、CJS 和 ESM,所以现在我想制作代码......

import { getMJS } from "@jrg/build"

import pkg from './package.json';

export default [
  getMJS(pkg)
];

但是当我尝试运行它时,我得到......

[!] Error: Must use import to load ES Module: /.../web-components/packages/base/node_modules/@jrg/build/dist/index.mjs
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /.../web-components/packages/base/node_modules/@jrg/build/dist/index.mjs
    at Module.load (internal/modules/cjs/loader.js:1048:11)

我错过了什么?@jrg/build 中的 index.mjs 文件是...

// node_modules/@jrg/index.mjs
import { string } from 'rollup-plugin-string';

const myString = string({
  include: "**/*.(html|css|svg)"
})

const getMJS = function(pkg, plugins){
  plugins = plugins || [ ];
  plugins.push(myString);
  return {
    input: pkg.src,
    plugins: plugins,
    external: ['ms'],
    output: [
      {
        file: pkg.main,
        format: 'esm'
      }
    ]
  }
};
export { getMJS };

更新

因此,如果我使用这样的 CJS 版本,它确实有效......

import * as build from "@jrg/build/dist/index.cjs"

export default [build.getMJS(pkg)];

但是,如果我尝试更改rollup.config.mjs并运行,rollup -c rollup.config.mjs我会得到...

[!] TypeError: defaultLoader is not a function

标签: rollupjs

解决方案


使用相对路径对我来说就像......

import {getMJS, getUMD} from "../../node_modules/@jrg-material/build/dist/index.mjs"

推荐阅读