繁体   English   中英

汇总动态模块解析

[英]Rollup dynamic module resolution

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

这是我的主要文件:

import * as commands from 'command-loader';

console.log(commands);

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

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

Rollup 错误很明显,它不知道如何找到command-loader'command-loader' is imported by ../index.js, but could not be resolved – treating it as an external dependency

我知道我可能只是读取命令文件的内容并将其添加到主文件中,但这感觉很尴尬,因为我必须从命令文件中删除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',
    })
  ]
});

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

知道了: @rollup/plugin-alias

一个 Rollup 插件,用于在捆绑包时定义别名。

这是我最终使用的代码:

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);

成功!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM