Giter Site home page Giter Site logo

register's Introduction

@swc/register

One of the ways you can use swc is through the require hook. The require hook will bind itself to node's require and automatically compile files on the fly.

Install

npm i -D @swc/core @swc/register

or

yarn add --dev @swc/core @swc/register

Usage

require("@swc/register");

All subsequent files required by node will be transformed by swc. You can also call @swc/register directly from command line.

swc-node <filename>
node -r '@swc/register' <filename>

 


@swc/register is primarily distributed under the terms of both the MIT license and the Apache License (Version 2.0). See COPYRIGHT for details.

register's People

Contributors

ide avatar kdy1 avatar selfagency avatar simnalamburt avatar sukkaw avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

register's Issues

export { default as name } from 'dependency'; not transpiled

I have a dependency of my project that depends on lodash-es, and when using @swc/register I get:

export { default as add } from './add.js';
^^^^^^

 SyntaxError: Unexpected token 'export'
     at internalCompileFunction (node:internal/vm:73:18)
     at wrapSafe (node:internal/modules/cjs/loader:1176:20)
     at Module._compile (node:internal/modules/cjs/loader:1218:27)
     at Module._extensions..js (node:internal/modules/cjs/loader:1308:10)
     at Object.newLoader [as .js] (/pro-app/node_modules/pirates/lib/index.js:141:7)
     at Module.load (node:internal/modules/cjs/loader:1117:32)
     at Function.Module._load (node:internal/modules/cjs/loader:958:12)
     at Module.require (node:internal/modules/cjs/loader:1141:19)
     at require (node:internal/modules/cjs/helpers:110:18)

My app is JS using commonjs, the component is a TS compiled with vite. Any clue why this could be happening?

Plugin fails with "Incompatible Export Type"

I followed the instructions for creating a new plugin - https://swc.rs/docs/plugin/ecmascript/getting-started.

  1. Ran swc plugin new
swc plugin new --target-type wasm32-wasi my-first-plugin
  1. Built the .wasm bundle.
cargo build --release --target wasm32-wasi && && cp target/wasm32-wasi/release/my_first_plugin.wasm .
  1. Checked the package.json correctly points as the .wasm binary.
"main": "my_first_plugin.wasm",
  1. Installed the my-first-plugin package in another NPM package using file: references.
"my-first-plugin": "file:../plugin/my-first-plugin"
  1. Configured .swcrc to use my-first-plugin
{
  "jsc": {
    "experimental": {
      "plugins": [["my-first-plugin", {}]]
    }
  }
}
  1. Ran node.
node -r @swc/register t.js

I get the following error

thread '<unnamed>' panicked at 'failed to invoke plugin: failed to invoke plugin on 'Some("/Users/samgoodwin/workspaces/nodejs-closure-serializer/t.js")'

Caused by:
    Incompatible Export Type', crates/swc/src/plugin.rs:273:14
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
/Users/samgoodwin/workspaces/nodejs-closure-serializer/node_modules/@swc/core/index.js:137
        return bindings.transformSync(isModule ? JSON.stringify(src) : src, isModule, toBuffer(newOptions));
                        ^

Error: failed to handle: failed to invoke plugin: failed to invoke plugin on 'Some("/Users/samgoodwin/workspaces/nodejs-closure-serializer/t.js")'

Caused by:
    Incompatible Export Type
    at Compiler.transformSync (/Users/samgoodwin/workspaces/nodejs-closure-serializer/node_modules/@swc/core/index.js:137:25)
    at Object.transformSync (/Users/samgoodwin/workspaces/nodejs-closure-serializer/node_modules/@swc/core/index.js:217:21)
    at compile (/Users/samgoodwin/workspaces/nodejs-closure-serializer/node_modules/@swc/register/lib/node.js:76:22)
    at compileHook (/Users/samgoodwin/workspaces/nodejs-closure-serializer/node_modules/@swc/register/lib/node.js:91:16)
    at Module._compile (/Users/samgoodwin/workspaces/nodejs-closure-serializer/node_modules/pirates/lib/index.js:130:29)
    at Module._extensions..js (node:internal/modules/cjs/loader:1157:10)
    at Object.newLoader [as .js] (/Users/samgoodwin/workspaces/nodejs-closure-serializer/node_modules/pirates/lib/index.js:141:7)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12) {
  code: 'GenericFailure'
}

Same problem with @swc/cli

npx swc ./t.js -o u.js
thread '<unnamed>' panicked at 'failed to invoke plugin: failed to invoke plugin on 'Some("t.js")'

Caused by:
    Incompatible Export Type', crates/swc/src/plugin.rs:273:14
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
failed to handle: failed to invoke plugin: failed to invoke plugin on 'Some("t.js")'

Caused by:
    Incompatible Export Type
Error: Failed to compile 1 file with swc.
    at Object.assertCompilationResult (/Users/samgoodwin/workspaces/nodejs-closure-serializer/node_modules/@swc/cli/lib/swc/util.js:113:15)
    at files (/Users/samgoodwin/workspaces/nodejs-closure-serializer/node_modules/@swc/cli/lib/swc/file.js:173:18)
    at async _default (/Users/samgoodwin/workspaces/nodejs-closure-serializer/node_modules/@swc/cli/lib/swc/file.js:192:9)

Using `node -r @swc/register` and `require("@swc/register")` no longer work

Hi! Looking into some test failures after upgrading and it seems that swc/register no longer performs the registration automatically but relies on a function to be called.

This is due to the removal of the register() call in #14. This broke swc-node but it was fixed in 0.1.9. Was the removal intentional? And is node -r @swc/register no longer supported in lieu of having to use swc-node?

I created a reproduction here which showcases the behavior change from 0.1.7 to 0.1.9:
https://github.com/thecrypticace/swc-register-issue

0.1.8 not working very well with yarn workspaces

After upgrading from 0.1.7 to 0.1.8 tests in our project stopped working. On further inspection I noticed that this was due to change in how ignoring node_modules is implemented.

For context - I ran tests for a workspace which is in a subdirectory, but that depends on test utils on parent directory. By default only includes just the contents of workspace subdirectory. I changed that and then hit a problem of ignore not ignoring the parent node_modules since it's set to a strict subdirectory_path.../node_modules.

I'm wondering if at the very least default ignore should be changed to a more relaxed regexp ("^node_modules")

swc-node doesn't work if child_process.fork is used in .ts

Hello!
When I try to run my typescript file which contains child_process.fork using swc-node I get the following error:

//main.ts
child_process.fork(__dirname + '/testsRunner/testsRunner.js', args, {cwd: process.cwd()})

internal/modules/cjs/loader.js:1023
  throw err;
  ^

Error: Cannot find module 'C:\src\testsRunner\testsRunner.js'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:1020:15)
    at Function.Module._load (internal/modules/cjs/loader.js:890:27)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
    at internal/main/run_main_module.js:17:47 {
  code: 'MODULE_NOT_FOUND',
  requireStack: []
}

It is because .js file doesn't really exist it supposed to be compiled on the fly. There is only testsRunner.ts file.
Is there a way to get it working?

Should this work with `type: module` packages?

When I try to import a .ts file from an ESM entry-point I get this error:

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /xxx/src/cli.ts
    at new NodeError (node:internal/errors:371:5)
    at Loader.defaultGetFormat [as _getFormat] (node:internal/modules/esm/get_format:71:15)
    at Loader.getFormat (node:internal/modules/esm/loader:105:42)
    at Loader.getModuleJob (node:internal/modules/esm/loader:243:31)
    at async Loader.import (node:internal/modules/esm/loader:177:17)
    at async file:///xxx/index.js:5:15 {
  code: 'ERR_UNKNOWN_FILE_EXTENSION'
}

I think the underlying pirates hook only works with commonjs entry-points.

Right now ESM loader hooks are experimental and expected to change. See: nodejs/modules#351). Problem is you have to then run the entry-point using cross-env 'NODE_OPTIONS=--experimental-loader some-swc-hook' which is annoying.

Here is an example of a transpiler hook: https://nodejs.org/api/esm.html#esm_transpiler_loader

Here is how instanbuljs is doing it: https://github.com/istanbuljs/esm-loader-hook/blob/master/index.js

Deprecate this project

I spent a long time debugging why something was broken in @swc/register, only to realize that @swc-node/register seems to be the currently maintained package to use.

This repo should be ideally archived and the package on npm should be marked as deprecated if this is the case

bug: When package.json "type" to "commonjs", .mts file should be "esmodule"

main.mts

import { hello } from "./hello.mjs";

console.log(hello());

hello.mts

export function hello() {
  return "hello";
}
> swc-node main.mts

(node:16280) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
import{hello}from"./hello.mjs";console.log(hello()); 
^^^^^^

SyntaxError: Cannot use import statement outside a module

Cannot import JSON

I've spent a bunch of time on this issue and think it may be a bug. I've created a minimum reproduction here, and have pasted the relevant code and output below. I'm trying to load JSON directly using SWC from an import statement in a script that is invoked via a hashbang operator. The script is:

#!/usr/bin/env -S node --loader @swc-node/register/esm
import p from './package.json' assert { type: 'json' }

console.log(p)

My .swcrc is

{
  "$schema": "https://json.schemastore.org/swcrc",
  "jsc": {
    "experimental": {
      "keepImportAssertions": true
    }
  }
}

When I run the script, I recieve the following output:

➜  minimum-example ./script.ts 
(node:2856) ExperimentalWarning: Custom ESM Loaders is an experimental feature and might change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
node:internal/errors:490
    ErrorCaptureStackTrace(err);
    ^

TypeError [ERR_IMPORT_ASSERTION_TYPE_MISSING]: Module "file:///Users/a2f0/github-thinkspan/minimum-example/package.json" needs an import assertion of type "json"
    at new NodeError (node:internal/errors:399:5)
    at validateAssertions (node:internal/modules/esm/assert:82:15)
    at defaultLoad (node:internal/modules/esm/load:84:3)
    at nextLoad (node:internal/modules/esm/loader:163:28)
    at load (file:///Users/a2f0/github-thinkspan/minimum-example/node_modules/@swc-node/register/esm/esm.mjs:57:16)
    at nextLoad (node:internal/modules/esm/loader:163:28)
    at ESMLoader.load (node:internal/modules/esm/loader:605:26)
    at ESMLoader.moduleProvider (node:internal/modules/esm/loader:457:22)
    at new ModuleJob (node:internal/modules/esm/module_job:64:26)
    at #createModuleJob (node:internal/modules/esm/loader:480:17) {
  code: 'ERR_IMPORT_ASSERTION_TYPE_MISSING'
}

Node.js v18.15.0
➜  minimum-example 

I've tried this with various tsconfig and package.json options (i.e. `"type": "module", or the absence thereof). I feel like it should be easy to get this working, that there's either something I don't understand about SWC's basic configuration, or some sort of bug in SWC.

Unknown file extension ".ts"

Trying to run node -r @swc/register test.ts throws the following:

❯ node -r @swc/register test.ts
internal/process/esm_loader.js:74
    internalBinding('errors').triggerUncaughtException(
                              ^
                              
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for test.ts
    at Loader.defaultGetFormat [as _getFormat] (internal/modules/esm/get_format.js:71:15)
    at Loader.getFormat (internal/modules/esm/loader.js:104:42)
    at Loader.getModuleJob (internal/modules/esm/loader.js:242:31)
    at async Loader.import (internal/modules/esm/loader.js:176:17)
    at async Object.loadESM (internal/process/esm_loader.js:68:5) {
  code: 'ERR_UNKNOWN_FILE_EXTENSION'
}

Context

  • node, npm: v14.17, v8
  • package.json:
...
  "type": "module",
...
    "@swc/cli": "^0.1.51",
    "@swc/core": "^1.2.111",
    "@swc/register": "^0.1.7",
  • .swcrc
{
  "minify": false,
  "sourceMaps": true,
  "env": {
    "target": "node",
    "mode": "entry",
    "coreJs": 3
  },
  "module": {
    "type": "es6"
  },
  "jsc": {
    "parser": {
      "syntax": "typescript",
      "tsx": false,
      "decorators": false,
      "dynamicImport": false
    }
  }
}

Cannot find TypeScript module with .js specifier in a TypeScript file

I'm not sure if this should be supported but it'd great to be able to import a TypeScript file with .js specifier in a TypeScript file, like so:

// module-a.ts
export const a = 100;

// main.ts
// import { a } from './module-a'; // it works without .js specifier
import { a } from './module-a.js'

console.debug(a); // 100

Source maps not working?

I've been digging into details while preparing reproduction for the following IntelliJ issue: https://youtrack.jetbrains.com/issue/WEB-52287/Debugging-doesnt-work-correctly-with-swc-transpiler-https-github.com-swc-project-swc

It looks like the source maps are not outputted, or incorrect in some way? See the attached issue, and the reproduction repository: https://github.com/wodCZ/swc-register-inspect-repro

Unfortunately, I wasn't able to find a workaround on how to reliably attach debugger to a process running through @swc/register.

Sourcemaps are fine when building the project with the same configuration and debugging the compiled js file. However, that's a large inconvenience for an interactive debugging of large node projects.

// EDIT: I've just tried with https://github.com/swc-project/swc-node and it's working correctly. Should that @swc-node/register be used instead of @swc/register?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.