CC 4.0 授權

本節內容源自以下連結的內容,並受 CC BY 4.0 授權約束。

如果沒有特別說明,以下內容可以假設為基於原始內容進行修改和刪除的結果。

編譯

此頁面將列出編譯物件上可用的方法和屬性。

注意

在 Rspack 中,真正的編譯物件在 Rust 端運行,而 JavaScript 編譯物件只是一個用來與 Rust 編譯物件通訊的代理物件

因此,某些複雜的資料結構和方法將在 JavaScript 編譯物件上不支援,資料是唯讀的,並且結構可能與 webpack 不同。

編譯方法

emitAsset

發出一個新的資源,如果該資源已存在,則拋出錯誤。

emitAsset(
  filename: string, // filename of the new asset
  source: Source, // content of the new asset
  info?: AssetInfo // asset info of the new asset
): void;

以下程式碼將新增一個名為 asset-name.js 的新資源,並且不會被壓縮

compiler.hooks.thisCompilation.tap('MyPlugin', compilation => {
  const { RawSource } = compiler.webpack.sources;
  compilation.hooks.processAssets.tap('MyPlugin', () => {
    const buffer = Buffer.from(
      'i am content of emit asset, do not minimize me',
    );
    const source = new RawSource(buffer, false);
    compilation.emitAsset('asset-name.js', source, {
      minimized: true,
    });
  });
});

updateAsset

更新現有的資源,如果該資源不存在,則拋出錯誤。

updateAsset(
  filename: string, // filename of the updating asset
  source: Source | ((source: Source) => Source), // the new content or a function returns the new content
  info?:  // the new info or a function returns the new info
    | AssetInfo
    | ((assetInfo: AssetInfo) => AssetInfo)
): void;

以下程式碼將替換 main.js 的內容,並且不會縮小它

compiler.hooks.thisCompilation.tap('MyPlugin', compilation => {
  const { RawSource } = compiler.webpack.sources;
  compilation.hooks.processAssets.tap('MyPlugin', () => {
    const updatedSource = new RawSource(
      `module.exports = "This is the updated"`,
    );
    compilation.updateAsset('main.js', updatedSource, {
      minimized: true,
    });
  });
});

renameAsset

重新命名現有的資源。

renameAsset(
  filename: string, // filename of the renaming asset
  newFilename: string // new filename
): void;

以下程式碼將名為 main.js 的資源重新命名為 my-asset-name.js

compiler.hooks.thisCompilation.tap('MyPlugin', compilation => {
  compilation.hooks.processAssets.tap('MyPlugin', () => {
    compilation.renameAsset('main.js', 'my-asset-name.js');
  });
});

deleteAsset

刪除現有的資源。

deleteAsset(
  filename: string // filename of the deleting asset
): void;

以下程式碼將刪除名為 no-need.js 的資源

compiler.hooks.thisCompilation.tap('MyPlugin', compilation => {
  compilation.hooks.processAssets.tap('MyPlugin', () => {
    compilation.deleteAsset('no-need.js');
  });
});

getAssets

取得資源物件的清單。

getAssets(): ReadonlyArray<{
  filename: string;
  source: Source;
  info: AssetInfo;
}>;

以下程式碼將列印所有資源的總大小

compiler.hooks.compilation.tap('MyPlugin', compilation => {
  compilation.hooks.processAssets.tap('MyPlugin', () => {
    const assets = compilation.getAssets();
    const totalSize = assets.reduce(
      (total, asset) => total + asset.source.size(),
      0,
    );
    console.log(`total size: ${totalSize}`);
  });
});

getAsset

取得具有指定名稱的資源物件。

getAsset(
  filename: string // filename of the getting asset
): Readonly<{
  filename: string;
  source: Source;
  info: AssetInfo;
}> | void;

以下程式碼將列印名為 main.js 的資源的大小

compiler.hooks.compilation.tap('MyPlugin', compilation => {
  compilation.hooks.processAssets.tap('MyPlugin', () => {
    const assetSize = compilation.getAsset('main.js')?.source.size();
    console.log(`main size: ${assetSize}`);
  });
});

getPath

根據檔案名稱模板產生路徑字串,有關模板規則,請參閱模板字串

getPath(
  filename: Filename, // filename template
  data: PathData = {} // generating path data
): string;

以下程式碼將替換模板中的預留位置以產生路徑

const path = compilation.getPath('[contenthash]-[fullhash].js', {
  contentHash: 'some1',
  hash: 'some2',
});
console.log(path); // "some1-some2.js"

getPathWithInfo

根據檔案名稱模板產生路徑字串和資源資訊,請參閱模板字串

getPathWithInfo(
  filename: Filename, // filename template
  data: PathData = {} // generating path data
): {
  path: string;
  info: AssetInfo;
};

以下程式碼將替換模板中的預留位置以產生路徑和資源資訊

const { path, info } = compilation.getPathWithInfo(
  '[contenthash]-[fullhash].js',
  {
    contentHash: 'some1',
    hash: 'some2',
  },
);
console.log(path); // "some1-some2.js"
console.log(info);
/* Object {
  immutable: true,
  minimized: false,
  fullhash: [ 'some2' ],
  chunkhash: [],
  contenthash: [ 'some1' ],
  development: false,
  hotModuleReplacement: false,
  related: {},
  extras: {}
} */

getStats

取得目前編譯的統計物件

getStats(): Stats;

以下程式碼會列印模組的總數

compiler.hooks.emit.tapAsync('MyPlugin', compilation => {
  const modules = compilation.getStats().toJson({ modules: true }).modules;
  console.log(`Total modules: ${modules.length}`);
});

createChildCompiler

允許在 Rspack 內部執行另一個 Rspack 實例。然而,作為具有不同設定和配置的子程序。它會複製父級(或頂級編譯器)的所有鉤子和外掛,並建立一個子 Compiler 實例。傳回建立的 Compiler

createChildCompiler(
  name: string, // name for the child `Compiler`
  outputOptions: OutputNormalized, // Output options object
  plugins: RspackPluginInstance[] // Plugins that will be applied
): Compiler;

以下程式碼將啟動一個以 child-entry.js 作為入口點的子編譯器,並輸出到 dist/child

compiler.hooks.make.tap('MyPlugin', compilation => {
  const childCompiler = compilation.createChildCompiler(
    'ChildCompiler',
    {
      path: 'dist/child',
    },
    [new compiler.webpack.EntryPlugin(compiler.context, './child-entry.js')],
  );
  childCompiler.compile((err, childCompilation) => {});
});

addRuntimeModule

將自訂執行期模組新增到編譯中。

addRuntimeModule(
  c: Chunk, // the runtime chunk which to add the runtime module
  m: RuntimeModule, // the runtime module instance to add
): void;

以下程式碼將新增一個執行期模組,該模組將 __webpack_require__.mock 定義到 "main" 區塊

rspack.config.js
module.exports = {
  entry: './index.js',
  plugins: [
    {
      apply(compiler) {
        const { RuntimeModule } = compiler.webpack;

        class CustomRuntimeModule extends RuntimeModule {
          constructor() {
            super('custom');
          }

          generate() {
            const compilation = this.compilation;
            return `
            __webpack_require__.mock = function() {
              // ...
            };
          `;
          }
        }

        compiler.hooks.thisCompilation.tap('CustomPlugin', compilation => {
          compilation.hooks.runtimeRequirementInTree
            .for(RuntimeGlobals.ensureChunkHandlers)
            .tap('CustomPlugin', (chunk, set) => {
              if (chunk.name === 'main') {
                compilation.addRuntimeModule(chunk, new CustomRuntimeModule());
              }
            });
        });
      },
    },
  ],
};

在實作自訂執行期模組類別時,可以覆寫以下方法/屬性來控制執行期模組的行為

  • 在建構函式中傳遞 namestage 參數以指定模組名稱和插入階段。
  • 覆寫 generate() 方法以控制模組的產生程式碼。
  • 覆寫 shouldIsolate() 方法以控制模組是否包裝在 IIFE 中。
  • 覆寫 attach() 方法以修改新增模組時的行為。
  • 修改其 fullHashdependentHash 屬性以控制是否可以快取模組。

rebuildModule

觸發模組的重新建置。

rebuildModule(
  m: Module, // module to be rebuilt
  f: (err: Error, m: Module) => void //  function to be invoked when the module finishes rebuilding
): void;

以下程式碼將重新建置以 a.js 結尾的模組

compiler.hooks.compilation.tap('MyPlugin', compilation => {
  compilation.hooks.finishModules.tapPromise('MyPlugin', async modules => {
    const oldModule = Array.from(modules).find(item =>
      item.resource.endsWith('a.js'),
    );
    compilation.rebuildModule(oldModule, (err, m) => {
      console.log(`Rebuilt ${m.identifier()}.`);
    });
  });
});

getLogger

取得具有指定名稱的日誌輸出工具物件,該物件可用於在外掛中列印具有統一格式的日誌。

getLogger(name: string | (() => string)): Logger;

以下程式碼會將資源列印到 processAssets 中的除錯日誌

compiler.hooks.compilation.tap('MyPlugin', compilation => {
  const logger = compilation.getLogger('MyPlugin');

  compilation.hooks.processAssets.tap('MyPlugin', () => {
    for (const asset of compilation.getAssets()) {
      logger.debug(`asset name: ${asset.name}`);
      logger.debug(`asset info: ${asset.info}`);
    }
  });
});

getCache

取得具有指定名稱的快取物件,該物件可用於外掛在多次編譯期間共用資料。

getCache(name: string): CacheFacade;

編譯屬性

options

類型: RspackOptionsNormalized

此編譯使用的正規化選項,有關詳細資訊,請參閱設定 Rspack

compiler

類型: Compiler

目前的編譯器物件

hooks

編譯鉤子

hash/fullhash

類型: Readonly<string | null>

此編譯的雜湊值。

assets

類型: Record<string, Source>

從資源檔案名稱到內容來源的對應。

chunkGroups

類型: ReadonlyArray<ChunkGroup>

區塊群組物件的清單,結構如下

entrypoints

類型: ReadonlyMap<string, Entrypoint>

從名稱到入口點的對應,這是一個特殊的區塊群組,包括執行期區塊。

namedChunkGroups

類型: ReadonlyMap<string, Readonly<ChunkGroup>>

從名稱到區塊群組的對應。

modules

類型: ReadonlySet<Module>

所有模組的清單,結構如下

builtModules

類型: ReadonlySet<Module>

未被快取的建置模組清單,結構如下

chunks

類型: ReadonlySet<Chunk>

所有程式碼區塊的列表,結構如下

namedChunks

類型: ReadonlyMap<string, Readonly<Chunk>>

從名稱到程式碼區塊的映射。

fileDependencies

類型: CompilationDependencies

此編譯所依賴的檔案列表。

contextDependencies

類型: CompilationDependencies

此編譯所依賴的目錄列表。

missingDependencies

類型: CompilationDependencies

此編譯所依賴的不存在的檔案列表。

buildDependencies

類型: CompilationDependencies

此編譯所依賴的建置依賴列表。

errors

類型: RspackError[]

此編譯期間發出的錯誤列表,結構如下

warnings

類型: RspackError[]

此編譯期間發出的警告列表。