Skip to content
文档
使用
打包

Bundling (swcpack)

🚧

This feature is still under construction.

SWC is able to bundle multiple JavaScript or TypeScript files into one.

This feature is currently named spack, but will be renamed to swcpack in v2. spack.config.js will be deprecated for swcpack.config.js.

View a basic example of bundling (opens in a new tab).

Usage

pnpm i -D @swc/cli @swc/core

Create a spack.config.js file and run:

npx spack

Configuration

To see all options, view the configuration.

Features

Compact Output

Just like rollup, SWC emits compact output.

a.js
console.log("loading A");
export function a() {
  console.log("use!");
}
lib.js
import { a } from "./a";
a();

becomes:

output.js
console.log("loading A");
function a() {
  console.log("use!");
}
a();

SWC was designed with merging in mind, so naming collisions between multiple files are automatically handled.

Tree Shaking

Just like other modern bundlers, SWC can remove unused exports.

Import Deglobbing

To aid with tree-shaking, SWC deglobs imports if possible.

import * as lib from "lib";
lib.foo();

behaves exactly same as:

import { foo } from "lib";
foo();

This preserves all side effects.

CommonJS Support

SWC supports importing CommonJS modules and emits more compact output than webpack.

source.js
import * as lib from "lib";
console.log(lib); // Prevent dce

If the lib above is a CommonJS module, it's transcompiled to:

output.js
const load = __spack_require.bind(void 0, function (module, exports) {
  // Code from lib goes here
});
const lib = load();
console.log(lib); // Prevent dce

Optimizations

  • Global Inlining (e.g. process.env.NODE_ENV)
  • Inlining
  • Constant propagation
  • Dead code elimination

The tree shaking described above is using the dead code elimination pass. Currently, SWC can deduce:

source.js
let b = 2;
let a = 1;
if (b) {
  a = 2;
}
let c;
if (a) {
  c = 3;
}
console.log(c);

into:

output.js
console.log(3);

High Performance

Performance is a priority for SWC. It's very fast because it uses all CPU cores and is optimized by llvm.

Multiple Entries Support

spack.config.js
const { config } = require("@swc/core/spack");
 
module.exports = config({
  entry: {
    web: __dirname + "/src/web.ts",
    android: __dirname + "/src/android.ts",
  },
  output: {
    path: __dirname + "/lib",
  },
  module: {},
});

Built-in Chunking

Using the same config as above, if android.ts and web.ts both references the same file, it will be extracted as a separate chunk and web.ts and android.ts will import it.