template-parameters Documentation

Official TypeScript developer resources and documentation for jantimon/template-parameters. Verified technical context for AI.

0 stars TypeScript TypeScript 1 file ยท ~9,712 tokens
RAW Doc

1. Project Overview & Quickstart (jantimon/template-parameters)

template-parameters

Open-source repository jantimon/template-parameters

Repository Details

Note: High-volume repository documentation is actively indexed and synchronized by YakaAI.

2. Official Technical Reference & Guides (jantimon/website)

File: docs/benchmark-autogen.md


id: benchmark-autogen title: Autogenerated Benchmarks sidebar_label: Autogenerated

import Benchmark from "../src/components/Benchmark/benchmark";


File: docs/benchmark-transform.md


id: benchmark-transform title: Transforms sidebar_label: Transforms

See kdy1/benchmark-done-right for the benchmark source code.

Things to note

babel does not same work. It does only little bit of works, but I didn't bother to configure it because it's slow even it does tiny amounts of work.

babel does not support parellel transforms.

esbuild does not support es3.

How to interpret result.

For most users, most important test result is parallel benchmark.
It's because build tool authors are smart enough to use await Promise.all(tasks) and the benchmark scenario which is most close to it is parallel.

If you are not lucky enough and you need to apply transforms synchronously, synchronous benchmark matters.

Parallel

Performance of babel and tsc is identical as them of sychronous benchmark.

es3

es5

es2015

es2016

es2017

es2018

es2019

es2020

Synchronous

es3

es5

es2015

es2016

es2017

es2018

es2019

es2020

Asynchronous

This benchmark suite does not use all cpu cores.

For swc, the benchmark stores only one task on node.js thread pool at a time.

es3

es5

es2015

es2016

es2017

es2018

es2019

es2020


File: docs/comparison-babel.md


id: comparison-babel title: Comparison with babel sidebar_label: Comparison with babel

Note: For the case where this document is outdated, you can expect swc to support all of ecmascript specifcation.

babel package name swc
babel-plugin-external-helpers โœ”๏ธ
babel-plugin-proposal-async-generator-functions โœ”๏ธ
babel-plugin-proposal-class-properties โœ”๏ธ
babel-plugin-proposal-decorators โœ”๏ธ
babel-plugin-proposal-do-expressions โŒ (stage 1)
babel-plugin-proposal-dynamic-import โœ”๏ธ
babel-plugin-proposal-export-default-from โœ”๏ธ
babel-plugin-proposal-export-namespace-from โœ”๏ธ
babel-plugin-proposal-function-bind โŒ (stage 0)
babel-plugin-proposal-function-sent โŒ (stage 2)
babel-plugin-proposal-json-strings โœ”๏ธ
babel-plugin-proposal-logical-assignment-operators โŒ (stage 1)
babel-plugin-proposal-nullish-coalescing-operator โœ”๏ธ
babel-plugin-proposal-numeric-separator โœ”๏ธ
babel-plugin-proposal-object-rest-spread โœ”๏ธ
babel-plugin-proposal-optional-catch-binding โœ”๏ธ
babel-plugin-proposal-optional-chaining โœ”๏ธ
babel-plugin-proposal-partial-application โŒ (stage 1)
babel-plugin-proposal-pipeline-operator โŒ (stage 0)
babel-plugin-proposal-private-methods โœ”๏ธ
babel-plugin-proposal-throw-expressions โŒ (stage 2)
babel-plugin-proposal-unicode-property-regex โŒ
babel-plugin-syntax-async-generators โœ”๏ธ
babel-plugin-syntax-bigint โœ”๏ธ
babel-plugin-syntax-class-properties โœ”๏ธ
babel-plugin-syntax-decorators โœ”๏ธ
babel-plugin-syntax-do-expressions โŒ (stage 1)
babel-plugin-syntax-dynamic-import โœ”๏ธ
babel-plugin-syntax-export-default-from โœ”๏ธ
babel-plugin-syntax-export-namespace-from โœ”๏ธ
babel-plugin-syntax-flow โŒ
babel-plugin-syntax-function-bind โŒ (stage 0)
babel-plugin-syntax-function-sent โŒ (stage 2)
babel-plugin-syntax-import-meta โŒ (stage 3, wip)
babel-plugin-syntax-json-strings โœ”๏ธ
babel-plugin-syntax-jsx โœ”๏ธ
babel-plugin-syntax-logical-assignment-operators โŒ (stage 1)
babel-plugin-syntax-nullish-coalescing-operator โœ”๏ธ
babel-plugin-syntax-numeric-separator โœ”๏ธ
babel-plugin-syntax-object-rest-spread โœ”๏ธ
babel-plugin-syntax-optional-catch-binding โœ”๏ธ
babel-plugin-syntax-optional-chaining โœ”๏ธ
babel-plugin-syntax-partial-application โŒ (stage 1)
babel-plugin-syntax-pipeline-operator โŒ (stage 0)
babel-plugin-syntax-throw-expressions โŒ (stage 2)
babel-plugin-syntax-top-level-await โœ”๏ธ
babel-plugin-syntax-typescript โœ”๏ธ
babel-plugin-transform-arrow-functions โœ”๏ธ
babel-plugin-transform-async-to-generator โœ”๏ธ
babel-plugin-transform-block-scoped-functions โœ”๏ธ
babel-plugin-transform-block-scoping โœ”๏ธ
babel-plugin-transform-classes โœ”๏ธ
babel-plugin-transform-computed-properties โœ”๏ธ
babel-plugin-transform-destructuring โœ”๏ธ
babel-plugin-transform-dotall-regex โŒ
babel-plugin-transform-duplicate-keys โœ”๏ธ
babel-plugin-transform-exponentiation-operator โœ”๏ธ
babel-plugin-transform-flow-comments โŒ
babel-plugin-transform-flow-strip-types โŒ
babel-plugin-transform-for-of โœ”๏ธ
babel-plugin-transform-function-name โœ”๏ธ
babel-plugin-transform-instanceof โœ”๏ธ
babel-plugin-transform-jscript โŒ
babel-plugin-transform-literals โœ”๏ธ
babel-plugin-transform-member-expression-literals โœ”๏ธ
babel-plugin-transform-modules-amd โœ”๏ธ
babel-plugin-transform-modules-commonjs โœ”๏ธ
babel-plugin-transform-modules-systemjs โŒ
babel-plugin-transform-modules-umd โœ”๏ธ
babel-plugin-transform-named-capturing-groups-regex โŒ
babel-plugin-transform-new-target โŒ
babel-plugin-transform-object-assign โŒ
babel-plugin-transform-object-set-prototype-of-to-assign โŒ
babel-plugin-transform-object-super โŒ
babel-plugin-transform-object-rest-spread โœ”๏ธ
babel-plugin-transform-parameters โœ”๏ธ
babel-plugin-transform-property-literals โœ”๏ธ
babel-plugin-transform-property-mutators โŒ
babel-plugin-transform-proto-to-assign โŒ
babel-plugin-transform-react-constant-elements โŒ
babel-plugin-transform-react-display-name โœ”๏ธ
babel-plugin-transform-react-inline-elements โŒ
babel-plugin-transform-react-jsx โœ”๏ธ
babel-plugin-transform-react-jsx-compat โŒ
babel-plugin-transform-react-jsx-self โœ”๏ธ
babel-plugin-transform-react-jsx-source โœ”๏ธ
babel-plugin-transform-regenerator โœ”๏ธ
babel-plugin-transform-reserved-words โœ”๏ธ
babel-plugin-transform-runtime โœ”๏ธ
babel-plugin-transform-shorthand-properties โœ”๏ธ
babel-plugin-transform-spread โœ”๏ธ
babel-plugin-transform-sticky-regex โœ”๏ธ
babel-plugin-transform-strict-mode โœ”๏ธ
babel-plugin-transform-template-literals โœ”๏ธ
babel-plugin-transform-typeof-symbol โœ”๏ธ
babel-plugin-transform-typescript โœ”๏ธ
babel-plugin-transform-unicode-regex โŒ
babel-preset-env โœ”๏ธ
babel-preset-env-standalone โŒ
babel-preset-flow โŒ
babel-preset-react โœ”๏ธ
babel-preset-stage-0 โŒ
babel-preset-stage-1 โŒ
babel-preset-stage-2 โŒ
babel-preset-stage-3 โŒ
babel-preset-typescript โœ”๏ธ
babel-register โœ”๏ธ (swc-register)

File: docs/config-js-minify.md


id: config-js-minify title: Configuring js minifier sidebar_label: Minification

Requires v1.2.67

Note: Currently, it's far from perfect. I decided to focus on real-world usages and only rules used by famous open source libraries are implemented. If the bundle size of your project is not good enough, please let me know. Feel free to file an issue or email me if it's a secret. ([email protected])


Config

The minifier uses options which is almost identical to it of terser.
Options like ie8 are ignored, but the minifier accepts it and ignores to be compatible with terser.

via .swcrc

You can configure javascript minifier using .swcrc.

Example .swcrc looks like:

jsonc
{
  "jsc": {
    "minify": {
      "compress": {
        "unused": true
      },
      "mangle": true
    }
  },
  // Enable minification in codgen.
  "minify": true
}

`jsc.minify.compress`

Type: boolean | object.

true is same as an empty object ({}).

json
{
  "jsc": {
    "minify": {
      "compress": true
    }
  }
}

is identical to

json
{
  "jsc": {
    "minify": {
      "compress": {}
    }
  }
}

Please refer to the compress option of terser.

`arguments`

Defaults to false.

`arrows`

Defaults to true.

`booleans`

Defaults to true.

`booleans_as_integers`

Defaults to false.

`collapse_vars`

Defaults to true.

`comparisons`

Defaults to true.

`computed_props`

Defaults to false.

`conditionals`

Defaults to false.

`dead_code`

Defaults to false.

`defaults`

Defaults to true.

`directives`

Defaults to false.

`drop_console`

Defaults to false.

`drop_debugger`

Defaults to true.

`ecma`

Defaults to 5.

`evaluate`

Defaults to true.

`global_defs`

Defaults to {}.

`hoist_funs`

Defaults to false.

`hoist_props`

Defaults to true.

`hoist_vars`

Defaults to false.

`ie8`

Ignored.

`if_return`

Defaults to true.

`inline`

Defaults to ``.

`join_vars`

Defaults to true.

`keep_classnames`

Defaults to false.

`keep_fargs`

Defaults to false.

`keep_infinity`

Defaults to false.

`loops`

Defaults to true.

`negate_iife`

Defaults to true.

`passes`

Defaults to 0, which means no limit.

`properties`

Defaults to true.

`pure_getters`

Defaults to ``.

`pure_funcs`

Defaults to [].
Type is an array of string.

`reduce_funcs`

Defaults to false.

`reduce_vars`

Defaults to false.

`sequences`

Defaults to true.

`side_effects`

Defaults to true.

`switches`

Defaults to false.

`top_retain`

Defaults to ``.

`toplevel`

Defaults to ``.

`typeofs`

Defaults to true.

`unsafe`

Defaults to false.

`unsafe_arrows`

Defaults to false.

`unsafe_comps`

Defaults to false.

`unsafe_Function`

Defaults to false.

`unsafe_math`

Defaults to false.

`unsafe_symbols`

Defaults to false.

`unsafe_methods`

Defaults to false.

`unsafe_proto`

Defaults to false.

`unsafe_regexp`

Defaults to false.

`unsafe_undefined`

Defaults to false.

`unused`

Defaults to true.

`module`

Ignored. Currently, all files are treated as module.

`jsc.minify.mangle`

Type: boolean | object.

true is same as an empty object ({}).

json
{
  "jsc": {
    "minify": {
      "mangle": true
    }
  }
}

is identical to

json
{
  "jsc": {
    "minify": {
      "mangle": {}
    }
  }
}

Please refer to the mangle option of terser.

`properties`

Defaults to false, and true is identical to {}.

`topLevel`

Defaults to false.
Aliased as toplevel for compatibility with terser.

`keepClassNames`

Defaults to false.

Aliased as keep_classnames for compatibility with terser.

`keepFnNames`

Defaults to false.

`keepFnNames`

Defaults to false.

`keepPrivateProps`

Defaults to false.

Aliased as keep_private_props for compatibility with terser.

`ie8`

Ignored.

`safari10`

Not implemented yet.

Usage

swc.minify(code, options)

This API exists on @swc/core.

Returns Promise<{ code: string, map: string }>.


This API is asynchronous and all of parsing, minification and code generation will be done in background thread.
The options argument is same as jsc.minify object.
You can use it like

js
import swc from "@swc/core";

const { code, map } = await swc.minify(
  "import foo from '@src/app'; console.log(foo)",
  {
    compress: false,
    mangle: true,
  }
);

expect(code).toMatchInlineSnapshot(`"import a from'@src/app';console.log(a);"`);

swc.minifySync(code, options)

This API exists on @swc/core, @swc/wasm, @swc/wasm-web.

Returns { code: string, map: string }.

Usage is similar to swc.minify.

APIs for WASM

Replacing terser without waiting for library developers

If you want to reduce build time without waiting for libraries developers to update their dependency, you can use resolution of yarn to override terser.

Add the code below to the package.json file.

json
"resolutions": { "terser": "npm:@swc/core" }

This will allow using the minifier of swc instead of terser for all nested dependencies.

After patching package.json, you should remove lockfile and reinstall dependencies.

sh
$ rm -rf node_modules yarn.lock
$ yarn

File: docs/config-js-module.md


id: config-js-module title: Configuring module using .swcrc sidebar_label: Module config

swc can transpile es6 modules to common js module, umd module or amd module.
If you don't specify module type, module statements will remain untouched.

shared options

These options are shared by commonjs / es6 / umd / amd.

.swcrc:

json
{
  "module": {
    // You can specify "commonjs", "es6", "amd", "umd"
    "type": "commonjs",
    "strict": false,
    "strictMode": true,
    "lazy": false,
    "noInterop": false,
    "ignoreDynamic": false
  }
}

strict

By default, when using exports with swc a non-enumerable __esModule property is exported. In some cases, this property is used to determine if the import is the default export or if it contains the default export.

To prevent the __esModule property from being exported, you can set the strict option to true.

Defaults to false.

strictMode

If true, swc emits 'use strict' directive.

Defaults to true.

lazy

Changes Babel's compiled import statements to be lazily evaluated when their imported bindings are used for the first time. This can improve the initial load time of your module because evaluating dependencies upfront is sometimes entirely unnecessary. This is especially the case when implementing a library module.

The value of lazy has a few possible effects:

  • false - No lazy initialization of any imported module.
  • true - Do not lazy-initialize local ./foo imports, but lazy-init foo dependencies.
    Local paths are much more likely to have circular dependencies, which may break if loaded lazily,
    so they are not lazy by default, whereas dependencies between independent modules are rarely cyclical.
  • Array<string> - Lazy-initialize all imports with source matching one of the given strings.

The two cases where imports can never be lazy are:

  • import "foo";
    Side-effect imports are automatically non-lazy since their very existence means that there is no binding to later kick-off initialization.
  • export from "foo"
    Re-exporting all names requires up-front execution because otherwise there is no
    way to know what names need to be exported.

Defaults to false.

noInterop

By default, when using exports with swc a non-enumerable __esModule property is exported.
This property is then used to determine if the import is the default export or if it contains the default export.

In cases where the auto-unwrapping of default is not needed, you can set the noInterop option to true to avoid the usage of the interopRequireDefault helper (shown in inline form above).

Defaults to false.

ignoreDynamic

If you set this to true, dynamic imports will be preserved.

commonjs

To emit a common js module, you can do so by

.swcrc:

json
{
  "module": {
    "type": "commonjs",

    // These are defaults.
    "strict": false,
    "strictMode": true,
    "lazy": false,
    "noInterop": false
  }
}

es6

To emit an ES6 module, you can do so by

.swcrc:

json
{
  "module": {
    "type": "es6",

    // These are defaults.
    "strict": false,
    "strictMode": true,
    "lazy": false,
    "noInterop": false
  }
}

amd

To emit amd module, you can do so by

.swcrc:

json
{
  "module": {
    "type": "amd",
    // Optional. If specified, swc emits named amd module.
    "moduleId": "foo",

    // These are defaults.
    "strict": false,
    "strictMode": true,
    "lazy": false,
    "noInterop": false
  }
}

moduleId

Defaults to undefined. If specified, swc emits named amd module.

umd

To emit umd module, you can do so by

.swcrc:

json
{
  "module": {
    "type": "umd",
    "globals": {},

    // These are defaults.
    "strict": false,
    "strictMode": true,
    "lazy": false,
    "noInterop": false
  }
}

globals

TODO


File: docs/configuring-preset-env.md


id: preset-env title: preset-env sidebar_label: preset-env

Starting with v1.1.10, you can now use browserslist to automaticallly configure swc.

You need to install browserslist to use this feature.

Usage

Example

.swcrc:

json
{
  "env": {
    "targets": {
      "chrome": "79"
    },
    "mode": "entry",
    "coreJs": 3
  }
}

browserslist

If you want to use browserslist with swc, you can just omit targets field like

.swcrc:

json
{
  "env": {
    "coreJs": 3
  }
}

Note that browserlists can be configured in multiple ways.

  • .browserslistrc
  • browserslist field in package.json

You can use path to specify a custom path to load these configuration files from.

Options

targets

string | Array<string> | { [string]: string }, defaults to {}.

Describes the environments you support/target for your project.

This can either be a browserslist-compatible query:

json
{
  "env": {
    "targets": "> 0.25%, not dead"
  }
}

Or an object of minimum environment versions to support:

json
{
  "env": {
    "targets": {
      "chrome": "58",
      "ie": "11"
    }
  }
}

Example environments: chrome, opera, edge, firefox, safari, ie, ios, android, node, electron.

If targets is not specified, swc uses browserslist to get target information. See browserslist

path

string, defaults to current directory.

The path specifies the directory to load the browserslist module and any browserslist configuration files
(e.g. .browserslistrc, browserslist field in package.json).

This can be useful if your build system isn't in the root of your project.

mode

See: https://babeljs.io/docs/en/babel-preset-env#usebuiltins

Possible values: usage, entry, undefined
Defaults to undefined.

Note: Currently usage is not efficient as one of babel. Even though, it does not matter in real world codes.

debug

Defaults to false.

dynamicImport

Defaults to false.

loose

boolean, defaults to false.

Enable "loose" transformations for any plugins in this preset that allow them.

skip

Skip some es features. You can use this option to reduce bundle size.

For example, to exclude core-js/modules/foo, you can use

.swcrc:

json
{
  "env": {
    "skip": ["core-js/modules/foo"]
  }
}

include

  • Type is string[]
  • can be a core-js module (es.math.sign) or a swc pass (transform-spread)

exclude

  • string[]
  • can be a core-js module (es.math.sign) or a swc pass (transform-spread)

coreJs

The version of the used core js. Defaults to undefined, which panic when mode is configured.

shippedProposals

  • boolean
  • Defaults to false.

forceAllTransforms

  • boolean
  • Defaults to false.

Enable all transforms


File: docs/configuring-swc.md


id: configuring-swc title: Configuring swc sidebar_label: Configuring swc

swc can be configured with .swcrc file.

preset-env

See preset-env for using swc with browserslist.

jsc

This is optional and defaults to

json
{
  "jsc": {
    "parser": {
      "syntax": "ecmascript",
      "jsx": false,
      "dynamicImport": false,
      "privateMethod": false,
      "functionBind": false,
      "exportDefaultFrom": false,
      "exportNamespaceFrom": false,
      "decorators": false,
      "decoratorsBeforeExport": false,
      "topLevelAwait": false,
      "importMeta": 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
  }
}

jsc.externalHelpers

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.

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.

Note: you must add @swc/helpers as a dependency in addition to @swc/core.

json
{
  "jsc": {
    "externalHelpers": true
  }
}

jsc.parser

typescript:

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

ecmascript:

json
{
  "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

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

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

jsc.loose

Starting from @swc/core v1.1.4, you can enable "loose" transformations by enabling jsc.loose which works like babel-preset-env loose mode.

See https://2ality.com/2015/12/babel6-loose-mode.html

json
{
  "jsc": {
    "loose": true
  }
}

jsc.transform

Example

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

jsc.transform.legacyDecorator

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

To enable legacy decorators, set jsc.transform.legacyDecorator and jsc.parser.decorators to true.

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

jsc.transform.decoratorMetadata

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

e.g.

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

Note: This feature requires v1.2.13+.

jsc.transform.react

jsc.transform.react.runtime

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

  • Use runtime: automatic to use a JSX runtime module (e.g. react/jsx-runtime introduced in React 17).
  • Use runtime: classic to use React.createElement instead - with this option, you must ensure that React is in scope when using JSX.

See https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html

jsc.transform.react.importSource

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

Defaults to react.

This option can be overrided with @jsxImportSource foo.

jsc.transform.react.pragma

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

Defaults to React.createElement.

This option can be overrided with @jsx foo.

jsc.transform.react.pragmaFrag

Replace the component used when compiling JSX fragments.

Defaults to React.Fragment

This option can be overrided with @jsxFrag foo.

jsc.transform.react.throwIfNamespace

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

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

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

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

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

jsc.transform.react.refresh

Enable react-refresh related transform. Defaults to false as it's considered experimental.

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

ts
interface ReactRefreshConfig {
  /** @default "$RefreshReg$" */
  refreshReg: String;
  /** @default "$RefreshSig$" */
  refreshSig: String;
  /** @default false */
  emitFullSignatures: boolean;
}

jsc.transform.constModules

.swcrc:

json
{
  "jsc": {
    "transform": {
      "constModules": {
        "globals": {
          "@ember/env-flags": {
            "DEBUG": "true"
          },
          "@ember/features": {
            "FEATURE_A": "false",
            "FEATURE_B": "true"
          }
        }
      }
    }
  }
}
js
import { DEBUG } from "@ember/env-flags";
import { FEATURE_A, FEATURE_B } from "@ember/features";

console.log(DEBUG, FEATURE_A, FEATURE_B);

becomes

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

`jsc.transform.optimizer`

Note: Optimizer of the swc assumes

  • It's a module or wrapped in an iife.
  • 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.
  • Files are served as gzipped.

It means that swc will not focus on reducing the size of non-gzipped file size.

Setting this to undefined skips optimizer pass

jsc.transform.optimizer.simplify

Starting from v1.2.101, you can set this value to false to use inline_globals while skipping optimizations.

e.g.
.swcrc:

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

jsc.transform.optimizer.globals

  • vars
    Variables to inline.

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

This option requires v1.2.101 or upper.

e.g.
.swcrc:

json
{
  "jsc": {
    "transform": {
      "optimizer": {
        "globals": {
          "vars": {
            "__DEBUG__": "true"
          }
        }
      }
    }
  }
}

npx swc '__DEBUG__' --filename input.js:

js
true;

jsc.transform.optimizer.jsonify

Note: This feature requires v1.1.1+

  • 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.

e.g.
.swcrc:

json
{
  "jsc": {
    "transform": {
      "optimizer": {
        "jsonify": {
          "minCost": 0
        }
      }
    }
  }
}

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

jsc.keepClassNames

Requires v1.2.50 or upper and requires target to be es2016 or upper.

Enabling this option will make swc preserve original class names.

`jsc.paths`

Requires [email protected]

Syntax is identical as it of tsconfig.json.

See https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-mapping for more details.

Requires jsc.baseUrl. See below.

`jsc.baseUrl`

See https://www.typescriptlang.org/docs/handbook/module-resolution.html#base-url

`jsc.minify`

Requires [email protected]

See the documentation for minification for more details.

`jsc.experimental`

Experimental features can be removed, or modified with a semver-incompatible way.
Use at your own risk.

Currently there's no experimental options.

module

To configure module system, see the docs for it.

minify

To get minified output, you can configure swc by

.swcrc:

json
{
  "minify": true
}

Multiple entries

Starting with v1.0.47, you can specify multiple entries. For example,

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

this make swc compile javascript files as common js module (uses require('foo')) and compile typescript files as amd modules.

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

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

test

Type: Regex / Regex[]

Usage:

.swcrc:

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

exclude

Type: Regex / Regex[]

.swcrc:

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

`sourceMaps`

Starting from v1.2.50, you can enable source map by adding sourceMaps: true or sourceMaps: 'inline' to the .swcrc.

Example:

json
{
  "sourceMaps": true
}

`inlineSourcesContent`

Starting from v1.2.101, this is true by default.

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

Example:

json
{
  "sourceMaps": true,
  "inlineSourcesContent": true
}

File: docs/installation.md


id: installation title: Installation

You can install swc with

sh
npm i -D @swc/core @swc/cli

or

sh
yarn add --dev @swc/core @swc/cli

This will download a prebuilt binary instead of building swc if possible.
Currently prebuilt binaries are provided only for mac (x64) / linux (x86_64) / win32-x64 / apple silicon / linux aarch64 / - linux armv7 / android aarch64 / windows ia32.

To use on Alpine Linux, also install the @swc/core-linux-musl npm package.


File: docs/migrating-from-babel-cli.md


id: migrating-from-babel-cli title: Migrating from babel cli sidebar_label: "@babel/cli"

Installation

Run

sh
npm i --save-dev @swc/cli @swc/core

or

sh
yarn add --dev @swc/cli @swc/core

CLI apis of @swc/cli are intentionally almost same as it of @babel/cli. So you can just replace npx babel to npx swc. If it results in an error, please [report an error][issues].


File: docs/migrating-from-babel-core.md


id: migrating-from-babel-core title: "Migrating from @babel/core" sidebar_label: "@babel/core"

Installation

Run

sh
npm i --save-dev @swc/core

or

sh
yarn add --dev @swc/core

Usage


File: docs/repl.md


id: online-repl title: Online Repl sidebar_label: Online Repl author: Joel Mun authorURL: "http://github.com/9oelM"

Moved to a dedicated page because of editor size.


File: docs/spack-basic.md


id: spack-basic title: Configuring spack sidebar_label: Configuring spack

Changes of name

The bundler of swc was called spack, but it will be changed to swcpack.
There's a project called spack, and it's much older than the bundler, so I think it's right to rename new tool.

The support for spack.config.js will be dropped in v2. It will be swcpack.config.js instead, although the new config file is not supported yet.

Config file

spack can be configured with spack.config.js. Config file for the spack is almost simillar to webpack. In future, I'll add a webpack-compatible plugin system.

Currently configuration items should be exported as common js exports, like

js
module.exports = {
  entry: {
    web: __dirname + "/src/index.ts",
  },
  output: {
    path: __dirname + "/lib",
  },
};

Note: In future, exporting config using ES modules will be supported.

If you want autocompletion or type checking for configuration, you can wrap with config function from @swc/core/spack. It's an identity function with type annotation.

ts
const { config } = require("@swc/core/spack");

module.exports = config({
  entry: {
    web: __dirname + "/src/index.ts",
  },
  output: {
    path: __dirname + "/lib",
  },
});

`mode`

Possible values: production, debug, none.

Currently this value is not used, but it will behave similarly to one of webpack.

`entry`

Determines the entry of bundling.
You may specify a file or a map of bundle name to file path.

Note: Currently this should be absolute path. You can use __dirname to create one.

But in future, spack will support using relative path and will resolve files relative to spack.config.js.

Example

ts
const { config } = require("@swc/core/spack");

module.exports = config({
  entry: __dirname + "/src/index.ts",
});

You can specify the name of bundle like following.

ts
const { config } = require("@swc/core/spack");

module.exports = config({
  entry: {
    web: __dirname + "/src/index.ts",
  },
});

`output`

You can change destination directory of the bundler using output.

Example

ts
const { config } = require("@swc/core/spack");

module.exports = config({
  output: {
    path: __dirname + "/lib",
    // Name is optional.
    name: "index.js",
  },
});

`options`

Used to control the behavior of swc. This field is optional.

See Options section of the swc doc for details.

Examples