当前位置:网站首页>SWC introduction

SWC introduction

2022-07-06 03:19:00 phial03

SWC Introduce

Let's take a look swc Of official Introduce :

SWC (stands for Speedy Web Compiler) is a super-fast TypeScript / JavaScript compiler written in Rust.

swc In fact, a large part of the reason for the emergence of the project is to replace babel, therefore babel yes , we have function He has almost all of them .

And babel The biggest difference may be : swc is super-fast

swc There is another sentence on the official website , It reflects his speed :

img

except swc In addition to the official publicity ,Next.js be based on swc Implemented a Rust compiler , Used to parse and compile 、 Packaging code . Here is Next.js combination swc A data given later :

img

So it can be seen simply from the above data swc The advantages of : Can improve development efficiency , Enhance the development experience .

Github

SWC Open source address
This is a man named kdy1 South Korea 97 The young man of... Is open source , It's awesome !
 Insert picture description here

swc Principle analysis

(1) Create a new one debug-swc project

$ cargo new debug-swc
$ cd debug-swc

The directory structure is as follows :

debug-swc
├── .gitignore
├── Cargo.toml
└── src
    └── main.rs

(2) Add dependency
Cargo.toml file ,[dependencies] Add the following content under the configuration item :

swc_ecma_parser = "0.31.2"
swc_common = "0.7.0"
swc_ecma_ast = "0.26.0"
swc_atoms = "0.2.2"

 Insert picture description here

(3) newly added test.js file
This file in the root directory , be used for debug swc For parsing , The contents are as follows ,

const i = 1;

(4) To write src/main.rs
The official example Crate: swc_ecma_parser Hardly need to make any changes .

In order to show swc analysis JavaScript Code results , I added a get_identifier_name function , Used to get test.js Variable names in the code i.

extern crate swc_common;
extern crate swc_ecma_parser;

use std::path::Path;
use swc_atoms::JsWord;
use swc_common::{
    
    errors::{
    ColorConfig, Handler},
    sync::Lrc,
    SourceMap,
};
use swc_ecma_ast::{
    Decl, Module, ModuleItem, Pat, Stmt};
use swc_ecma_parser::{
    lexer::Lexer, Parser, StringInput, Syntax};

fn main() {
    
    swc_common::GLOBALS.set(&swc_common::Globals::new(), || {
    
        let cm: Lrc<SourceMap> = Default::default();
        let handler = Handler::with_tty_emitter(
            ColorConfig::Auto, true, false, Some(cm.clone()));

        let fm = cm
            .load_file(Path::new("./test.js"))
            .expect("failed to load test.js");

        let lexer = Lexer::new(
            // We want to parse ecmascript
            Syntax::Es(Default::default()),
            // JscTarget defaults to es5
            Default::default(),
            StringInput::from(&*fm),
            None,
        );

        let mut parser = Parser::new_from(lexer);

        for e in parser.take_errors() {
    
            e.into_diagnostic(&handler).emit();
        }

        let module = parser
            .parse_module()
            .map_err(|e| {
    
                // Unrecoverable fatal error occurred
                e.into_diagnostic(&handler).emit()
            })
            .expect("failed to parser module");

        if let Ok(identifier_name) = get_identifier_name(&module) {
    
            println!("identifier name: {}", identifier_name);
        }
    });
}

fn get_identifier_name(module: &Module) -> Result<&JsWord, ()> {
    
    for module_item in &module.body {
    
        if let ModuleItem::Stmt(Stmt::Decl(Decl::Var(var))) = module_item {
    
            for decl in &var.decls {
    
                if let Pat::Ident(identifier) = &decl.name {
    
                    return Ok(&identifier.id.sym);
                }
            }
        }
    }
    Err(())
}

src/main.rs The complete source code of can be seen here :github: debug-swc/src/main.rs

(4) Take a look at the execution results

$ cargo run

perform cargo run We'll do it first cargo build, The final results are as follows ,
 Insert picture description here

We analyzed AST from test.js Get the variable name in the source code i.


Reference article :
swc–babel Replacement
Easy to use SWC
Next generation build tools
SWC Experience
Compiler tools SWC

原网站

版权声明
本文为[phial03]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060317123315.html