首页 > 解决方案 > 默认使用 @rollup/plugin-commonjs 从 CJS 模块导入导出

问题描述

我正在使用为 cjs 编写的 javascript 库。我还使用@rollup/plugin-commonjs 来转换该库,以便我可以导入它。

// a file I want to import from cjs library
exports.x = 5
// rollup.config.js
resolve({
  browser: true,
  dedupe: ['svelte'],
  preferBuiltins: false,
}),
commonjs({
  include: [
    "node_modules/**",
  ],
  dynamicRequireTargets: [  
    "node_modules/cjs-lib/**",
  ],
}),

我正在尝试在我自己的应用程序中使用它。

import lib from "cjs-lib/file.js"
lib.z = function() {
  return lib.x + 5;
}

那里发生了一个问题,与

Uncaught TypeError: lib.x is not a function

似乎所有在 cjs 库中定义的方法exports.x在导入时都是未定义的。

无论如何要配置@rollup/plugin-commonjs使exports最初在 cjs 库中的对象在我的应用程序中导入时成为默认导出对象?

编辑:

更具体地说,我正在使用的确切库是 CodeMirror,我正在尝试使用它的插件,runmode/runmode.node.js.

import CodeMirror from 'codemirror/addon/runmode/runmode.node';
import 'codemirror/mode/meta';

// Try to extend it here, but findModeByExtension is undefined.
CodeMirror.findMode = function (mode) {
    return mode && (CodeMirror.findModeByExtension(mode) ||
        CodeMirror.findModeByFileName(mode) ||
        CodeMirror.findModeByName(mode) ||
        CodeMirror.findModeByMIME(mode) ||
        CodeMirror.findModeByMode(mode));
};

使用 rollup,CodeMirror导入的对象是空的,{}. 但是对于 webpack,该CodeMirror对象包含分配给它的所有方法exports.x = y以及文件exports[a] = b中的所有方法runmode.node.js

编辑:

令人惊讶的是,如果在 中导入库rollup.config.js,则导入的对象不是空的,并且包含所有预期的方法。

// rollup.config.js
import * as CodeMirror from "codemirror/addon/runmode/runmode.node"
console.log("CodeMirror", CodeMirror);

runmode [Object: null prototype] {
  StringStream: [Getter],
  countColumn: [Getter], ...

编辑

就目前而言,我的rollup.config.js文件有

        commonjs({
            include: "node_modules/**",
            dynamicRequireTargets: ["node_modules/codemirror/**"],
        }),

如果不包含codemirror在 中,当涉及到 中的这些行时dynamicRequireTargets,它会导致错误:require is undefinedrunmode.node.js

require.cache[require.resolve("../../lib/codemirror")] = require.cache[require.resolve("./runmode.node")];
require.cache[require.resolve("../../addon/runmode/runmode")] = require.cache[require.resolve("./runmode.node")];

dynamicRequireTargets似乎通过将整个文件包装在这个

const commonjsRegister = require('commonjsHelpers.js?commonjsRegister');
commonjsRegister("/$$rollup_base$$/node_modules/codemirror/addon/runmode/runmode.node.js", function (module, exports) {
  'use strict';
  // runmode.node.js
}

但是,这会删除所有导出,因此会删除空导入。有没有办法dynamicRequireTargets和cjs一起导出?

标签: javascriptcommonjsrollupjs

解决方案


推荐阅读