gpt4 book ai didi

javascript - Rollup动态模块解析

转载 作者:行者123 更新时间:2023-12-02 22:23:48 25 4
gpt4 key购买 nike

我正在尝试使用 Rollup将一些 JS 捆绑到一个文件中。然而,我想要导入的文件之一的路径仅在编译时才知道,因此我需要告诉 Rollup 如何找到它。

这是我的主文件:

import * as commands from 'command-loader';

console.log(commands);

您可以看到它正在从 command-loader 导入所有内容。文件的名称和内容并不重要,我只需要将其内容捆绑到主文件中即可。该文件看起来像:

export function exampleCommand() {
console.log('Running command...');
}

Rollup 错误非常明显,它不知道如何找到 command-loader:'command-loader' 由 ../index.js 导入,但无法已解决 - 将其视为外部依赖项

我知道我可能只需读取命令文件的内容并将其添加到主文件中,但这感觉很尴尬,因为我必须从命令文件中删除 export 并且定义一个“命令”对象,这可能违背了 Rollup 的目的。

我尝试过使用 rollup-plugin-node-resolve告诉 Rollup 如何找到 command-loader,但它似乎不起作用(当然,我不太了解这个插件)。

const rollup = require('rollup');
const resolve = require('rollup-plugin-node-resolve');

await rollup.rollup({
input: mainFilePath,
plugins: [
resolve({
'command-loader': dynamicFilePath
})
]
});

我也尝试过使用 rollup-plugin-bundle-imports没有效果。

const rollup = require('rollup');
const { bundleImports } = require('rollup-plugin-bundle-imports');

await rollup.rollup({
input: mainFilePath,
plugins: [
bundleImports({
include: [dynamicFilePath],
importAs: 'command-loader',
})
]
});

也许我采取了错误的方法。如果有更好的方法在编译时动态导入文件,我很想了解它。

最佳答案

知道了:@rollup/plugin-alias

A Rollup plugin for defining aliases when bundling packages.

这是我最终使用的代码:

const rollup = require('rollup');
const alias = require('@rollup/plugin-alias');

await rollup.rollup({
input: mainFilePath,
plugins: [
alias({
entries: {
'command-loader': dynamicFilePath
}
})
]
});

结合 CJS 输出格式,解析上面的示例代码并产生:

'use strict';

function exampleCommand() {
console.log('Running command...');
}

var commands = /*#__PURE__*/Object.freeze({
__proto__: null,
exampleCommand: exampleCommand
});

console.log(commands);

成功!

关于javascript - Rollup动态模块解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59132170/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com