Skip to content
Advertisement

Migrating from Babel to SWC with React

TL;DR

How to translate a node script like this:

JavaScript

to use SWC instead of Babel?


Context

We recently upgraded our Next.js version. Next.js now supports SWC instead of Babel.

The unit tests for React in our project are written with RITEway. The test command is:

JavaScript

It transforms the files with Babel first because otherwise import statements and JSX would cause errors.

During our attempts to migrating to SWC, we had no luck with the CLI. However, we found the @swc-node/register package. It allowed us to transform our command like this:

JavaScript

which fixes new syntax like the import statement and a test like this would run:

JavaScript

However, tests for React components like this

JavaScript

still throw the following error:

JavaScript

How can we create that command so that it runs with SWC?

Advertisement

Answer

After some experimentation I found out that it works if you import React from 'react'; in every file (both the component as well as the test) and change the file extensions to .jsx as described in the docs.

However, this is unsatisfying, as we’d like to use React 17’s JSX transform feature to avoid having to import React in every file. Additionally, we’d like to keep all file endings .js.

We tried setting .swcrc without any luck so far.

I’m posting this answer here in case no way to configure .swcrc can be found.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement