javascript - 默认使用 @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 undefined
runmode.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一起导出?
解决方案
推荐阅读
- python - Python:从 pyqt5 拖到文件夹/桌面
- sql - 使用 Azure SQL-db 安排 SQL 查询以将数据从一个表移动到另一个表
- angular - 错误:模块“NgxMatColorPickerModule”导出的意外值“未定义”
- microsoft-graph-api - 从 Microsoft Graph Api 获取 400 错误请求以获取 SchemaExtensions
- node.js - 无法使用 node.js 和 mongodb 以同步方式调用函数
- html - 如果我在父 div 上使用“转换”,则混合混合模式不起作用
- r - 如何通过合并 R 中不同数据框中具有相同名称的列来创建新数据框?
- python - Keras 功能 API 从带有 LSTM 层的 Keras Sequential API 产生不同的结果
- android - 在 okhttp3 中的请求之间创建一秒延迟
- c# - 如何编写一个程序,将平均成绩计算为双值,并在消息框中显示成绩?