CC 4.0 许可

本节内容来自以下链接,并受 CC BY 4.0 许可。

除非另有说明,以下内容可以被认为是基于原始内容的修改和删除的结果。

输出

顶级输出键包含一组选项,指示 Rspack 如何以及在何处输出您的包、资产以及您使用 Rspack 捆绑或加载的任何其他内容。

  • 类型: Object

output.assetModuleFilename

  • 类型: string | ((pathData: PathData, assetInfo?: JsAssetInfo) => string)
  • 默认: '[hash][ext][query]'

output.filename 相同,但针对 资产模块

对于从 data URI 替换构建的资产,[name][file][query][fragment][base][path] 设置为空字符串。

资产模块要输出的文件名。此值可以被 Rule.generator.filename 覆盖。

资产模块输出为单独的文件

output.asyncChunks

  • 类型: boolean
  • 默认: true

创建按需加载的异步块。

output.charset

  • 类型: boolean
  • 默认: true

charset="utf-8" 添加到 HTML <script> 标签。

提示

尽管 <script> 标签的 charset 属性已 弃用,但 Rspack 仍然默认添加它以与非现代浏览器兼容。

output.chunkFilename

  • 类型: string = '[id].js' | (pathData: PathData, assetInfo?: JsAssetInfo) => string
  • 默认:output.filename 不是函数时由其决定,否则为 '[id].js'

此选项确定非初始块文件的名称。有关可能值的详细信息,请参阅 output.filename 选项。

请注意,这些文件名需要在运行时生成才能发送块请求。因此,像 [name][chunkhash] 这样的占位符需要使用 Rspack 运行时将从块 ID 到占位符值的映射添加到输出包中。这会增加大小,并且当任何块的占位符值发生变化时可能会使包失效。

默认情况下,使用 [id].js 或从 output.filename 推断的值([name] 被替换为 [id][id]. 被添加在前面)。

rspack.config.js
module.exports = {
  //...
  output: {
    //...
    chunkFilename: '[id].js',
  },
};

用作函数

rspack.config.js
module.exports = {
  //...
  output: {
    chunkFilename: pathData => {
      return pathData.chunk.name === 'main' ? '[name].js' : '[name]/[name].js';
    },
  },
};

output.chunkFormat

  • 类型: false | 'array-push' | 'commonjs' | 'module' | string
  • 默认:targetoutput.module 决定

块的格式(默认包含的格式为 'array-push'(web/webworker)、'commonjs'(node.js)、'module'(ESM),但其他格式可能由插件添加)。

提示

此选项的默认值取决于 targetoutput.module 设置。有关更多详细信息,请在 Rspack 默认值中搜索“chunkFormat”

rspack.config.js
module.exports = {
  output: {
    chunkFormat: 'commonjs',
  },
};

output.chunkLoadTimeout

  • 类型: number
  • 默认值: 120000

块请求超时之前的毫秒数。

rspack.config.js
module.exports = {
  //...
  output: {
    //...
    chunkLoadTimeout: 30000, // 30 seconds before chunk request timed out.
  },
};

output.chunkLoadingGlobal

Rspack 用于加载块的全局变量。

rspack.config.js
module.exports = {
  output: {
    chunkLoadingGlobal: 'myCustomFunc',
  },
};

output.chunkLoading

  • 类型: false | 'jsonp' | 'import-scripts' | 'require' | 'async-node' | 'import'

加载块的方法(默认包含的方法是 'jsonp'(web)、'import'(ESM)、'importScripts'(webworker)、'require'(同步 node.js)、'async-node'(异步 node.js),但其他方法可能会由插件添加)。默认值将根据 targetchunkFormat 的配置确定。

提示

此选项的默认值取决于 targetchunkFormat 设置。有关更多详细信息,请在 Rspack 默认值中搜索 "chunkLoading"

rspack.config.js
module.exports = {
  output: {
    chunkLoading: 'async-node',
  },
};

output.clean

  • 类型: boolean
  • 默认值: false

在生成产品之前,删除输出目录中的所有文件。

rspack.config.js
module.exports = {
  //...
  output: {
    clean: true, // Clean the output directory before emit.
  },
};

output.compareBeforeEmit

  • 类型: boolean
  • 默认: true

告诉 Rspack 在写入输出文件系统之前检查要发射的文件是否已存在并且具有相同的内容。

警告

当文件已存在于磁盘上并且具有相同的内容时,Rspack 不会写入输出文件。

rspack.config.js
module.exports = {
  //...
  output: {
    compareBeforeEmit: false,
  },
};

output.crossOriginLoading

  • 类型: false | 'anonymous' | 'use-credentials'
  • 默认值: false

crossOriginLoading 配置允许您为动态加载的块设置 crossorigin 属性

如果 target'web',Rspack 将动态创建 <script><link> 标签以加载异步 JavaScript 和 CSS 资源。如果这些资源的 URL 在其他域上,并且 crossOriginLoading 不是 false,Rspack 将在 <script><link> 标签中添加 crossorigin 属性。

可选值

crossOriginLoading 具有以下可选值

  • false:不设置 crossorigin 属性
  • 'anonymous':将 crossorigin 设置为 'anonymous' 以在没有用户凭据的情况下启用跨源。
  • 'use-credentials':将 crossorigin 设置为 'use-credentials' 以使用用户凭据启用跨源。

示例

例如,将 output.publicPath 设置为 https://example.com/,并将 output.crossOriginLoading 设置为 'anonymous'

rspack.config.js
const path = require('path');

module.exports = {
  output: {
    publicPath: 'https://example.com/',
    crossOriginLoading: 'anonymous',
  },
};

当 Rspack 动态加载 JavaScript 资源时,它将生成以下 HTML

<script src="https://example.com/foo.js" crossorigin="anonymous"></script>

output.cssChunkFilename

  • 类型: string | (pathData: PathData, assetInfo?: JsAssetInfo) => string
  • 默认值: 当它不是函数时,由 output.chunkFilename 决定,否则为 '[id].css'

此选项确定磁盘上非初始 CSS 输出文件的名称。有关可能值的详细信息,请参见 output.filename 选项。

不得在此处指定绝对路径。但是,您可以随意包含由 '/' 分隔的文件夹。此指定路径与 output.path 值相结合,以精确确定磁盘上的位置。

output.cssFilename

  • 类型: string | (pathData: PathData, assetInfo?: JsAssetInfo) => string
  • 默认值:output.filename 决定

此选项确定磁盘上 CSS 输出文件的名称。有关可能值的详细信息,请参见 output.filename 选项。

不得在此处指定绝对路径。但是,您可以随意包含由 '/' 分隔的文件夹。此指定路径与 output.path 值相结合,以精确确定磁盘上的位置。

output.devtoolFallbackModuleFilenameTemplate

  • 类型: string | function (info)
  • 默认值: undefined

当上面的模板字符串或函数产生重复时,使用回退。

参见 output.devtoolModuleFilenameTemplate

output.devtoolModuleFilenameTemplate

  • 类型: string = 'webpack://[namespace]/[resource-path]?[loaders]' | function (info) => string
  • 默认值: undefined

此选项仅在 devtool 使用需要模块名称的选项时使用。

自定义每个源映射的 sources 数组中使用的名称。这可以通过传递模板字符串或函数来完成。例如,当使用 devtool: 'eval' 时。

rspack.config.js
module.exports = {
  //...
  output: {
    devtoolModuleFilenameTemplate:
      'webpack://[namespace]/[resource-path]?[loaders]',
  },
};

以下替换在模板字符串中可用

模板 描述
[absolute-resource-path] 绝对文件名
[all-loaders] 自动和显式加载器以及参数,直到第一个加载器的名称
[hash] 模块标识符的哈希值
[id] 模块标识符
[loaders] 显式加载器以及参数,直到第一个加载器的名称
[resource] 用于解析文件和第一个加载器上使用的任何查询参数的路径
[resource-path] 用于解析文件而没有任何查询参数的路径
[namespace] 模块命名空间。这通常是作为库构建时的库名称,否则为空

当使用函数时,相同的选项通过 info 参数以骆驼大小写形式提供

rspack.config.js
module.exports = {
  //...
  output: {
    devtoolModuleFilenameTemplate: info => {
      return `webpack:///${info.resourcePath}?${info.loaders}`;
    },
  },
};

如果多个模块会导致相同的名称,则 output.devtoolFallbackModuleFilenameTemplate 将用于这些模块。

output.devtoolNamespace

  • 类型: string
  • 默认值: undefined

此选项确定与 output.devtoolModuleFilenameTemplate 一起使用的模块的命名空间。当未指定时,它将默认为以下值:output.uniqueName。它用于在加载使用 Rspack 构建的多个库时,防止源映射中的源文件路径冲突。

例如,如果您有两个库,其命名空间分别为 library1library2,它们都具有文件 ./src/index.js(可能具有不同的内容),它们将公开这些文件作为 webpack://library1/./src/index.jswebpack://library2/./src/index.js

output.enabledChunkLoadingTypes

入口点可以使用的一组启用用于使用的块加载类型。将由 Rspack 自动填充。仅在使用函数作为入口选项并在其中返回 chunkLoading 选项时才需要。

rspack.config.js
module.exports = {
  //...
  output: {
    enabledChunkLoadingTypes: ['jsonp', 'require'],
  },
};

output.enabledLibraryTypes

入口点可以使用的一组启用用于使用的库类型。

rspack.config.js
module.exports = {
  //...
  output: {
    enabledLibraryTypes: ['module'],
  },
};

output.enabledWasmLoadingTypes

入口点可以使用的一组启用用于使用的 Wasm 加载类型。

rspack.config.js
module.exports = {
  //...
  output: {
    enabledWasmLoadingTypes: ['fetch'],
  },
};

output.environment

告诉 Rspack 在生成的运行时代码中可以使用哪种 ES 功能。

rspack.config.js
module.exports = {
  output: {
    environment: {
      // The environment supports arrow functions ('() => { ... }').
      arrowFunction: true,
      // The environment supports async function and await ('async function () { await ... }').
      asyncFunction: true,
      // The environment supports BigInt as literal (123n).
      bigIntLiteral: false,
      // The environment supports const and let for variable declarations.
      const: true,
      // The environment supports destructuring ('{ a, b } = obj').
      destructuring: true,
      // The environment supports 'document' variable.
      document: true,
      // The environment supports an async import() function to import EcmaScript modules.
      dynamicImport: false,
      // The environment supports an async import() when creating a worker, only for web targets at the moment.
      dynamicImportInWorker: false,
      // The environment supports 'for of' iteration ('for (const x of array) { ... }').
      forOf: true,
      // The environment supports 'globalThis'.
      globalThis: true,
      // The environment supports ECMAScript Module syntax to import ECMAScript modules (import ... from '...').
      module: false,
      // Determines if the node: prefix is generated for core module imports in environments that support it.
      // This is only applicable to Webpack runtime code.
      nodePrefixForCoreModules: false,
      // The environment supports optional chaining ('obj?.a' or 'obj?.()').
      optionalChaining: true,
      // The environment supports template literals.
      templateLiteral: true,
    },
  },
};

output.filename

  • 类型: string | (pathData: PathData, assetInfo?: JsAssetInfo) => string
  • 默认值:[output.module](#outputmodule)true 时,它为 '[name].mjs',否则为 '[name].js'

此选项确定每个输出捆绑包的名称。捆绑包被写入由 output.path 选项指定的目录。

对于单个 entry 点,这可以是静态名称。

rspack.config.js
module.exports = {
  output: {
    filename: 'bundle.js',
  },
};

但是,当通过多个入口点、代码拆分或各种插件创建多个捆绑包时,您应该使用以下替换之一来为每个捆绑包指定唯一的名称...

对多个捆绑包可以拆分的其他情况的描述

Rspack 对用户输入代码执行代码拆分优化,其中可能包括但不限于代码拆分、捆绑拆分或通过其他插件实现的拆分。这些拆分操作会导致生成多个捆绑包,因此捆绑包的文件名需要动态生成。

使用 Entry 名称

rspack.config.js
module.exports = {
  //...
  output: {
    filename: '[name].bundle.js',
  },
};

使用内部块 ID

rspack.config.js
module.exports = {
  //...
  output: {
    filename: '[id].bundle.js',
  },
};

使用从生成内容生成的哈希值

rspack.config.js
module.exports = {
  //...
  output: {
    filename: '[contenthash].bundle.js',
  },
};

组合多个替换

rspack.config.js
module.exports = {
  //...
  output: {
    filename: '[name].[contenthash].bundle.js',
  },
};

使用函数返回文件名

rspack.config.js
module.exports = {
  //...
  output: {
    filename: pathData => {
      return pathData.chunk.name === 'main' ? '[name].js' : '[name]/[name].js';
    },
  },
};

请注意,此选项称为 filename,但您仍然可以使用 'js/[name]/bundle.js' 之类的东西来创建文件夹结构。

请注意,此选项不会影响按需加载的块的输出文件。它只会影响最初加载的输出文件。对于按需加载的块文件,将使用 output.chunkFilename 选项。加载器创建的文件也不受影响。在这种情况下,您需要尝试特定加载器提供的选项。

模板字符串

下面的模板字符串可用于替换相应的文件名。不同的上下文对应不同的可替换内容,例如 output.assetModuleFilename 支持使用 文件上下文模块上下文

编译上下文

可在编译级别替换的内容。

模板 描述
[fullhash] 编译的完整哈希值

块上下文

可在块级别替换的内容。

模板 描述
[id] 当前块 ID
[name] 当块名称存在时使用名称,否则使用块 ID
[chunkhash] 块的哈希值,根据当前块中所有类型元素计算得出
[contenthash] 块的哈希值,根据仅包含该类型内容的元素计算得出。例如,如果生成了类型为 JavaScript 的模块,则仅使用当前块中所有 JavaScript 类型模块的哈希值。

模块上下文

可在模块级别替换的内容。

模板 描述
[id] 模块 ID
[hash] 模块的哈希值
[contenthash] 模块内容的哈希值

文件上下文

可在文件级别替换的内容。

模板 描述
[file] 文件名和路径,不含查询或片段
[query] 带前导 ? 的查询
[fragment] 带前导 # 的片段
[base] 仅文件名(含扩展名),不含路径
[filebase] 相同,但已弃用
[path] 仅路径,不含文件名
[name] 仅文件名,不含扩展名或路径
[ext] 带前导 . 的扩展名(对于 output.filename 不可使用)

URL 级别的可用替换

模板 描述
[url] URL
提示

[file] 等于 [path][base][base] 等于 [name][ext]。完整路径为 [path][name][ext][query][fragment][path][base][query][fragment][file][query][fragment]

哈希值([hash][contenthash][chunkhash])的长度可以使用 [hash:12] 指定(默认值为 16)。或者,指定 output.hashDigestLength 来全局配置长度。

当您想要在实际文件名中使用占位符时,可以过滤掉占位符替换。例如,要输出文件 [name].js,您必须通过在方括号之间添加反斜杠来转义 [name] 占位符。这样 [\name\] 将生成 [name],而不是被替换为资源的 name

例如:[\id\] 将生成 [id],而不是被替换为 id

如果为此选项使用函数,则该函数将传递一个包含上述表格中替换数据的对象。替换也将应用于返回的字符串。传递的对象将具有以下类型:(属性根据上下文可用)

type PathData = {
  hash: string;
  hashWithLength: (number) => string;
  chunk: Chunk | ChunkPathData;
  module: Module | ModulePathData;
  contentHashType: string;
  contentHash: string;
  contentHashWithLength: (number) => string;
  filename: string;
  url: string;
  runtime: string | SortableSet<string>;
  chunkGraph: ChunkGraph;
};
type ChunkPathData = {
  id: string | number;
  name: string;
  hash: string;
  hashWithLength: (number) => string;
  contentHash: Record<string, string>;
  contentHashWithLength: Record<string, (number) => string>;
};
type ModulePathData = {
  id: string | number;
  hash: string;
  hashWithLength: (number) => string;
};

output.globalObject

  • 类型: string
  • 默认值: 'self'

当面向库(尤其是当 library.type'umd' 时),此选项指示将使用哪个全局对象来挂载库。为了使 UMD 构建在浏览器和 Node.js 上都可用,请将 output.globalObject 选项设置为 'this'。对于类似 Web 的目标,默认为 self

您的入口点的返回值将使用 output.library.name 的值分配给全局对象。根据 type 选项的值,全局对象可能会相应地更改,例如 selfglobalglobalThis

例如

rspack.config.js
module.exports = {
  // ...
  output: {
    library: 'myLib',
    libraryTarget: 'umd',
    filename: 'myLib.js',
    globalObject: 'this',
  },
};

output.hashDigest

  • 类型: string
  • 默认值: 'hex'

生成哈希值时使用的编码。对于文件名,使用 'base64' 可能有问题,因为它在字母表中包含字符 /。同样,'latin1' 可能包含任何字符。

output.hashDigestLength

  • 类型: number
  • 默认值: 16

要使用的哈希摘要的前缀长度。

output.hashFunction

  • 类型: 'md4' | 'xxhash64'
  • 默认值: 'xxhash64'

要使用的哈希算法。

rspack.config.js
module.exports = {
  //...
  output: {
    hashFunction: 'xxhash64',
  },
};
提示

Rspack 从 v1.1 开始默认使用更快的 xxhash64 算法。

output.hashSalt

  • 类型: string
  • 默认值: undefined

用于更新哈希值的可选盐。

output.hotUpdateChunkFilename

  • 类型: string
  • 默认值: "[id].[fullhash].hot-update.js"

自定义热更新块的文件名。有关可能值的详细信息,请参阅 output.filename 选项。

此处允许的唯一占位符是 [id][fullhash],默认值为

rspack.config.js
module.exports = {
  //...
  output: {
    hotUpdateChunkFilename: '[id].[fullhash].hot-update.js',
  },
};
提示

通常您不需要更改 output.hotUpdateChunkFilename

output.hotUpdateGlobal

  • 类型: string
  • 默认值: "webpackHotUpdate" + output.uniqueName

仅当 target 设置为 'web' 时使用,该设置使用 JSONP 加载热更新。

JSONP 函数用于异步加载热更新块。

有关详细信息,请参阅 output.chunkLoadingGlobal

output.hotUpdateMainFilename

  • 类型: string
  • 默认值: "[runtime].[fullhash].hot-update.json"

自定义主要的热更新文件名。[fullhash][runtime] 可用作占位符。

提示

通常您不需要更改 output.hotUpdateMainFilename

output.iife

  • 类型: boolean
  • 默认: true

告诉 Rspack 在已发出的代码周围添加 IIFE 包装器。

rspack.config.js
module.exports = {
  //...
  output: {
    iife: true,
  },
};

output.importFunctionName

  • 类型: string
  • 默认值: 'import'

本机 import() 函数的名称。可用于填充,例如使用 dynamic-import-polyfill

rspack.config.js
module.exports = {
  //...
  output: {
    importFunctionName: '__import__',
  },
};

output.importMetaName

  • 类型: string
  • 默认值: 'import.meta'

本机 import.meta 对象的名称(可以替换为填充)。

rspack.config.js
module.exports = {
  //...
  output: {
    importMetaName: 'pseudoImport.meta',
  },
};

output.library

输出一个库,该库公开您的入口点的导出。

  • 类型: string | string[] | object

让我们看一个例子。

rspack.config.js
module.exports = {
  // …
  entry: './src/index.js',
  output: {
    library: 'MyLibrary',
  },
};

假设您在 src/index.js 入口文件中导出了一个函数

export function hello(name) {
  console.log(`hello ${name}`);
}

现在变量 MyLibrary 将绑定到您的入口文件的导出,以下是如何使用 Rspack 打包的库

<script src="https://example.org/path/to/my-library.js"></script>
<script>
  MyLibrary.hello('rspack');
</script>

在上面的示例中,我们向 entry 传递了一个单个入口文件,但是,Rspack 可以接受 多种类型的入口点,例如 arrayobject

  1. 如果您提供 array 作为 entry 点,则只有数组中的最后一个将被公开。

    module.exports = {
      // …
      entry: ['./src/a.js', './src/b.js'], // 只有在 b.js 中导出的内容才会被暴露
      output: {
        library: 'MyLibrary',
      },
    };
  2. 如果提供 object 作为 entry 点,则可以使用 libraryarray 语法公开所有条目

    module.exports = {
      // …
      entry: {
        a: './src/a.js',
        b: './src/b.js',
      },
      output: {
        filename: '[name].js',
        library: ['MyLibrary', '[name]'], // name is a placeholder here
      },
    };

    假设 a.jsb.js 都导出了函数 hello,以下是如何使用这些库

    <script src="https://example.org/path/to/a.js"></script>
    <script src="https://example.org/path/to/b.js"></script>
    <script>
      MyLibrary.a.hello('rspack');
      MyLibrary.b.hello('rspack');
    </script>

output.library.amdContainer

  • 类型: string

在 AMD 模块中,使用一个容器(在全局空间中定义)来调用 define/require 函数。

警告

请注意,amdContainer 的值 必须为 作为全局变量设置。

rspack.config.js
module.exports = {
  // …
  output: {
    library: {
      amdContainer: 'window["clientContainer"]',
      type: 'amd', // or 'amd-require'
    },
  },
};

这将产生以下包

window['clientContainer'].define(/*define args*/); // or 'amd-require' window['clientContainer'].require(/*require args*/);

output.library.name

为库指定一个名称。

  • 类型: string | string[] | {amd?: string, commonjs?: string, root?: string | string[]}
module.exports = {
  // …
  output: {
    library: {
      name: 'MyLibrary',
    },
  },
};

output.library.type

配置库的公开方式。

  • 类型: string

    默认情况下包含的类型为 'var''module''system''assign''assign-properties''this''window''self''global''commonjs''commonjs2''commonjs-module''commonjs-static''amd''amd-require''umd''umd2',但插件可能会添加其他类型。

对于以下示例,我们将使用 _entry_return_ 来表示入口点返回的值。

公开一个变量

这些选项将入口点的返回值(例如,入口点导出的任何内容)分配给由 output.library.name 在包被包含的任何范围内提供的名称。

type: 'var'
rspack.config.js
module.exports = {
  // …
  output: {
    library: {
      name: 'MyLibrary',
      type: 'var',
    },
  },
};

当加载库时,入口点的返回值 将分配给一个变量

var MyLibrary = _entry_return_;

// In a separate script with `MyLibrary` loaded…
MyLibrary.doSomething();
type: 'assign'
module.exports = {
  // …
  output: {
    library: {
      name: 'MyLibrary',
      type: 'assign',
    },
  },
};

这将生成一个隐式全局,它有可能重新分配现有值(谨慎使用)

MyLibrary = _entry_return_;

请注意,如果 MyLibrary 之前没有定义,则您的库将设置在全局范围内。

type: 'assign-properties'
module.exports = {
  // …
  output: {
    library: {
      name: 'MyLibrary',
      type: 'assign-properties',
    },
  },
};

类似于 type: 'assign',但更安全,因为它会在 MyLibrary 已存在的情况下重新使用 MyLibrary

// only create MyLibrary if it doesn't exist
MyLibrary = typeof MyLibrary === 'undefined' ? {} : MyLibrary;
// then copy the return value to MyLibrary
// similarly to what Object.assign does

// for instance, you export a `hello` function in your entry as follow
export function hello(name) {
  console.log(`Hello ${name}`);
}

// In another script with MyLibrary loaded
// you can run `hello` function like so
MyLibrary.hello('World');

通过对象分配公开

这些选项将入口点的返回值(例如,入口点导出的任何内容)分配给由 output.library.name 定义的特定对象下的名称。

type: 'this'
module.exports = {
  // …
  output: {
    library: {
      name: 'MyLibrary',
      type: 'this',
    },
  },
};

入口点的返回值 将分配给 this,并在 output.library.name 命名的属性下。this 的含义由您决定

this['MyLibrary'] = _entry_return_;

// In a separate script
this.MyLibrary.doSomething();
MyLibrary.doSomething(); // if `this` is window
type: 'window'
module.exports = {
  // …
  output: {
    library: {
      name: 'MyLibrary',
      type: 'window',
    },
  },
};

入口点的返回值 将使用 output.library.name 值分配给 window 对象。

window['MyLibrary'] = _entry_return_;

window.MyLibrary.doSomething();
type: 'global'
module.exports = {
  // …
  output: {
    library: {
      name: 'MyLibrary',
      type: 'global',
    },
  },
};

入口点的返回值 将使用 output.library.name 值分配给全局对象。根据 target 值,全局对象可能会相应地更改,例如 selfglobalglobalThis

global['MyLibrary'] = _entry_return_;

global.MyLibrary.doSomething();
type: 'commonjs'
module.exports = {
  // …
  output: {
    library: {
      name: 'MyLibrary',
      type: 'commonjs',
    },
  },
};

您的入口点的返回值将使用output.library.name值分配给exports对象。顾名思义,这在 CommonJS 环境中使用。

exports['MyLibrary'] = _entry_return_;

require('MyLibrary').doSomething();
警告

请注意,不设置output.library.name将导致入口点返回的所有属性都分配给给定的对象;没有对现有属性名称的检查。

模块定义系统

这些选项将生成一个带有完整头的捆绑包,以确保与各种模块系统兼容。output.library.name选项将在以下output.library.type选项下具有不同的含义。

type: 'module'
rspack.config.js
module.exports = {
  // …
  experiments: {
    outputModule: true,
  },
  output: {
    library: {
      // do not specify a `name` here
      type: 'module',
    },
  },
};

输出 ES 模块。

但是此功能仍处于实验阶段,尚未完全支持,因此请确保事先启用experiments.outputModule。此外,您可以在此线程中跟踪开发进度。

type: 'commonjs2'
module.exports = {
  // …
  output: {
    library: {
      // note there's no `name` here
      type: 'commonjs2',
    },
  },
};

您的入口点的返回值将分配给module.exports。顾名思义,这在 Node.js (CommonJS) 环境中使用

module.exports = _entry_return_;

require('MyLibrary').doSomething();

如果我们使用type: commmonjs2指定output.library.name,则您的入口点的返回值将分配给module.exports.[output.library.name]

提示

想知道 CommonJS 和 CommonJS2 之间的区别吗?虽然它们很相似,但它们之间存在一些细微差别,在 Rspack 的上下文中通常不相关。(有关更多详细信息,请阅读此问题。)

type: 'commonjs-static'
module.exports = {
  // …
  output: {
    library: {
      // note there's no `name` here
      type: 'commonjs-static',
    },
  },
};

单个导出将被设置为module.exports上的属性。名称中的“static”是指输出是静态可分析的,因此命名导出可通过 Node.js 导入到 ESM 中

输入

export function doSomething() {}

输出

function doSomething() {}

// …

exports.doSomething = __webpack_exports__.doSomething;

消费 (CommonJS)

const { doSomething } = require('./output.cjs'); // doSomething => [Function: doSomething]

消费 (ESM)

import { doSomething } from './output.cjs'; // doSomething => [Function: doSomething]
提示

当源代码以 ESM 编写并且输出应该与 CJS 和 ESM 兼容时,这很有用。有关更多详细信息,请阅读此问题这篇文章(特别是这一部分)。

type: 'amd'

这将公开您的库作为 AMD 模块。

AMD 模块要求入口块(例如,<script>标签加载的第一个脚本)使用特定属性定义,例如definerequire,这通常由 RequireJS 或任何兼容的加载器(例如almond)提供。否则,直接加载生成的 AMD 捆绑包将导致错误,例如define is not defined

使用以下配置

rspack.config.js
module.exports = {
  //...
  output: {
    library: {
      name: 'MyLibrary',
      type: 'amd',
    },
  },
};

生成的输出将使用名称"MyLibrary"定义,即

define('MyLibrary', [], function () {
  return _entry_return_;
});

捆绑包可以包含在脚本标签中,并且捆绑包可以这样调用

require(['MyLibrary'], function (MyLibrary) {
  // Do something with the library...
});

如果output.library.name未定义,则会生成以下内容。

define(function () {
  return _entry_return_;
});

如果直接使用<script>标签加载,此捆绑包将无法按预期工作,或者根本无法工作(在almond加载器的情况下)。它仅通过 RequireJS 兼容的异步模块加载器通过该文件的实际路径工作,因此在这种情况下,如果这些路径直接在服务器上公开,则output.pathoutput.filename可能对这种特定设置很重要。

type: 'amd-require'
rspack.config.js
module.exports = {
  //...
  output: {
    library: {
      name: 'MyLibrary',
      type: 'amd-require',
    },
  },
};

这将使用立即执行的 AMD require(dependencies, factory) 包装器打包您的输出。

'amd-require'类型允许使用 AMD 依赖项,而无需单独的后续调用。与'amd'类型一样,这取决于适当的require函数在加载 Rspack 输出的环境中可用。

使用此类型,库名称不可用。

type: 'umd'

这将公开您的库,使其在所有模块定义下都能工作,允许它与 CommonJS、AMD 和全局变量一起使用。查看UMD 存储库以了解更多信息。

在这种情况下,您需要library.name属性来命名您的模块

module.exports = {
  //...
  output: {
    library: {
      name: 'MyLibrary',
      type: 'umd',
    },
  },
};

最后输出为

(function webpackUniversalModuleDefinition(root, factory) {
  if (typeof exports === 'object' && typeof module === 'object')
    module.exports = factory();
  else if (typeof define === 'function' && define.amd) define([], factory);
  else if (typeof exports === 'object') exports['MyLibrary'] = factory();
  else root['MyLibrary'] = factory();
})(global, function () {
  return _entry_return_;
});

请注意,省略library.name将导致入口点返回的所有属性直接分配给根对象,如对象分配部分中所述。示例

module.exports = {
  //...
  output: {
    libraryTarget: 'umd',
  },
};

输出将是

(function webpackUniversalModuleDefinition(root, factory) {
  if (typeof exports === 'object' && typeof module === 'object')
    module.exports = factory();
  else if (typeof define === 'function' && define.amd) define([], factory);
  else {
    var a = factory();
    for (var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];
  }
})(global, function () {
  return _entry_return_;
});

您可以为每个目标指定不同的名称,为library.name指定一个对象

module.exports = {
  //...
  output: {
    library: {
      name: {
        root: 'MyLibrary',
        amd: 'my-library',
        commonjs: 'my-common-library',
      },
      type: 'umd',
    },
  },
};
type: 'system'

这将公开您的库作为System.register模块。

系统模块要求在执行 Rspack 捆绑包时,浏览器中存在全局变量System。编译为System.register格式允许您System.import('/bundle.js')而无需额外的配置,并将您的 Rspack 捆绑包加载到系统模块注册表中。

module.exports = {
  //...
  output: {
    library: {
      type: 'system',
    },
  },
};

输出

System.register([], function (__WEBPACK_DYNAMIC_EXPORT__, __system_context__) {
  return {
    execute: function () {
      // ...
    },
  };
});

通过在配置中添加output.library.name以及将output.library.type设置为system,输出捆绑包将具有库名称作为System.register的参数

System.register(
  'MyLibrary',
  [],
  function (__WEBPACK_DYNAMIC_EXPORT__, __system_context__) {
    return {
      execute: function () {
        // ...
      },
    };
  },
);

其他类型

type: 'jsonp'

rspack.config.js
module.exports = {
  // …
  output: {
    library: {
      name: 'MyLibrary',
      type: 'jsonp',
    },
  },
};

这将把您的入口点的返回值包装到 jsonp 包装器中。

MyLibrary(_entry_return_);

库的依赖项将由externals配置定义。

output.library.export

指定应公开为库的哪个导出。

  • 类型: string | string[]
  • 默认值: undefined

默认情况下为undefined,它将导出整个(命名空间)对象。以下示例演示了在使用output.library.type: 'var'时,此配置的效果。

rspack.config.js
module.exports = {
  output: {
    library: {
      name: 'MyLibrary',
      type: 'var',
      export: 'default',
    },
  },
};

您的入口点的默认导出将分配给库名称

// If your library has a default export
var MyLibrary = _entry_return_.default;

您也可以将数组传递给output.library.export,它将被解释为要分配给库名称的模块的路径

rspack.config.js
module.exports = {
  output: {
    library: {
      name: 'MyLibrary',
      type: 'var',
      export: ['default', 'subModule'],
    },
  },
};

这是库代码

var MyLibrary = _entry_return_.default.subModule;

output.library.auxiliaryComment

在 UMD 包装器中添加注释。

  • 类型: string | { amd?: string, commonjs?: string, commonjs2?: string, root?: string }
  • 默认值: undefined

要为每个umd类型插入相同的注释,请将auxiliaryComment设置为字符串

module.exports = {
  // …
  mode: 'development',
  output: {
    library: {
      name: 'MyLibrary',
      type: 'umd',
      auxiliaryComment: 'Test Comment',
    },
  },
};

这将产生以下结果

(function webpackUniversalModuleDefinition(root, factory) {
  //Test Comment
  if (typeof exports === 'object' && typeof module === 'object')
    module.exports = factory();
  //Test Comment
  else if (typeof define === 'function' && define.amd) define([], factory);
  //Test Comment
  else if (typeof exports === 'object') exports['MyLibrary'] = factory();
  //Test Comment
  else root['MyLibrary'] = factory();
})(self, function () {
  return _entry_return_;
});

为了精细控制,请传递一个对象

module.exports = {
  // …
  mode: 'development',
  output: {
    library: {
      name: 'MyLibrary',
      type: 'umd',
      auxiliaryComment: {
        root: 'Root Comment',
        commonjs: 'CommonJS Comment',
        commonjs2: 'CommonJS2 Comment',
        amd: 'AMD Comment',
      },
    },
  },
};

output.library.umdNamedDefine

  • 类型: boolean
  • 默认值: undefined

当使用output.library.type: "umd"时,将output.library.umdNamedDefine设置为true将命名 UMD 构建的 AMD 模块。否则,将使用匿名define

module.exports = {
  //...
  output: {
    library: {
      name: 'MyLibrary',
      type: 'umd',
      umdNamedDefine: true,
    },
  },
};

AMD 模块将是

define('MyLibrary', [], factory);

output.module

  • 类型: boolean
  • 默认值: false

将 JavaScript 文件输出为模块类型。默认情况下禁用,因为它是一个实验性功能。要使用它,您必须将experiments.outputModule设置为true

启用后,Rspack 将在内部将output.iife设置为false,将output.scriptType设置为'module',并将terserOptions.module设置为true

如果您使用 Rspack 编译要供其他人使用的库,请确保在output.moduletrue时,将output.libraryTarget设置为'module'

rspack.config.js
module.exports = {
  //...
  experiments: {
    outputModule: true,
  },
  output: {
    module: true,
  },
};

output.path

  • 类型: string
  • 默认: path.resolve(process.cwd(), 'dist')

输出目录作为绝对路径。

rspack.config.js
const path = require('path');

module.exports = {
  output: {
    path: path.resolve(__dirname, 'dist/assets'),
  },
};

请注意,此参数中的[fullhash]将被编译的哈希值替换。

警告

路径中不能包含感叹号(!),因为它被 Rspack 保留用于加载器语法)。

output.pathinfo

  • 类型: boolean | 'verbose'
  • 默认: true

告诉 Rspack 在捆绑包中包含有关包含模块的信息的注释。此选项在development中默认为true,在production模式中默认为false'verbose'显示更多信息,例如导出、运行时要求和中止。

警告

虽然这些注释可以提供的数据在开发过程中阅读生成的代码时很有用,但它不应在生产中使用。

rspack.config.js
module.exports = {
  //...
  output: {
    pathinfo: true,
  },
};
提示

它还将一些有关树摇动的信息添加到生成的捆绑包中。

output.publicPath

  • 类型: 'auto' | string | ((pathData: PathData, assetInfo?: JsAssetInfo) => string)
  • 默认:targets'web''webworker'时,为'auto'。否则为undefined

此选项确定引用的资源的 URL 前缀,例如:图像、文件等。

例如,给定一个配置文件。

rspack.config.js
module.exports = {
  output: {
    publicPath: '/assets/',
    chunkFilename: '[id].chunk.js',
    assetModuleFilename: '[name][ext]',
  },
};

对于非初始块文件,其请求 URL 如下所示:/assets/1.chunk.js

对于对图像的引用,请求 URL 如下所示:/assets/logo.png

此外,当您使用 CDN 部署产品时,它很有用

rspack.config.js
module.exports = {
  output: {
    publicPath: 'https://cdn.example.com/assets/',
    assetModuleFilename: '[name][ext]',
  },
};

对于所有资产资源,它们的请求 URL 如下所示:https://cdn.example.com/assets/logo.png

动态设置 publicPath

您可以使用运行时代码中的__webpack_public_path__动态设置publicPath,而__webpack_public_path__将覆盖 Rspack 配置中的publicPath,但它只对动态加载的资源生效。

首先创建一个publicPath.js

publicPath.js
__webpack_public_path__ = 'https://cdn.example.com/assets/';

然后将其导入入口文件的首行

entry.js
import './publicPath.js';
import './others.js';

output.scriptType

  • 类型: 'module' | 'text/javascript' | boolean
  • 默认值: false

此选项允许使用自定义脚本类型加载异步块,例如<script type="module" ...>

提示

如果output.module设置为true,则output.scriptType将默认为'module'而不是false

rspack.config.js
module.exports = {
  //...
  output: {
    scriptType: 'module',
  },
};

output.sourceMapFilename

  • 类型: string
  • 默认: '[file].map[query]'

配置源映射的命名方式。仅当devtool设置为'source-map'(写入输出文件)时才生效。

可以使用来自 output.filename[name][id][fullhash][chunkhash] 替换。除了这些,还可以使用 模板字符串 中“文件名级别”下列出的替换。

output.strictModuleErrorHandling

  • 类型: boolean
  • 默认值: false

根据 EcmaScript 模块规范处理模块加载错误,但会影响性能。

rspack.config.js
module.exports = {
  //...
  output: {
    strictModuleErrorHandling: true,
  },
};

output.strictModuleExceptionHandling

  • 类型: boolean

告诉 Rspack 如果模块在被 require 时抛出异常,则将其从模块实例缓存 (require.cache) 中移除。

output.trustedTypes

  • 类型: true | string | object
  • 默认值: undefined

控制 Trusted Types 兼容性。启用后,Rspack 将检测 Trusted Types 支持,如果支持,则使用 Trusted Types 策略来创建它动态加载的脚本 URL。当应用程序运行在 require-trusted-types-for 内容安全策略指令下时使用。

默认情况下它被禁用(没有兼容性,脚本 URL 是字符串)。

  • 当设置为 true 时,Rspack 将使用 output.uniqueName 作为 Trusted Types 策略名称。
  • 当设置为非空字符串时,它的值将用作策略名称。
  • 当设置为对象时,策略名称将从对象的 policyName 属性中获取。
rspack.config.js
module.exports = {
  //...
  output: {
    trustedTypes: {
      policyName: 'my-application#webpack',
    },
  },
};

output.uniqueName

  • 类型: string
  • 默认值: 默认值为 output.library 名称或上下文中的 package.json 中的包名称,如果两者都找不到,则设置为 ''

Rspack 构建的唯一名称,以避免在使用全局变量时多个 Rspack 运行时发生冲突。

output.uniqueName 将用于为以下内容生成唯一的全局变量:

rspack.config.js
module.exports = {
  output: {
    uniqueName: 'my-package-xyz',
  },
};

output.wasmLoading

  • 类型: false | 'fetch', 'async-node'
  • 默认值: 'fetch'

用于设置加载 WebAssembly 模块方法的选项。默认情况下包含的方法是 'fetch'(web/webworker)、'async-node'(Node.js),但可能由插件添加其他方法。

默认值可能会受到不同的 target 的影响。

  • 如果 target 设置为 'web''webworker''electron-renderer''node-webkit',则默认值为 'fetch'
  • 如果 target 设置为 'node''async-node''electron-main''electron-preload',则默认值为 'async-node'
rspack.config.js
module.exports = {
  //...
  output: {
    wasmLoading: 'fetch',
  },
};

output.webassemblyModuleFilename

  • 类型: string
  • 默认值: '[hash].module.wasm'

指定 WebAssembly 模块的文件名。它应作为 output.path 目录中的相对路径提供。

rspack.config.js
module.exports = {
  //...
  output: {
    webassemblyModuleFilename: '[id].[hash].wasm',
  },
};

output.workerChunkLoading

  • 类型: false | 'jsonp' | 'import-scripts' | 'require' | 'async-node' | 'import'
  • 默认值: false

新的选项 workerChunkLoading 控制工作者的块加载。

提示

此选项的默认值取决于 target 设置。有关更多详细信息,请在 Rspack 默认值 中搜索 "workerChunkLoading"

rspack.config.js
module.exports = {
  //...
  output: {
    workerChunkLoading: false,
  },
};

output.workerPublicPath

  • 类型: string
  • 默认值: ""

为 Worker 设置公共路径,默认值为 output.publicPath 的值。仅当你的工作者脚本位于与其他脚本不同的路径中时才使用此选项。

rspack.config.js
module.exports = {
  //...
  output: {
    workerPublicPath: '/workerPublicPath2/',
  },
};

output.workerWasmLoading

  • 类型: false | 'fetch-streaming' | 'fetch' | 'async-node' | string
  • 默认值: false

用于在工作者中设置加载 WebAssembly 模块方法的选项,默认值为 output.wasmLoading 的值。

rspack.config.js
module.exports = {
  //...
  output: {
    workerWasmLoading: 'fetch',
  },
};

output.auxiliaryComment

警告

建议使用 output.library.auxiliaryComment 代替。

output.libraryExport

警告

我们可能会放弃对它的支持,因此建议使用 output.library.export,它与 libraryExport 的工作方式相同。

output.libraryTarget

警告

请使用 output.library.type 代替,因为我们可能会在将来放弃对 output.libraryTarget 的支持。

output.umdNamedDefine

警告

建议使用 output.library.umdNamedDefine 代替。

output.cssHeadDataCompression

  • 类型: boolean
  • 默认值: 开发模式为 false,生产模式为 true

Rspack 在 CSS 中添加一些元数据以解析 CSS 模块,此配置决定是否压缩这些元数据。

例如

.local-a {
  color: blue;
}

head {
  --webpack-main: a: local-a/&\.\/ src\/index\.module\.css;
}

压缩后 👇

.local-a {
  color: blue;
}

head {
  --webpack-main: &\.\/ srcăindexāmoduleācss;
}