New generation compiler SWC

Recently, there has been a rush of trust in the front-end circle. All front-end tools that can be rewritten with trust are rewritten with trust. The tool introduced today is bable: swc, a tool that converts ES6 into ES5.

Moreover, on the official website of swc, it is very straightforward to say that they are benchmarking with babel. swc and babel commands can be replaced with each other, and most babel plug-ins have been implemented.

One advantage of using t rust is that it is fast. For example, in our previous project, after replacing babel with swc, the compilation speed was increased from 7 seconds to 1 second, and the efficiency exploded directly.

Get started

Like babel, swc divides command line tools and compilation core modules into two packages.

  • @swc/cli is similar to @ babel/cli;
  • @swc/core is similar to @ babel/core;
npm i -D @swc/cli @swc/core

You can convert an ES6 JS file to ES5 through the following command.

npx swc source.js -o dist.js

Here is source JS code:

const start = () => {
  console.log('app started')
}

The code includes two features of ES6, const declaration and arrow function. After swc transformation, these two features are transformed into var declaration and function anonymous function respectively.

configuration file

swc, like babel, supports similar Configuration file for babelrc: swcrc, the configured format is JSON.

{
  "jsc": { // Compilation Rules
    "target": "es5", // Specification of output js
    "parser": {
      // In addition to ecmascript, typescript is also supported
      "syntax": "ecmascript",
      // Whether to parse jsx, corresponding to plug-in @ Babel / plugin transform react jsx
      "jsx": false,
      // Whether decorators are supported, corresponding to the plug-in @ Babel / plugin syntax decorators
      "decorators": false,
      // Whether dynamic import is supported, corresponding to the plug-in @ Babel / plugin syntax dynamic import
      "dynamicImport": false,
      // ......
      // Most of babel's plug-ins can find the corresponding configuration here
    },
    "minify": {}, // For compression related configurations, you need to start compression first
  },
  "env": { // Compilation result related configuration
    "targets": { // The compilation result requires an appropriate browser
      "ie": "11" // Compatible to ie 11 only
    },
    "corejs": "3" // Version of corejs
  },
  "minify": true // Turn on compression
}

babel's plug-in system is integrated into JSC by swc Basically, most plug-ins can take care of the configuration in parser. Moreover, swc also inherits the ability of compression, which is enabled through the minify attribute, JSC Minify is used to configure compression related rules. More detailed configurations can be viewed file.

Node APIs

Through the node JS code, import the @ swc/core module, which can be found in node In JS, calling api directly compiles the code, which is a routine operation for the development of CLI tools.

// swc.mjs
import { readFileSync } from 'fs'
import { transform } from '@swc/core'

const run = async () => {
  const code = readFileSync('./source.js', 'utf-8')
    const result = await transform(code, {
    filename: "source.js",
  })
  // Output compiled code
  console.log(result.code)
}

run()

Packaging code

In addition to escaping code, swc also provides a simple packaging capability. We create a new src folder and two new files in it: index js,utils.js.

// src/index.js
import { log } from './utils.js'
const start = () => log('app started')
start()
// src/utils.js
export const log = function () {
  console.log(...arguments)
}
export const errorLog = function () {
  console.error(...arguments)
}

You can see the index JS imported utils JS, and then we create a new spack config. JS file, which is the swc packaged configuration file.

// spack.config.js
module.exports = {
  entry: {
    // Packaged entrance
    web: __dirname + "/src/index.js",
  },
  output: {
    // Folder for output after packaging
    path: __dirname + "/dist",
  },
};

Then run on the command line:

$ npx spack

After successful packaging, a web. XML file will be output in dist directory JS file.

As you can see, not only index js,utils.js is packaged into a file, and tree shaking is carried out to convert utils The errorLog method not used in JS is deleted.

Can I use it?

After all, after so many years of development, babel is far better than swc in terms of bug loss and community activity. Therefore, if it is a small product to test the water, you can still try swc. If babel has been used in the old project, it is not recommended to migrate.

In the process of using, some small problems were found. For example, if I use async function, swc will automatically import the regenerator runtime module.

// Before compilation, there is an async method
const start = async () => {
  console.log('app started')
}

After calling swc for compilation, the code is as follows:

This result seems to be OK, but swc, like babel, also has helpers (@ swc/helpers) and provides the externalHelpers switch. If externalHelpers is set to true, swc will import some tool classes in the form of modules.

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

The default value of external helpers is false. At this time, is the regenerator runtime imported in the form of modules or written to the file?

swc happens to have an issue[ https://github.com/swc-projec...]](https://github.com/swc-projec... )We are discussing this problem.

In addition to the problem mentioned above, there is another point. The author thinks there is a problem with the previous architecture and is stepping up rewriting version 2.0. I feel I can look forward to it. In addition, the author of swc is a Korean brother in 1997. At present, I haven't graduated from college. Finally, I can only say: cow!

Keywords: Javascript Rust Babel

Added by Brokenhope on Thu, 13 Jan 2022 13:23:59 +0200