Nursing Code

Using SWC with Phoenix


I've recently been making some small contributions to swc, a super fast javascript / typescript compiler written in Rust.

It's orders of magnitude faster than Babel and requires significantly less memory and CPU cycles to get the transpilation process done.

I did some work to integrate it into the build process for an app using the Phoenix web framework.

Swapping Babel for SWC

Note -> I'll be using yarn rather than npm

In your assets folder.

Remove the following items from package.json

"@babel/core": "^7.0.0",
"@babel/preset-env": "^7.0.0",
"babel-loader": "^8.0.0",

Then run yarn add -D swc-loader. This will add the item to your package.json, fetch the dependency and remove the unused items from yarn.lock.

Next, in webpack.config.js, replace

      rules: [
        {
          test: /\.js$/,
          exclude: /node_modules/,
          use: {
            loader: 'babel-loader'
          }
        },

with

      rules: [
        {
          test: /\.(js|ts)$/,
          exclude: /node_modules/,
          loader: 'swc-loader',
        },

Notice that we've updated the config to use the swc-loader and also updated the test property to look at TypeScript files as well as javascript files.

We'll also update

      'app': glob.sync('./vendor/**/*.js').concat(['./js/app.js'])

to

    entry: {
      'app': glob.sync('./vendor/**/*.{js|ts}').concat(['./js/app.ts'])
    },

And rename app.js to app.ts

Add a tsconfig.json file. This is just an example, you'll need to set it up how you want it. Bear in mind that this primarily exists to tell your dev tools / text editor how to look at your project. It doesn't affect the output of SWC.

{
  "compilerOptions": {
    "target": "es2020",
    "moduleResolution": "node",
    "baseUrl": ".",
    "module": "es6",
    "allowSyntheticDefaultImports": true,
    "paths": {
      "*": [
        "types/*"
      ]
    }
  }
}

Configuring SWC

If you want to have some special configuration for the transpiled javascript, then you'll want to add an .swcrc file to provide options you want / needs. See config guide.

You can also use browserslist to target particular combinations of browsers.

Happy coding :)