iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🐧

Creating an SWC plugin and integrating it into Next.js

に公開

Next.js v12.2.0 introduced support for SWC plugins 🎉

https://nextjs.org/blog/next-12-2

I've always enjoyed creating Babel and ESLint plugins, so I decided to take this opportunity to create an SWC plugin and try applying it to Next.js. I'll document that process in this article.

https://github.com/nissy-dev/swc-plugin-react-native-web

The SWC Plugin to be Created

This time, I set a goal to replace babel-plugin-react-native-web with an SWC plugin so that I could run the official Next.js sample for React Native for Web. babel-plugin-react-native-web is a plugin that transforms import/export statements like this:

+ import ReactNative from "react-native"; // Before transformation
- import ReactNative from "react-native-web/dist/index"; // After transformation

+ import { View, Text } from "react-native"; // Before transformation
- import View from "react-native-web/dist/exports/View"; // After transformation
- import Text from "react-native-web/dist/exports/Text"; // After transformation

+ export { View } from "react-native"; // Before transformation
- export { default as View } from "react-native-web/dist/exports/View"; // After transformation

The main reasons for choosing this plugin were that I happened to find a discussion on Next.js suggesting there might be a need for an SWC plugin for React Native for Web, and that the implementation of babel-plugin-react-native-web was relatively lightweight.

https://github.com/vercel/next.js/discussions/36566

Creating an SWC Plugin

Creating a Project

SWC provides a CLI that allows you to create template projects for plugins. When making an SWC plugin, first execute the commands as described in this documentation.

// if you haven't, add build targets for webassembly
rustup target add wasm32-wasi wasm32-unknown-unknown

cargo install swc_cli

swc plugin new swc-plugin-react-native-web --target-type wasm32-wasi

Implementing Tests

Once the project is created, start implementing tests. Looking at the test code for swc_ecma_transforms_module in SWC as a reference, it seems there are two main ways to implement tests:

  • Tests that run using input and output defined as strings (using the test! macro from swc_ecma_transforms_testing).
  • Tests that run using JS files containing input and output (using the test_fixture! macro from swc_ecma_transforms_testing).

This time, I implemented it using the test! macro in src/lib.rs because preparing separate files for input and output was a bit of a hassle. During implementation, I referred to swc-plugin-valtio, which is introduced in "Migrating a Real-World Babel Plugin to an SWC Plugin".

Add the necessary crates for testing to Cargo.toml. (Please use appropriate versions.)

[dev-dependencies]
swc_ecma_parser = "0.105.6"
swc_ecma_transforms_testing = "0.91.0"

Using the added crates, write the actual test code as follows:

#[cfg(test)]
mod transform_visitor_tests {
    use swc_ecma_parser::{EsConfig, Syntax};
    use swc_ecma_transforms_testing::test;

    use super::*;

    fn transform_visitor() -> impl 'static + Fold + VisitMut {
        as_folder(TransformVisitor::new())
    }

    test!(
        Syntax::Es(EsConfig {
            jsx: true,
            ..Default::default()
        }),
        |_| transform_visitor(),
        test_sample,
        // Before transformation
        r#"
        import ReactNative from "react-native";
        import { View, Text } from "react-native";
        export { View } from "react-native";
        "#,
        // After transformation
        r#"
        import ReactNative from "react-native-web/dist/index";
        import View from "react-native-web/dist/exports/View";
        import Text from "react-native-web/dist/exports/View";
        export { default as View } from "react-native-web/dist/exports/View"
        "#
    );
}

As for the test cases, I prepared the same ones as those described in babel-plugin-react-native-web.

Implementing the Plugin

Once the tests are created, you write the actual plugin implementation in src/lib.rs. Regarding the implementation, you're basically replacing the Babel plugin logic written in JS with Rust. However, it's quite a challenge because the path.replaceXXX series of functions available in Babel plugins aren't provided in SWC. For instance, babel-plugin-react-native-web used path.replaceWithMultiple to replace a single AST node with multiple transformed ones. To address this, I implemented it using visit_mut_module, referring to the implementation of swc-plugin-valtio. The specific implementation flow is as follows:

  • Find AST nodes related to import/export statements that load "react-native".
  • If a target node exists, create the transformed AST nodes and store the index of the target node and the array of transformed AST nodes in a HashMap.
  • Perform the replacement of import/export statements using the HashMap.

Additionally, babel-plugin-react-native-web has an option to change import paths for CommonJS. I implemented this option by referencing the styled-components SWC plugin.

#[derive(Debug, Default, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
    #[serde(default)]
    pub commonjs: bool,
}

#[plugin_transform]
pub fn process_transform(program: Program, metadata: TransformPluginProgramMetadata) -> Program {
    let mut visitor = TransformVisitor::new();
    // Since the string options are passed in metadata.plugin_config,
    // we use serde_json to deserialize them into the struct.
    let config = serde_json::from_str::<Config>(&metadata.plugin_config)
        .expect("invalid config for swc-plugin-react-native-web");
    // Pass the options to the visitor
    visitor.set_config(config.commonjs);
    program.fold_with(&mut as_folder(visitor))
}

Furthermore, I frequently consulted the Plugin cheatsheet, which summarizes SWC plugin tips such as the JsWord type and match expressions involving Box<T>.

https://swc.rs/docs/plugin/ecmascript/cheatsheet

Release

Once you have passed all the tests and finished the implementation of the plugin, compile the source code into WASM with the following command:

cargo prepublish --release

The following alias is registered in .cargo/config for prepublish when the project is created:

[alias]
prepublish = "build --target wasm32-wasi"

The generated WASM file is located at target/wasm32-wasi/release/your_plugin_name.wasm. Add this file to the main and files fields in your package.json and perform npm publish.

Using the SWC Plugin in Next.js

To use the SWC plugin you published to npm, edit next.config.js as follows:

/** @type {import('next').NextConfig} */
const nextConfig = {
  ...,
  experimental: {
    swcPlugins: [
      ["@nissy-dev/swc-plugin-react-native-web", { commonjs: true }],
    ],
  },
};

swcPlugins accepts an array of tuples, where the first element is the path to the plugin and the second element is an object containing the plugin's options. The plugin path can be either the package name of an npm module or an absolute path to the .wasm binary itself. Even if you don't have any options to set, you still need to pass an empty object. For more details, refer to the following documentation:

https://github.com/vercel/next.js/blob/canary/docs/advanced-features/compiler.md#swc-plugins-experimental

Conclusion

In this article, I provided a brief overview of how to create an SWC plugin and how to introduce it into Next.js. For more specific implementation details, I would appreciate it if you could refer to the code in the actual repository.

As a side note, in the React Native for Web community, there are voices calling for migrating the Babel plugin for react-native-reanimated to an SWC plugin as well.

https://github.com/software-mansion/react-native-reanimated/discussions/2586

https://twitter.com/axeldelafosse/status/1493992830175481859

It's a complex Babel plugin with about 800 lines, but if you're comfortable with Babel plugins and Rust, it might be a great challenge to take on!

GitHubで編集を提案

Discussion