swc is a super-fast compiler written in rust; producing widely-supported javascript from modern standards and typescript.

Overview

babel

Make the web (development) faster.

npm Downloads undefined

CI Status

SWC (stands for Speedy Web Compiler) is a super-fast TypeScript / JavaScript compiler written in Rust. It's a library for Rust and JavaScript at the same time. If you are using SWC from Rust, see rustdoc and for most users, your entry point for using the library will be parser.

If you are using SWC from JavaScript, please refer to docs on the website.

Documentation

Check out the documentation in the website.

Features

Please see comparison with babel.

Performance

Please see benchmark results on the website.

Supporting swc

Backers on Open Collective Gold sponsors on Open Collective Silver sponsors on Open Collective Bronze sponsors on Open Collective

SWC is a community-driven project, and is maintained by a group of volunteers. If you'd like to help support the future of the project, please consider:

Contributing

See CONTRIBUTING.md. You may also find the architecture documentation useful (ARCHITECTURE.md).

License

SWC is primarily distributed under the terms of both the MIT license and the Apache License (Version 2.0).

See LICENSE-APACHE and LICENSE-MIT for details.

Comments
  • feat(node-swc): Babel ast translator

    feat(node-swc): Babel ast translator

    This pull request is a WIP.

    • [x] Translate babel AST definitions to rust
    • [x] Implement convert functions for swc --> babel
    • [x] Write tests

    Let me know if there's anything missing from the todo list.

    opened by dwoznicki 82
  • Comments on types are stripped

    Comments on types are stripped

    Describe the bug

    Comments are stripped due to unknown reasons, against expectation.

    Input code

    // FILE bad.ts:
    
    /* istanbul ignore next */
    type Z = number;
    x = 1;
    
    
    // FILE good.ts
    /* istanbul ignore next */
    x = 1;
    

    Config

    {
      "jsc": {
        "transform": {}
      },
      "swcrc": true
    }
    

    Playground link

    https://play.swc.rs/?version=1.2.117&code=H4sIAAAAAAAAAzXMOwrAIBBF0d5VvFoCklqykXQahjigY4hjPruPTdpz4ToLbhok9gzepZ4EoUdhnXEO%2Bh6EFQukl0inx7AuWy2FRKGJGzILTbiDbmkA4Y8h1otwBeGWzDMWszcfPlBa620AAAA%3D&config=H4sIAAAAAAAAA6tWys3My0yrVLJKS8wpTtVRyipOVrKqVipILCpOLQKxiivzShIrlKyUSioLUouTizILSpRqa2sBrzFAMDkAAAA%3D

    Expected behavior

    bad.ts should emit:

    /* istanbul ignore next */
    x = 1;
    

    but does emit:

    x = 1;
    

    dropping the istanbul comment

    Version

    1.2.117

    Additional context

    No response

    enhancement 
    opened by cdaringe 54
  • Investigate performance issues for experimental plugin

    Investigate performance issues for experimental plugin

    I wrote a fairly simple plugin to extract the first string literal argument from calls to i18n.get, in order to collect translation strings that are used.

    My goal was to transform an input file into a JSON array of strings. Please disregard that it currently will emit a semicolon at the end of that array :-)

    use std::vec::Vec;
    use swc_plugin::{ast::*, plugin_transform, syntax_pos::DUMMY_SP};
    
    pub struct I18NVisitor {
        strings: Vec<String>,
    }
    
    impl Default for I18NVisitor {
        fn default() -> I18NVisitor {
            I18NVisitor {
                strings: Vec::new(),
            }
        }
    }
    
    impl Visit for I18NVisitor {
        noop_visit_type!();
    
        fn visit_call_expr(&mut self, call_expr: &CallExpr) {
            if let Callee::Expr(expr) = &call_expr.callee {
                if let Expr::Member(member_expr) = &**expr {
                    if let (Expr::Ident(obj_id), MemberProp::Ident(prop_id)) =
                        (&*member_expr.obj, &member_expr.prop)
                    {
                        if &*obj_id.sym == "i18n" && &*prop_id.sym == "get" {
                            let args = &call_expr.args;
                            let arg0 = &args[0];
                            let expr = &arg0.expr;
                            if let Expr::Lit(lit_expr) = &**expr {
                                if let Lit::Str(str_lit) = lit_expr {
                                    self.strings.push(str_lit.value.to_string());
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    
    #[plugin_transform]
    pub fn process_transform(program: Program, _config: String, _context: String) -> Program {
        let mut visitor = I18NVisitor::default();
    
        program.visit_with(&mut visitor);
    
        let strs = visitor.strings.into_iter().map(|s| {
            Some(ExprOrSpread {
                spread: None,
                expr: Box::new(Expr::Lit(Lit::Str(Str {
                    span: DUMMY_SP,
                    has_escape: false,
                    kind: StrKind::default(),
                    value: JsWord::from(s),
                }))),
            })
        });
        let expr = Box::new(Expr::Array(ArrayLit {
            span: DUMMY_SP,
            elems: strs.collect(),
        }));
        let stmt = Stmt::Expr(ExprStmt {
            span: DUMMY_SP,
            expr,
        });
        let body = Vec::from([ModuleItem::Stmt(stmt)]);
    
        return Program::Module(Module {
            span: DUMMY_SP,
            body,
            shebang: None,
        });
    }
    

    Now when trying this WASM plugin, it is a lot slower than the equivalent JavaScript version while processing about 4500 files individually. The JavaScript version takes about 5 seconds (using parseFile + visitor.visitModule), while the Rust WASM plugin version takes about a minute (using a lot more CPU as well!) and sometimes actually crashes with (likely caused by my lacking knowledge of writing code in Rust):

    ✘ [ERROR] [plugin i18n-plugin] failed to handle: failed to invoke plugin: failed to invoke `./swc_i18n.wasm` as js transform plugin at swc_i18n.wasm
    
    Caused by:
        0: RuntimeError: out of bounds memory access
               at dlfree (<module>[538]:0xce51b)
               at free (<module>[537]:0xce131)
               at __plugin_process_impl (<module>[34]:0x7534)
               at __plugin_process_impl.command_export (<module>[566]:0xd0534)
        1: heap_get_oob
    

    It is invoked via transformFile inside an esbuild build script as follows:

    await transformFile(filePath, {
        syntax: 'typescript',
        tsx: true,
        jsc: {
        parser: {
            syntax: 'typescript',
            tsx: true,
        },
        experimental: {
            plugins: [['./swc_i18n.wasm', {}]],
        },
        },
    });
    

    Using @swc/core version 1.2.140 (JS) & swc_plugin version 0.27.0 (Rust)

    I hoped I could speed things up even further using a native plugin, but got the opposite. What am I doing wrong? :)

    Originally posted by @fxb in https://github.com/swc-project/swc/discussions/3540#discussioncomment-2186990

    A: plugin 
    opened by kwonoj 38
  • Feature request: regenerator-runtime should be inlined when externalHelpers is false (or offer the functionality to do so)

    Feature request: regenerator-runtime should be inlined when externalHelpers is false (or offer the functionality to do so)

    Describe the feature

    swc comes with a set of helper functions, all of which are inlined by default. However, it leverages regenerator-runtime for transforming async- and generator functions. However, even when externalHelpers are false (the default option), regenerator-runtime is included via a require("regenerator-runtime") call.

    To my knowledge, there is no way to configure swc to inline regenerator-runtime.

    The only way to work around it is by transforming the output of swc to manually remove the require() call and inline it, which is cumbersome and slow.

    Proposed solution

    Ideally, externalHelpers should be respected, since regenerator-runtime is being used by swc as a helper function.

    Alternatively, at the very least, it should be customizable whether or not regenerator-runtime is inlined.

    Any suggestions for workarounds are more than welcome.

    opened by wessberg 36
  • fix(plugin-runner): More details on pointer conversion failures

    fix(plugin-runner): More details on pointer conversion failures

    Description: This change set provides (1) additional debug infos in cases when conversions of pointers between the Rust world and the WASM world fail, and (2) fixes an existing misleading error message.

    Related issue (if exists): This should help to make progress addressing https://github.com/swc-project/swc/issues/6249.

    opened by stahlbauer 34
  • Circular class imports break when upgrading 1.2.205 -> 1.2.206

    Circular class imports break when upgrading 1.2.205 -> 1.2.206

    Describe the bug

    When upgrading from 1.2.205 to 1.2.206, SWC changes how it compiles exports.

    In version 1.2.205:

    Screenshot 2022-06-27 at 21 36 27

    In version 1.2.206:

    Screenshot 2022-06-27 at 21 49 11

    I have a bunch of model classes in my codebase, which of course circularly reference each other.

    To avoid circularity problems, the ORM I use uses the "late binding" hack popular in the JavaScript community, referencing bindings with anonymous functions, e.g. @OneToMany(() => Book) instead of just @OneToMany(Book). However, this seems to no longer work after the compilation change of SWC 1.2.206.

    Input code

    // Person.ts
    import { Book } from "./Book";
    
    export class Person {
        books = new Collection<Book>();
    }
    
    // Book.ts
    import { Person } from "./Person";
    
    export class Book {
        author?: Person;
    }
    

    Config

    {
      "jsc": {
        "parser": {
          "syntax": "typescript",
          "tsx": false,
          "decorators": true,
          "dynamicImport": true
        },
        "transform": {
          "legacyDecorator": true,
          "decoratorMetadata": true
        },
        "target": "es2018",
        "baseUrl": "src",
        "paths": {
          "lib/*": ["lib/*"],
          "app/*": ["app/*"],
          "fixtures/*": ["fixtures/*"],
          "test-utils/*": ["test-utils/*"]
        }
      },
      "module": {
        "type": "commonjs"
      }
    }
    

    Playground link

    No response

    Expected behavior

    Running this code after building it, or running it with node -r @swc/register should work.

    Actual behavior

    Running the code after building it, or running it with node -r @swc/register, produces this error:

    $ NODE_ENV=script node -r @swc/register src/fixtures/command.ts reapply
    /Users/kelley/mywheels/api/src/app/core/models/Fleet.ts:6
        get: ()=>Fleet,
                 ^
    
    ReferenceError: Cannot access 'Fleet' before initialization
        at Object.get [as Fleet] (/Users/kelley/mywheels/api/src/app/core/models/Fleet.ts:16:14)
        at Object.<anonymous> (/Users/kelley/mywheels/api/src/app/core/models/FleetContractType.ts:13:16)
        at Module._compile (node:internal/modules/cjs/loader:1103:14)
        at Module._compile (/Users/kelley/mywheels/api/node_modules/pirates/lib/index.js:99:24)
        at Module._extensions..js (node:internal/modules/cjs/loader:1157:10)
        at Object.newLoader [as .ts] (/Users/kelley/mywheels/api/node_modules/pirates/lib/index.js:104:7)
        at Module.load (node:internal/modules/cjs/loader:981:32)
        at Function.Module._load (node:internal/modules/cjs/loader:822:12)
        at Module.require (node:internal/modules/cjs/loader:1005:19)
        at require (node:internal/modules/cjs/helpers:102:18)
    error Command failed with exit code 1.
    

    Version

    1.2.206

    Additional context

    No response

    C-bug 
    opened by kelleyvanevert 34
  • `Cannot redefine property` error when using `jest.spyOn` after v1.2.206

    `Cannot redefine property` error when using `jest.spyOn` after v1.2.206

    Describe the bug

    SWC version v1.2.206 is causing our jest setup file to error out when calling jest.spyOn. v1.2.205 does not error out.

    Input code

    // jest.setup.ts
    import * as cache from './packages/foo/src/common/cache'
    const redis = new RedisMock(7481)
    beforeEach(() => {
      jest.spyOn(cache, 'getRedis').mockResolvedValue(redis)
    })
    
    // cache.ts
    import memoize from 'p-memoize'
    import { getConfig } from './config'
    export const getRedis = memoize(async () => {
      const config = await getConfig()
      return new Redis(config.redisUrl)
    })
    

    Config

    {
      "jsc": {
        "parser": {
          "syntax": "typescript",
          "decorators": true
        },
        "target": "es2021",
        "keepClassNames": true
      }
    }
    

    Playground link

    No response

    Expected behavior

    jest.spyOn should stub cache.getRedis

    Actual behavior

    jest.spyOn fails with the following error:

    TypeError: Cannot redefine property: getRedis
        at Function.defineProperty (<anonymous>)
        at ModuleMocker.spyOn (/home/circleci/project/node_modules/jest-mock/build/index.js:820:16)
        at Object.spyOn (/home/circleci/project/jest.setup.ts:26:8)
        at Promise.then.completed (/home/circleci/project/node_modules/jest-circus/build/utils.js:333:28)
        at new Promise (<anonymous>)
        at callAsyncCircusFn (/home/circleci/project/node_modules/jest-circus/build/utils.js:259:10)
        at _callCircusHook (/home/circleci/project/node_modules/jest-circus/build/run.js:240:40)
        at runMicrotasks (<anonymous>)
        at processTicksAndRejections (node:internal/process/task_queues:96:5)
        at _runTest (/home/circleci/project/node_modules/jest-circus/build/run.js:202:5)
    

    Version

    v1.2.206+

    Additional context

    No response

    C-bug 
    opened by ldiqual 29
  • [Meta] Plugin system for 2.0

    [Meta] Plugin system for 2.0

    I will modify this as required.

    Javascript plugins

    If it's possible to make it fast, I'll support js plugins, too.

    Rust-based plugins

    Tasks

    Task: Proxy swc_common (#2646)

    • swc_common: Create a trait for thread-local APIs. (cargo feature plugin-base)
    • swc_common: Implement the trait. (cargo feature plugin-rt)
    • swc_common: Replace APIs in plugin mode. (cargo feature plugin-mode)
    • Pass the trait to plugins and use it to replace swc_common APIs.

    Task: rplugin: System to pass AST directly (#2671)

    This is important for performance.

    Task: Share more input, like SourceMap or SourceFile.

    Task: Actaully use rplugin.

    Task: Improve plugin runner

    Task: Add plugin feature to swc

    Task: Expose node apis

    Design

    I experimented lots of ways for plugin system, and decided to go with abi_stable. But there's a problem.

    Problem: Identical API

    I want to provide identical API as core transforms. And it requires sharing data stored in thread-local variables.

    Triage: Dynamic library

    I initially thought I need to make swc_common a dynamic library so plugins can invoke it. But dynamic linking does not fit for swc plugins. As swc_common depends on std, the version of rustc should be all same among plugins, and chaning version of rustc becomes a huge breaking change. I don't want to break all plugins by upgrading rustc. So wee need another way than a dynamic library.


    I posted some questions on the rust community while trying this option, in case you are curious about what I tried.

    • https://www.reddit.com/r/rust/comments/ql1c5m/questions_about_sharing_thread_locals_between/
    • https://users.rust-lang.org/t/sharing-a-crate-with-crate-type-dylib/66768

    I also experimented with extern "C". See https://github.com/kdy1/rust-dylib-test

    Solution: Pass function to plugin with stable abi

    Instead of making swc_common dynamic library, we can pass a big trait that contains functions related to thread-local variables in swc_common.

    The plugin runner will pass this trait while invoking plugins. abi_stable can be used to do this.

    For plugins, operations of swc_common will be replaced by the trait. In other words, functions in swc_common will work by calling a method in the passed trait object.


    opened by kdy1 29
  • Migrate neon to napi-rs

    Migrate neon to napi-rs

    Started at https://github.com/napi-rs/node-rs/pull/34

    Benefits

    • Minimal overhead
    • Stable native API, easy to release Releases

    First benchmark in my local machine

    swc (es3) x 695 ops/sec ±1.92% (82 runs sampled)
    swc (es5) x 699 ops/sec ±1.14% (83 runs sampled)
    swc (es2015) x 667 ops/sec ±1.70% (85 runs sampled)
    swc (es2016) x 1,654 ops/sec ±1.62% (84 runs sampled)
    swc (es2017) x 1,630 ops/sec ±2.06% (85 runs sampled)
    swc (es2018) x 2,177 ops/sec ±1.63% (88 runs sampled)
    @node-rs/swc (es2018) x 5,538 ops/sec ±1.04% (86 runs sampled)
    swc-optimize (es3) x 1,555 ops/sec ±1.31% (85 runs sampled)
    babel (es5) x 32.78 ops/sec ±4.99% (52 runs sampled)
    
    opened by Brooooooklyn 29
  • Path aliases don't seem to respect nested folder structure

    Path aliases don't seem to respect nested folder structure

    Describe the bug After https://github.com/swc-project/swc/issues/1934 and https://github.com/swc-project/swc/issues/1935 were resolved in 1.2.76, I gave it a quick try and run into another issue.

    It seems to me that paths simply rewrites the path prefix but doesn't respect the location of given file. I also tried using baseUrl but no luck. Am I missing some configuration?

    Input code Using ~ as an alias for src and having a file src/subfolder/A.ts with an import { B } from '~/subfolder/B.ts'; (and considering the src/subfolder/B.ts exists and exports B), we'll run into Error: Cannot find module './subfolder/B'.

    This is because the import was rewritten to ./subfolder/B instead of just ./B or ../subfolder/B (that should be correct as these files are in the same subfolder indeed).

    The command I'm running is: yarn swc src -s -d ./dist

    Config Note that baseUrl probably has no effect but I tried to add it to conform with tsconfig.json.

    {
      "jsc": {
        "parser": {
          "syntax": "typescript",
        },
        "target": "es2020",
        "baseUrl": ".",
        "paths": {
          "~/*": ["./*"]
        }
      },
      "module": {
        "type": "commonjs"
      }
    }
    

    Also note that in TypeScript the correct path in the config would be "~/*": ["./src/*"] in this case (including the src portion) since baseUrl is .. With SWC, however, I need to use just ./*, probably because I'm passing src dir to the swc command.

    Expected behavior Paths should be rewritten using current file location (not just using a static prefix). In the given example the import from '~/subfolder/B.ts was rewritten to ./subfolder/B instead of just ./B (or ../subfolder/B).

    Version The version of @swc/core: 1.2.76

    Additional context TypeScript also uses baseUrl to set the base path relative to which imports are rewritten.

    C-bug 
    opened by JanJakes 28
  • feat(css/minifier) Static computation for 'calc' expressions

    feat(css/minifier) Static computation for 'calc' expressions

    Description:

    This is a first step to fold the "calc" expressions:

    • division operator is not (yet) included: i don't know if we want to transform "1/3" into "0,33333"
    • other optimizations could follow (operation with infinity, NaN, etc)

    BREAKING CHANGE:

    None except the CSS output

    Related issue (if exists): #5860

    opened by ghostd 26
  • install swc_cli failed

    install swc_cli failed

    Describe the bug

    I think we should have a pre dependencies doc for installing 'swc_cli', especially for newer.

    cargo install swc_cli
    

    Updating crates.io index Downloaded swc_cli v0.91.11 Downloaded 1 crate (32.9 KB) in 2.58s Installing swc_cli v0.91.11 error: failed to compile swc_cli v0.91.11, intermediate artifacts can be found at /var/folders/zd/lnd478dn09vgfd72vv8tzjrw0000gn/T/cargo-installVIvc8H

    Caused by: failed to select a version for the requirement swc_core = "^0.50.1" candidate versions found which didn't match: 0.23.5, 0.23.4, 0.23.3, ... location searched: crates.io index required by package swc_cli v0.91.11

    I looked the issues, and find the following commands:

    cargo install swc_cli --locked
    

    Updating crates.io index Installing swc_cli v0.91.11 error: failed to select a version for the requirement swc_core = "=0.50.3" candidate versions found which didn't match: 0.23.5, 0.23.4, 0.23.3, ... location searched: crates.io index required by package swc_cli v0.91.11

    and suddenly I find my rust version is nightly-x, it is slightly old version, and I switch to the 'stable-x86_64-apple-darwin ', then the installing work.

    Default host: x86_64-apple-darwin rustup home: /Users/lishoulong/.rustup

    installed toolchains

    stable-x86_64-apple-darwin nightly-2021-09-30-x86_64-apple-darwin (default)

    active toolchain

    nightly-2021-09-30-x86_64-apple-darwin (default) rustc 1.57.0-nightly (11491938f 2021-09-29)

    So i suggested we should add pre environments in the page

    Input code

    No response

    Config

    No response

    Playground link

    No response

    Expected behavior

    we should install swc_cli smoothly

    Actual behavior

    [it errors with ](error: failed to compile swc_cli v0.91.11)

    Version

    v0.91.11

    Additional context

    No response

    C-bug 
    opened by lishoulong 0
  • `dead_branch_remover` hoists variable out of function expressions

    `dead_branch_remover` hoists variable out of function expressions

    Describe the bug

    The dead_branch_remover hoists a variable out of a function expression in a dead branch, and then also doesn't remove the variable even though it was a dead branch.

    Input code

    if (false) {
        foo(function () {
            var module = {};
            return module;
        });
    }
    

    Config

    use std::collections::HashSet;
    
    use swc::{self};
    use swc_atoms::JsWord;
    use swc_common::{
        chain,
        comments::SingleThreadedComments,
        errors::{DiagnosticBuilder, Emitter, Handler},
        sync::Lrc,
        FileName, Globals, Mark, SourceMap, SyntaxContext, DUMMY_SP,
    };
    use swc_ecma_ast::{CatchClause, Decl, Id, Ident, Module, Pat, Stmt, VarDeclKind};
    use swc_ecma_codegen::{text_writer::JsWriter, Config};
    use swc_ecma_parser::{lexer::Lexer, EsConfig, PResult, Parser, StringInput, Syntax, TsConfig};
    use swc_ecma_preset_env::{preset_env, BrowserData, Mode, Targets, Version};
    use swc_ecma_transforms::{
        compat::reserved_words::reserved_words,
        fixer,
        fixer::paren_remover,
        helpers, hygiene,
        optimization::simplify::{dead_branch_remover, expr_simplifier},
        react::{self, Runtime},
        resolver,
    };
    use swc_ecma_visit::{Fold, FoldWith, Visit, VisitWith};
    
    #[derive(Debug, Clone, Default)]
    pub struct ErrorBuffer(std::sync::Arc<std::sync::Mutex<Vec<swc_common::errors::Diagnostic>>>);
    
    impl Emitter for ErrorBuffer {
        fn emit(&mut self, db: &DiagnosticBuilder) {
            self.0.lock().unwrap().push((**db).clone());
        }
    }
    
    fn main() {
        let cm = Lrc::<SourceMap>::default();
    
        let src = r#"
    if (false) {
        foo(function () {
            var module = {};
            return module;
        });
    }
    "#;
        let (module, comments) = parse(src, "test.js", &cm).unwrap();
    
        let error_buffer = ErrorBuffer::default();
        let handler = Handler::with_emitter(true, false, Box::new(error_buffer.clone()));
        swc_common::errors::HANDLER.set(&handler, || {
            swc_common::GLOBALS.set(&Globals::new(), || {
                helpers::HELPERS.set(&helpers::Helpers::new(true), || {
                    let unresolved_mark = Mark::fresh(Mark::root());
                    let top_level_mark = Mark::fresh(Mark::root());
                    let module =
                        module.fold_with(&mut resolver(unresolved_mark, top_level_mark, false));
    
                    let module = module.fold_with(&mut dead_branch_remover(unresolved_mark));
    
                    let module = module.fold_with(&mut chain!(
                        reserved_words(),
                        hygiene(),
                        fixer(Some(&comments))
                    ));
                    let code = emit(&module, &comments, cm);
                    println!("{}", code);
                });
            });
        });
    }
    
    
    fn parse(
        code: &str,
        filename: &str,
        cm: &Lrc<SourceMap>,
    ) -> PResult<(Module, SingleThreadedComments)> {
        let source_file = cm.new_source_file(FileName::Real(filename.into()), code.into());
        let comments = SingleThreadedComments::default();
    
        let lexer = Lexer::new(
            Syntax::Es(EsConfig {
                jsx: true,
                ..Default::default()
            }),
            // Syntax::Typescript(TsConfig {
            //     tsx: true,
            //     ..Default::default()
            // }),
            Default::default(),
            StringInput::from(&*source_file),
            Some(&comments),
        );
        let mut parser = Parser::new_from(lexer);
        match parser.parse_module() {
            Err(err) => Err(err),
            Ok(module) => Ok((module, comments)),
        }
    }
    
    fn emit(module: &Module, comments: &SingleThreadedComments, cm: Lrc<SourceMap>) -> String {
        let mut buf = vec![];
        {
            let writer = Box::new(JsWriter::new(cm.clone(), "\n", &mut buf, None));
            let config = Config {
                minify: false,
                ..Default::default()
            };
            let mut emitter = swc_ecma_codegen::Emitter {
                cfg: config,
                comments: Some(&comments),
                cm,
                wr: writer,
            };
            emitter.emit_module(&module).unwrap();
        }
    
        String::from_utf8(buf).unwrap()
    }
    

    Playground link

    No response

    Expected behavior

    Everything is removed

    Actual behavior

    Output is

    var module;
    

    Version

    0a1e30a4f850949ce2ec5b7e95f53cb1a3d4b771

    Additional context

    https://github.com/parcel-bundler/parcel/issues/7882

    C-bug 
    opened by mischnic 0
  • minify.mangle causes variable confusion

    minify.mangle causes variable confusion

    Describe the bug

    In the case , output code :

    // ....other code
    export const styleLoader = ()=>{
        return {
            name: 'style-loader',
            setup (n) {
                n.onLoad({
                    filter: /.*/,
                    namespace: 'less'
                }, function() {
                    var n = t(function*(n) {});
                    return function(n) {
                        // n is args variable
                        return n.apply(this, arguments); 
                        // when run the code get an error `n.apply is not a function`
                    };
                }());
            }
        };
    };
    

    before mangle output code is :

    // ....other code
    export const styleLoader = ()=>{
        return {
            name: 'style-loader',
            setup (build) {
                build.onLoad({
                    filter: /.*/,
                    namespace: 'less'
                }, function() {
                    var _ref = _asyncToGenerator(function*(args) {});
                    return function(args) {
                        // _ref variable is async 
                        return _ref.apply(this, arguments);
                    };
                }());
            }
        };
    };
    

    Input code

    import { OnResolveArgs, PartialMessage, Plugin, PluginBuild } from 'esbuild';
    import fs from 'fs';
    import path from 'path';
    
    export const styleLoader = (): Plugin => {
      return {
        name: 'style-loader',
        setup(build: PluginBuild) {
          build.onLoad({ filter: /.*/, namespace: 'less' }, async (args) => {
            
          });
        },
      };
    };
    

    Config

    {
      "jsc": {
        "parser": {
          "syntax": "typescript",
          "tsx": false
        },
        "target": "es2015",
        "loose": false,
        "minify": {
          "compress": false,
          "mangle": {
            "toplevel": false,
            "keep_classnames": false,
            "keep_fnames": false,
            "keep_private_props": false,
            "ie8": false,
            "safari10": false
          }
        }
      },
      "module": {
        "type": "es6"
      },
      "minify": false,
      "isModule": true
    }
    

    Playground link

    https://play.swc.rs/?version=1.3.24&code=H4sIAAAAAAAAA01QQW7DIBC8%2BxVzw67c5G4rlZpzq1b9AXHWLhIGi8VVI4u%2FBwhRgpCY3WFmB9S8WOex4cv8EFv9R%2B9u4hbf0nkl9Scxy4lirddJmft5XJU%2BI2B0doYgPqVa9JW6uY1cmJEfzUX639JOMBIV%2FWdmsIY92F80fVh5JocD6qYrs3B4w1YBjvzqTIaAkTN1EFnzqrNItJnheG2pc6DuOW1TlEDmdtakWfWGUWlPrsN%2B97JvszEvckjuOj5eILSQfDEDahl%2FprnHua0CQtNnFFKG0FdxXwGJ3Ag3WQEAAA%3D%3D&config=H4sIAAAAAAAAA22P3QrCMAyF3yXXu9gERfYOPoOEmo5q14YmG47Rd7eT%2FSB4leR8h3DODE8x0M7AmITSsskUFN%2FQgk5MYpJjhQpUimTRC%2BVyYOpIi4XkVDfngn2MQquhgt4FZ6flmYk9JxI5EIbO04I0sqeR%2FI5eRHw3HkUC9iS%2Fuv2jcXIjKpUZ%2BUCOrvsuaDG5pt6i5xK%2Bj49hTVAKfktcIB%2BhtzdyW42aBsofcZ6zHCkBAAA%3D

    Expected behavior

    The mangle results are the same as terser

    Actual behavior

    variable confusion

    Version

    1.3.24

    Additional context

    No response

    C-bug 
    opened by noyobo 0
  • Unknown minify bug, causes infinite run

    Unknown minify bug, causes infinite run

    Describe the bug

    Simple code that makes SWC hang for ever.

    How to reprod ?

    Go to the playground link below, then enable compress, you will find browser blocks

    Input code

    export async function foo() {
      if (undefined_var_1) {
        let replace;
      
        if (undefined_var_2) {
          replace = 1;
        } else {
          replace = 2;
        }
      
        await a({ replace })
      }
    }
    

    Config

    {
      "jsc": {
        "parser": {
          "syntax": "typescript",
          "decorators": true,
          "tsx": false
        },
        "target": "es2020",
        "loose": false,
        "minify": {
          "compress": false,
          "mangle": false
        }
      },
      "module": {
        "type": "es6"
      },
      "minify": true,
      "isModule": true
    }
    

    Playground link

    https://play.swc.rs/?version=1.3.24&code=H4sIAAAAAAAAA22OSwqEMBAF9znFW8albsWzSBM7EAgdiXFUJHf3m9nMbKuKx%2BN1DDGBpk0M7CwmuSCwIegKuwKchZ5lYOuEh%2F5Dsa8fAXhOiDx6Mtye4Ga%2FeVNylBgd6vZGGewn%2FuOb15dZWsidJ%2FX%2BbXKlLp%2FVATGG0ebBAAAA&config=H4sIAAAAAAAAA0WOPQ7DIAxG7%2BKZIcrQgTv0EBZxIioCyHakIsTdC0mqbP5537MrfMSBrZCRhXhUUqLiFyxoySSOfVYwsJBLjJpYwCofZEClQysGodYb5I20h0jmaZ56IKQkdAMGdh%2F9WobepT0ziTwrjFv4k6279rQcY1DPD07nC9rjuM57ed%2Fc6NsPsPYZ%2F8kAAAA%3D

    Expected behavior

    Normally get result.

    Actual behavior

    SWC running without error and don't stop.

    Version

    1.3.24

    Additional context

    No response

    C-bug 
    opened by JSerFeng 1
  • Using externalHelpers causes webpack errors 'import' and 'export' may appear only with 'sourceType: module'

    Using externalHelpers causes webpack errors 'import' and 'export' may appear only with 'sourceType: module'

    Describe the bug

    In my config swc is currently set up to output esm modules in order to let the webpack handle all the stuff with modules. And it mostly works well, but for some packages in node_modules I'm getting the next error:

    error GLOBAL:ERROR Module parse failed: 'import' and 'export' may appear only with 'sourceType: module' (2:0)
    File was processed with these loaders:
     * ../../node_modules/swc-loader/src/index.js
    You may need an additional loader to handle the result of these loaders.
    | "use strict";
    import _type_of from "@swc/helpers/src/_type_of.mjs";
    | exports.__esModule = true;
    | exports.calcFontColor = calcFontColor;
    Error: Module parse failed: 'import' and 'export' may appear only with 'sourceType: module' (2:0)
    File was processed with these loaders:
     * ../../node_modules/swc-loader/src/index.js
    You may need an additional loader to handle the result of these loaders.
    | "use strict";
    import _type_of from "@swc/helpers/src/_type_of.mjs";
    | exports.__esModule = true;
    | exports.calcFontColor = calcFontColor;
        at /workspaces/Tinkoff/tramvai/packages/cli/lib/builder/webpack/utils/runWebpack.js:10:13
        at finalCallback (/workspaces/Tinkoff/tramvai/node_modules/webpack/lib/Compiler.js:441:32)
        at /workspaces/Tinkoff/tramvai/node_modules/webpack/lib/Compiler.js:458:13
        at Hook.eval [as callAsync] (eval at create (/workspaces/Tinkoff/tramvai/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous\>:33:1)
        at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (/workspaces/Tinkoff/tramvai/node_modules/tapable/lib/Hook.js:18:14)
        at onCompiled (/workspaces/Tinkoff/tramvai/node_modules/webpack/lib/Compiler.js:456:21)
        at /workspaces/Tinkoff/tramvai/node_modules/webpack/lib/Compiler.js:1196:17
        at Hook.eval [as callAsync] (eval at create (/workspaces/Tinkoff/tramvai/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous\>:6:1)
        at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (/workspaces/Tinkoff/tramvai/node_modules/tapable/lib/Hook.js:18:14)
        at /workspaces/Tinkoff/tramvai/node_modules/webpack/lib/Compiler.js:1192:33
    

    There is no such issue for babel though.

    I've made some digging to trace the error cause:

    • swc inserts esm imports for helpers anyway - code that later are compiled to commonjs if module is set to commonjs in swc config. And as I'm configured swc to output esm they are not converted to commonjs inside commonjs module
    • the issue surprisingly doesn't affect most of modules. This is because webpack in most cases parses type of file as javascript/auto to provide smart parsing that will dynamically figure out is it esm or commonjs. But some of the packages are explicitly marked with type: "commonjs" in their package.json and it get parsed in webpack more strictly leading to the error above
    • babel outputs the import depending on the package itself so there is no issue when using babel-loader

    Input code

    const fs = require("fs");
    
    exports.test = async () => {};
    

    Config

    {
      "jsc": {
        "parser": {
          "syntax": "typescript",
          "tsx": false
        },
        "externalHelpers": true,
        "target": "es5",
        "loose": false,
        "minify": {
          "compress": false,
          "mangle": false
        }
      },
      "module": {
        "type": "es6"
      },
      "minify": false,
      "isModule": true
    }
    

    Playground link

    https://play.swc.rs/?version=1.3.24&code=H4sIAAAAAAAAA0vOzysuUUgrVrBVKEotLM0sStVQSitW0rTm5eLlSq0oyC8qKdYrSQWqsVVILK7MS1bQ0FSwtVOorrUGALdsYEI7AAAA&config=H4sIAAAAAAAAA0WOSwrDMAxE76K1t%2B3CJ%2BimhxCuElz8Q1IgxvjutYNLdmI0b2YafMWBbVCQhXheUpPiCRa0FhLHvigYUBnShkGoG6BTiROGF4VCLGCVDxoe5J10kCSPgYSchRZkIPrktzoLXI6FSeR%2BYdrD39lHfsyfYwrt2nAFPqHfGYvz8l7G2d9%2Fo%2FC0EMwAAAA%3D

    Expected behavior

    Generate imports for helpers as it is implemented in babel - based on the sourceType of the module itself, not only bare config

    Actual behavior

    Generated imports for helpers are always in esm

    Version

    1.3.24

    Additional context

    The issue might be related

    C-bug 
    opened by meskill 0
  • automatic polyfill for scripts

    automatic polyfill for scripts

    Describe the feature

    https://github.com/swc-project/swc/blob/0a652096aebe2ed12aa3cfb3c611f7e805b8bc0a/crates/swc_ecma_preset_env/src/lib.rs#L457-L459

    I think we can use require to insert them like helpers. https://github.com/swc-project/swc/blob/0a652096aebe2ed12aa3cfb3c611f7e805b8bc0a/crates/swc_ecma_transforms_base/src/helpers/mod.rs#L413-L417 babel use require to import polyfills when it is a script.

    Babel plugin or link to the feature description

    No response

    Additional context

    https://github.com/swc-project/swc/issues/5921

    enhancement 
    opened by RiESAEX 0
Releases(v1.3.24)
Owner
swc
spdy web compiler: Make the web (development) faster.
swc
Modern JavaScript runtime for Sony PSP, based on rust-psp and QuickJS.

PSP.js Modern JavaScript runtime for Sony PSP, based on rust-psp and QuickJS. ⚠️ Currently in PoC state, unusable for developing JavaScript apps yet.

Yifeng Wang 15 Nov 28, 2022
Diamond is a minimalistic, powerful, and modern Javascript runtime that uses Deno_Core.

Diamond Diamond is a minimalistic, powerful, and modern Javascript runtime that uses Deno_Core. Installation Diamond is currently in beta(not even Alp

Catermelon 4 Aug 30, 2021
This tool converts Lua code to TS automatically, including the conversion of common standards to their TS equivalents.

lua-to-ts This tool converts Lua code to TS automatically, including the conversion of common standards to their TS equivalents. Code that fails to be

Dion 11 Nov 21, 2022
C-like language compiler, the final project of ZJU Compiler Principle course

cc99 cc99 (not cc98.org) is a C-like language compiler, which is the final project of ZJU Compiler Principle course. It supports many of the C99 langu

Ralph 37 Oct 18, 2022
Node.js bindings to the ripgrep library, for fast file searching in JavaScript without child processes!

ripgrepjs ripgrepjs: Node.js bindings to the ripgrep library, for direct integration with JS programs without spawning an extra subprocess! This proje

Annika 1 May 10, 2022
Parametric surfaces drawn using the Rust + WASM toolchain with WebGL, React, and TypeScript.

Parametric Surfaces in the Browser My.Movie.3.mp4 Wanted to experiment with WebGL using the Rust + WASM toolchain, with React and TypeScript to glue e

Benji Nguyen 45 Oct 21, 2022
🚀 A fast, modern & efficient interpreted language.

Lace is an efficient, modern and predictable procedural programming language written in rust. Easy to write: Lace's syntax is easy to learn and write,

null 11 Oct 2, 2022
📝 A template for creating WASM + Typescript + Rust workflow libraries.

Create Rust + TypeScript libraries with ease! PR'S WELCOMED! ✨ Inspiration I wanted to create a WebAssembly/Rust library with additional JS features,

Shaoru Ian Huang 25 Dec 24, 2022
A super-lightweight Lua microservice (toy) framework.

Hive A super-lightweight microservice (toy) framework written in Rust. It uses Lua as interface to provide simple, fun developing experience and fast

Eric Long 39 Aug 14, 2022
A parser, compiler, and virtual machine evaluator for a minimal subset of Lua; written from scratch in Rust.

lust: Lua in Rust This project implements a parser, compiler, and virtual machine evaluator for a minimal subset of Lua. It is written from scratch in

Phil Eaton 146 Dec 16, 2022
A JavaScript Runtime built with Mozilla's SpiderMonkey Engine and Rust

Spiderfire Spiderfire is a javascript runtime built with Mozilla's SpiderMonkey engine and Rust. Spiderfire aims to disrupt the server-side javascript

Redfire 122 Dec 15, 2022
A simple programming language made for scripting inspired on rust and javascript.

FnXY Programming Language Quick move: CONTRIBUTING | LICENSE What? FnXY is a simple programming language made for scripting inspired on rust and javas

null 2 Nov 27, 2021
Facilitating high-level interactions between Wasm modules and JavaScript

wasm-bindgen Facilitating high-level interactions between Wasm modules and JavaScript. Guide | API Docs | Contributing | Chat Built with ?? ?? by The

Rust and WebAssembly 5.9k Jan 8, 2023
The JavaScript runtime that aims for productivity and ease

Byte Byte is a easy and productive runtime for Javascript . It makes making complex programs simple and easy-to-scale with its large and fast Rust API

Byte 32 Jun 16, 2021
A programming environment that aims to help people learn how to program in JavaScript, while giving them a tour on how old computers and their limitations used to be.

This repository is for the new under renovation rewrite of the LIKO-12 project. The legacy version with the original stars and contributions is still

null 1k Jan 5, 2023
My 'Lugli' language compiler for learning purposes, written in rust. 🥰🤠

Lugli language compiler My 'Lugli' language compiler for learning purposes, written in rust. This language is to be a subset for other purposes, for e

Vinicios Lugli 3 Nov 2, 2022
Guarding 是一个用于 Java、JavaScript、Rust、Golang 等语言的架构守护工具。借助于易于理解的 DSL,来编写守护规则。Guarding is a guardians for code, architecture, layered.

Guarding Guarding is a guardians for code, architecture, layered. Using git hooks and DSL for design guard rules. Usage install cargo install guarding

Inherd OS Team (硬核开源小组) 47 Dec 5, 2022
Rust bindings for Supabase JavaScript library via WebAssembly.

supabase-js-rs Rust bindings for Supabase JavaScript library via WebAssembly. Usage Add supabase-js-rs to Cargo.toml supabase-js-rs = { version = "0.1

Valery Stepanov 8 Jan 13, 2023
Javascript wrapper bindings for diamond types

Diamond JS wrapper library This is a javascript / WASM wrapper around diamond types. This code is currently experimental WIP. Do not trust this for an

Seph Gentle 14 Jun 16, 2022