簡體   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