Skip to content
开发文档
Configuration
汇编

汇编

¥Compilation

使用 SWC 进行开箱即用的编译,不需要定制。你也可以选择覆盖该配置。以下是默认值:

¥Compilation works out of the box with SWC and does not require customization. Optionally, you can override the configuration. Here are the defaults:

.swcrc
{
  "jsc": {
    "parser": {
      "syntax": "ecmascript",
      "jsx": false,
      "dynamicImport": false,
      "privateMethod": false,
      "functionBind": false,
      "exportDefaultFrom": false,
      "exportNamespaceFrom": false,
      "decorators": false,
      "decoratorsBeforeExport": false,
      "topLevelAwait": false,
      "importMeta": false,
      "preserveAllComments": false
    },
    "transform": null,
    "target": "es5",
    "loose": false,
    "externalHelpers": false,
    // Requires v1.2.50 or upper and requires target to be es2016 or upper.
    "keepClassNames": false
  },
  "isModule": false
}

env

SWC 有 preset-env 的替代方案。你可以

¥SWC has an alternative for preset-env. You can

  • 设置目标浏览器

    ¥Set target browsers

  • 使用 browserslist

    ¥Use browserslist

  • 控制变换

    ¥Control transforms

env 条目。请注意,这不适用于 jsc.target

¥with env entry. Note that this does not work with jsc.target.

env.targets

可能的值:

¥Possible values:

  • 查询:string

    ¥Query: string

示例:

¥Example:

.swcrc
{
    "jsc": {
        "parser": {
            "syntax": "typescript",
            "tsx": true,
        },
        "externalHelpers": true
    },
    "env": {
        "targets": "Chrome >= 48"
    }
}
 
  • 查询:string[]

    ¥Queries: string[]

  • 每个浏览器的版本:Map<String, Version>

    ¥Version per browser: Map<String, Version>

定位 chrome 79 的示例。

¥Example of targeting chrome 79.

.swcrc
{
    "env": {
        "targets": {
            "chrome": "79",
        }
    },
}

env.mode

可选的。可能的值:"usage" | "entry" | false,默认为 false

¥Optional. Possible values: "usage" | "entry" | false, defaults to false.

env.debug

可选的。类型:布尔

¥Optional. Type: Bool

启用调试日志记录。

¥Enable debug logging.

env.dynamicImport

可选的。类型:布尔

¥Optional. Type: Bool

env.loose

可选的。类型:布尔

¥Optional. Type: Bool

启用宽松模式。另请参见 jsc.loose

¥Enable loose mode. See jsc.loose also.

env.skip

可选的。类型:string[]

¥Optional. Type: string[]

env.include

可选的。类型:string[]

¥Optional. Type: string[]

要包含的功能或模块。

¥Feature or module to include.

针对 chrome 79 启用 async/yield 转换的示例。

¥Example of enabling async/yield transform while targeting chrome 79.

.swcrc
{
    "env": {
        "targets": {
            "chrome": "79",
        },
        "include": [
            "transform-async-to-generator",
            "transform-regenerator",
        ],
    },
}

env.exclude

可选的。类型:string[]

¥Optional. Type: string[]

要排除的功能或模块。

¥Feature or module to exclude.

env.coreJs

可选的。类型:string

¥Optional. Type: string

.swcrc
{
    "jsc": {
        "parser": {
            "syntax": "ecmascript",
            "jsx": true
        }
    },
    "env": {
        "mode": "usage",
        "coreJs": "3.26.1"
    }
}

env.path

可选的。目前没有。

¥Optional. Currently noop.

env.shippedProposals

可选的。类型:布尔

¥Optional. Type: Bool

env.forceAllTransforms

可选的。类型:布尔

¥Optional. Type: Bool

env.bugfixes

可选的。类型:布尔

¥Optional. Type: Bool

启用错误修复通道。

¥Enable bugfix passes.

jsc.externalHelpers

.swcrc
{
  "jsc": {
    "externalHelpers": true
  }
}

输出代码可能依赖于辅助函数来支持目标环境。默认情况下,辅助函数会内联到需要的输出文件中。

¥The output code may depend on helper functions to support the target environment. By default, a helper function is inlined into the output files where it is required.

你可以通过启用 externalHelpers 使用外部模块中的辅助程序,并且辅助程序代码将由 node_modules/@swc/helpers 的输出文件导入。

¥You can use helpers from an external module by enabling externalHelpers and the helpers code will be imported by the output files from node_modules/@swc/helpers.

打包时,此选项将大大减小文件大小。

¥While bundling, this option will greatly reduce your file size.

除了 @swc/core 之外,你还必须添加 @swc/helpers 作为依赖。

¥You must add @swc/helpers as a dependency in addition to @swc/core.

jsc.parser

typescript

.swcrc
{
  "jsc": {
    "parser": {
      "syntax": "typescript",
      "tsx": false,
      "decorators": false,
      "dynamicImport": false
    }
  }
}

ecmascript

.swcrc
{
  "jsc": {
    "parser": {
      "syntax": "ecmascript",
      "jsx": false,
      "dynamicImport": false,
      "privateMethod": false,
      "functionBind": false,
      "classPrivateProperty": false,
      "exportDefaultFrom": false,
      "exportNamespaceFrom": false,
      "decorators": false,
      "decoratorsBeforeExport": false,
      "importMeta": false
    }
  }
}

jsc.target

@swc/core v1.0.27 开始,你可以通过该字段指定目标环境。

¥Starting from @swc/core v1.0.27, you can specify the target environment by using the field.

.swcrc
{
  "jsc": {
    // Disable es3 / es5 / es2015 transforms
    "target": "es2016"
  }
}

jsc.loose

@swc/core v1.1.4 开始,你可以通过启用 jsc.loose 来启用 "loose" 转换,其工作方式类似于 babel-preset-env 宽松模式 (opens in a new tab)

¥Starting from @swc/core v1.1.4, you can enable "loose" transformations by enabling jsc.loose which works like babel-preset-env loose mode (opens in a new tab).

.swcrc
{
  "jsc": {
    "loose": true
  }
}

jsc.transform

.swcrc
{
  "jsc": {
    "transform": {
      "react": {
        "pragma": "React.createElement",
        "pragmaFrag": "React.Fragment",
        "throwIfNamespace": true,
        "development": false,
        "useBuiltins": false
      },
      "optimizer": {
        "globals": {
          "vars": {
            "__DEBUG__": "true"
          }
        }
      }
    }
  }
}

jsc.transform.legacyDecorator

你可以使用旧的(第 1 阶段)类装饰器语法和行为。

¥You can use the legacy (stage 1) class decorators syntax and behavior.

.swcrc
{
  "jsc": {
    "parser": {
      "syntax": "ecmascript",
      "decorators": true
    },
    "transform": {
      "legacyDecorator": true
    }
  }
}

jsc.transform.decoratorMetadata

此功能需要 v1.2.13+

¥This feature requires v1.2.13+.

如果你使用启用了 emitDecoratorMetadata 的 TypeScript 和装饰器,则可以使用 swc 来加快迭代速度:

¥If you are using typescript and decorators with emitDecoratorMetadata enabled, you can use swc for faster iteration:

.swcrc
{
  "jsc": {
    "parser": {
      "syntax": "typescript",
      "decorators": true
    },
    "transform": {
      "legacyDecorator": true,
      "decoratorMetadata": true
    }
  }
}

jsc.transform.react

jsc.transform.react.runtime

可能的值:automaticclassic。这会影响 JSX 源代码的编译方式。

¥Possible values: automatic, classic. This affects how JSX source code will be compiled.

  • 默认为 classic

    ¥Defauts to classic.

  • 使用 runtime: automatic 来使用 JSX 运行时模块(例如 React 17 中引入的 react/jsx-runtime)。

    ¥Use runtime: automatic to use a JSX runtime module (e.g. react/jsx-runtime introduced in React 17).

  • runtime: classic 代替用 React.createElement - 使用此选项,你必须确保使用 JSX 时 React 在范围内。

    ¥Use runtime: classic to use React.createElement instead - with this option, you must ensure that React is in scope when using JSX.

在这里了解更多 (opens in a new tab)

¥Learn more here (opens in a new tab).

jsc.transform.react.importSource

  • 默认为 react

    ¥Defaults to react.

  • 使用 runtime: automatic 时,确定要导入的运行时库。

    ¥When using runtime: automatic, determines the runtime library to import.

  • 该选项可以用 @jsxImportSource foo 覆盖。

    ¥This option can be overrided with @jsxImportSource foo.

jsc.transform.react.pragma

  • 默认为 React.createElement

    ¥Defaults to React.createElement.

  • 使用 runtime: classic 时,替换编译 JSX 表达式时使用的函数。

    ¥When using runtime: classic, replaces the function used when compiling JSX expressions.

  • 该选项可以用 @jsx foo 覆盖。

    ¥This option can be overrided with @jsx foo.

jsc.transform.react.pragmaFrag

  • 默认为 React.Fragment

    ¥Defaults to React.Fragment

  • 替换编译 JSX 片段时使用的组件。

    ¥Replace the component used when compiling JSX fragments.

  • 该选项可以用 @jsxFrag foo 覆盖。

    ¥This option can be overrided with @jsxFrag foo.

jsc.transform.react.throwIfNamespace

切换是否在使用 XML 命名空间标记名称时引发错误。例如:<f:image />

¥Toggles whether or not to throw an error if an XML namespaced tag name is used. For example: <f:image />

尽管 JSX 规范允许这样做,但默认情况下它是禁用的,因为 React 的 JSX 目前不支持它。

¥Though the JSX spec allows this, it is disabled by default since React's JSX does not currently have support for it.

jsc.transform.react.development

在 JSX 生成的元素上切换调试属性 __self__source,这些元素由 React Developer Tools 等开发工具使用。

¥Toggles debug props __self and __source on elements generated from JSX, which are used by development tooling such as React Developer Tools.

当与 swc-loader 一起使用时,此选项会根据 Webpack mode 设置自动设置。参见 将 SWC 与 Webpack 结合使用

¥This option is set automatically based on the Webpack mode setting when used with swc-loader. See Using swc with webpack.

jsc.transform.react.useBuiltins

使用 Object.assign() 代替 _extends。默认为 false。

¥Use Object.assign() instead of _extends. Defaults to false.

jsc.transform.react.refresh

启用 react-refresh (opens in a new tab) 相关转换。默认为 false,因为它被认为是实验性的。

¥Enable react-refresh (opens in a new tab) related transform. Defaults to false as it's considered experimental.

传递 refresh: true 来启用此功能,或具有以下内容的对象:

¥Pass refresh: true to enable this feature, or an object with the following:

interface ReactRefreshConfig {
  refreshReg: String;
  refreshSig: String;
  emitFullSignatures: boolean;
}

jsc.transform.constModules

.swcrc
{
  "jsc": {
    "transform": {
      "constModules": {
        "globals": {
          "@ember/env-flags": {
            "DEBUG": "true"
          },
          "@ember/features": {
            "FEATURE_A": "false",
            "FEATURE_B": "true"
          }
        }
      }
    }
  }
}

然后,源代码如下:

¥Then, source code like:

source.js
import { DEBUG } from "@ember/env-flags";
import { FEATURE_A, FEATURE_B } from "@ember/features";
 
console.log(DEBUG, FEATURE_A, FEATURE_B);

变换为:

¥is transformed to:

output.js
console.log(true, false, true);

jsc.transform.optimizer

SWC 优化器假设:

¥The SWC optimizier assumes:

  • 它是一个模块或封装在一个 iife 中。

    ¥It's a module or wrapped in an iife.

  • 访问(获取)全局变量没有副作用。这与 google 闭包编译器的假设相同。

    ¥Accessing (get) global variables does not have a side-effect. It is the same assumption as the google closure compiler.

  • 你不能将字段添加到数字字面量、正则表达式或字符串字面量等字面量中。

    ¥You don't add fields to literals like a numeric literal, regular expression or a string literal.

  • 文件以 gzip 形式提供。

    ¥Files are served as gzipped.

SWC 不会专注于减小非 gzip 压缩文件的大小。

¥SWC will not focus on reducing the size of non-gzipped file size.

将其设置为 undefined 会跳过优化器传递。

¥Setting this to undefined skips optimizer pass.

jsc.transform.optimizer.simplify

需要 v1.2.101+

¥Requires v1.2.101+

你可以将其设置为 false 以使用 inline_globals,同时跳过优化。

¥You can set this to false to use inline_globals while skipping optimizations.

.swcrc
{
  "jsc": {
    "transform": {
      "optimizer": {
        "simplify": false,
        "globals": {
          "vars": {
            "__DEBUG__": "true"
          }
        }
      }
    }
  }
}

jsc.transform.optimizer.globals

需要 v1.2.101+

¥Requires v1.2.101+

  • vars - 要内联的变量。

    ¥vars - Variables to inline.

  • typeofs - 如果设置 { "window": "object" }typeof window 将被替换为 "object"

    ¥typeofs - If you set { "window": "object" }, typeof window will be replaced with "object".

.swcrc
{
  "jsc": {
    "transform": {
      "optimizer": {
        "globals": {
          "vars": {
            "__DEBUG__": "true"
          }
        }
      }
    }
  }
}

然后,你就可以像 npx swc '__DEBUG__' --filename input.js 一样使用它了。

¥Then, you can use it like npx swc '__DEBUG__' --filename input.js.

jsc.transform.optimizer.jsonify

需要 v1.1.1+

¥Requires v1.1.1+

  • minCost - 如果解析纯对象字面量的成本大于此值,则对象字面量将转换为 JSON.parse('{"foo": "bar"}')。默认为 1024。

    ¥minCost - If cost of parsing a pure object literal is larger than this value, the object literal is converted to JSON.parse('{"foo": "bar"}'). Defaults to 1024.

.swcrc
{
  "jsc": {
    "transform": {
      "optimizer": {
        "jsonify": {
          "minCost": 0
        }
      }
    }
  }
}

这会将所有纯对象字面量更改为 JSON.parse("")

¥This will change all pure object literals to JSON.parse("").

jsc.keepClassNames

需要 v1.2.50+ 且目标为 es2016 或更高版本

¥Requires v1.2.50+ and target to be es2016 or higher

启用此选项将使 swc 保留原始类名。

¥Enabling this option will make swc preserve original class names.

jsc.paths

需要 v1.2.62+

¥Requires v1.2.62+

语法与 tsconfig.json 相同:了解更多 (opens in a new tab)

¥Syntax is identical as it of tsconfig.json: learn more (opens in a new tab).

需要 jsc.baseUrl。见下文。

¥Requires jsc.baseUrl. See below.

jsc.baseUrl

该路径必须指定为绝对路径。

¥The path must be specified as an absolute path.

了解更多 (opens in a new tab)

¥Learn more (opens in a new tab).

jsc.minify

需要 v1.2.67+

¥Requires v1.2.67+

详细信息请参见 缩小文档

¥See the documentation for minification for more details.

jsc.experimental

jsc.experimental.keepImportAssertions

保留导入断言。这是实验性的,因为 ecmascript 规范尚未涵盖导入断言。

¥Preserve import assertions. This is experimental because import assertions are not covered by ecmascript specifications yet.

jsc.experimental.plugins

它遵循 node.js 的解析规则。

¥It follows resolving rule of node.js,.

指定插件名称,例如

¥Specify the plugin name like

.swcrc
{
  "jsc": {
    "experimental": {
      "plugins": [
        ["@swc/plugin-styled-jsx", {}]
      ]
    }
  }
}

styled-jsx 之所以有效,是因为它被发布为 @swc/plugin-styled-jsx

¥styled-jsx works because it's published as @swc/plugin-styled-jsx.

jsc.preserveAllComments

指示编译期间应保留所有注释。源中的注释可能会发生变化,以保留其从源到编译输出的相对位置。此功能对于需要注释保持相对接近源的转译非常有用:例如 使用 istanbul-ignore 覆盖注释进行测试的文件。

¥Indicate that all comments should be preserved during compilation. Comments from source may be shifted in order to preserve thier relative location from source to compiled output. This feature is useful for transpilation that requires comments remain relatively close to the source: e.g. files under test with istanbul-ignore coverage annotations.

jsc.transform.useDefineForClassFields

可能的值:

¥Possilbe values:

  • true
class Foo {
  init = 3;
}
 
console.log(Foo.init)

将被编译为

¥will be compiled as

class Foo {
    constructor(){
        // Helper
        _defineProperty(this, "init", 3);
    }
}
console.log(Foo.init);
  • false
class Foo {
  init = 3;
}
 
console.log(Foo.init)

将被编译为

¥will be compiled as

class Foo {
    constructor(){
        this.init = 3;
    }
}
console.log(Foo.init);

jsc.transform.decoratorVersion

v1.3.47 开始,你可以使用第 3 阶段装饰器。

¥Starting from v1.3.47, you can use stage 3 decorator.

.swcrc
{
    "jsc": {
        "parser": {
            "syntax": "ecmascript",
            "decorators": true
        },
        "transform": {
            "decoratorVersion": "2022-03"
        }
    }
}

可能的值:

¥Possible values:

  • "2021-12"(默认)

    ¥"2021-12" (default)

传统装饰器。

¥Legacy decorator.

  • "2022-03"

第 3 阶段装饰器。

¥Stage 3 decorator.

多入口

¥Multiple Entries

需要 v1.0.47+

¥Requires v1.0.47+

[
  {
    "test": ".*\\.js$",
    "module": {
      "type": "commonjs"
    }
  },
  {
    "test": ".*\\.ts$",
    "module": {
      "type": "amd"
    }
  }
]

这使得 SWC 将 JavaScript 文件编译为 CommonJS 模块,并将 TypeScript 文件编译为 AMD 模块。

¥This makes SWC compile JavaScript files as CommonJS modules and compile TypeScript files as AMD modules.

请注意,test 选项可用于仅转编译 TypeScript 文件,例如

¥Note that test option can be used to transcompile only typescript files, like

.swcrc
{
  "test": ".*\\.ts$",
  "jsc": {
    "parser": {
      "syntax": "typescript",
      "tsx": false,
      "decorators": true,
      "dynamicImport": true
    }
  }
}

test

类型:Regex / Regex[]

¥Type: Regex / Regex[]

.swcrc
{
  "test": ".*\\.ts$",
  "jsc": {
    "parser": {
      "syntax": "typescript",
      "tsx": false,
      "decorators": true,
      "dynamicImport": true
    }
  }
}

exclude

类型:Regex / Regex[]

¥Type: Regex / Regex[]

.swcrc
{
  "exclude": [".*\\.js$", ".*\\.map$"],
  "jsc": {
    "parser": {
      "syntax": "typescript",
      "tsx": false,
      "decorators": true,
      "dynamicImport": true
    }
  }
}

sourceMaps

需要 v1.2.50+

¥Requires v1.2.50+

通过将 sourceMaps: truesourceMaps: 'inline' 添加到 .swcrc 来启用源映射。

¥Enable source map by adding sourceMaps: true or sourceMaps: 'inline' to the .swcrc.

.swcrc
{
  "sourceMaps": true
}

inlineSourcesContent

需要 v1.2.101+

¥Requires v1.2.101+

默认为 true。如果想让 swc 将文件内容存储到 sourcemap 中,可以将 inlineSourcesContent 设置为 true

¥Defaults to true. If you want to make swc store contents of files into sourcemap, you can set inlineSourcesContent to true.

.swcrc
{
  "sourceMaps": true,
  "inlineSourcesContent": true
}

isModule

可能的值:truefalse"unknown"

¥Possible values: true, false, "unknown"

用于将输入视为模块或脚本。如果设置为 unknown,如果是 esm,则为 Module,否则为 Script

¥Used to treat input as a module or script. If this is set to unknown, it will be Module if it's esm and Script otherwise.