Coder Social home page Coder Social logo

cli's Introduction

cli's People

Contributors

3axap4ehko avatar aeons avatar brodo avatar ccouzens avatar chyzwar avatar clhuang avatar dangreen avatar davecardwell avatar doubleinc avatar dsvgit avatar gamote avatar heygrady avatar jakechampion avatar johndaly avatar kdy1 avatar keesvv avatar kherock avatar klaitos avatar kwonoj avatar niyarlatotep avatar royalicing avatar shogunpanda avatar swagadon avatar tmpfs avatar unoqwy avatar walkerburgin avatar xnuk 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

cli's Issues

No output when compiling a directory

For a project

<ProjectRoot>
+-- src
    +-- index.ts

and

@swc/cli: 0.1.42
@swc/core: 1.2.58

Nothing generated when compiling a directory

The command

npx swc src -d dist

only creates an empty directory <ProjectRoot>/dist without dist/index.ts.

  • same behavior with/without .swcrc
  • It seems that await util.globSources(cliOptions.filenames, cliOptions.includeDotfiles) returns an empty object: {}

Output generated as expected when compiling a single file

npx swc src\index.ts -d dist

generates the dist/index.ts

sourceMappingURL wrong path

Given this line of code below:

code += "\n//# sourceMappingURL=" + slash(path.relative(filename, mapLoc));

const path = require('path');

console.log(path.relative('dist/helpers/a.js', 'dist/helpers/a.js.map'));

It will output:

"../a.js.map"

Which points to wrong sourcemap file.

Source Maps support

Now no source-maps option works:

$ swc -s test/bundle/a.js
swc:
  stdin compilation requires either -f/--filename [filename] or --no-swcrc

Why that error? Ok, use true:

$ swc -s true test/bundle/a.js
'use strict';
Object.defineProperty(exports, '__esModule', {
    value: true
});
exports.default = void 0;
var _default = 'a is for apple';
exports.default = _default;
xxx;

Where are the sourcemaps? Ok, try to define file:

$ swc -s true --source-file-name x.map test/bundle/a.js
'use strict';
Object.defineProperty(exports, '__esModule', {
    value: true
});
exports.default = void 0;
var _default = 'a is for apple';
exports.default = _default;
xxx;

No x.map is ever created.

Excluded files throw errors when compiling

Here's my configuration .swcrc:

 [ 
  {
    "test": ".*.js$",
    "exclude": [
        "__tests__"
    ],
    "module": {
      "type": "commonjs"
    },
    "jsc": {
      "parser": {
        "syntax": "ecmascript",
        "jsx": true
      },
      "transform": {
          "react": {
              "runtime": "automatic"
          }
      },
      "loose": true
    }
  },
  {
    "test": ".*.ts$",
    "exclude": [
        "__tests__"
    ],
    "module": {
      "type": "commonjs"
    },
    "jsc": {
      "parser": {
        "syntax": "typescript",
        "tsx": true
      },
      "transform": {
          "react": {
              "runtime": "automatic"
          }
      },
      "loose": true
    }
  }
]

The strategy is pretty simple: For .js files, use ecmascript syntax and compile to commonjs module. For .ts files, use typescript syntax and also compile to commonjs module format. In both cases, just ignore __tests__.

When I run:

npx swc src -d lib -s --sync

It tries to compile .test.js files, but complain that there's no matching configuration for them:

failed to process js file

Caused by:
    0: failed to load config for file 'Real("src/__tests__/AfwClient.test.js")'
    1: failed to read swcrc file (src/__tests__/AfwClient.test.js)
    2: failed to process config file
    3: .swcrc exists but not matched

Do I need to match .test.js files in another entry and figure out how to noop them? Using --exclude doesn't seem to help, either. The docs are not very thorough about how configuration all works together. Especially with multiple entries.

npx swc --version

@swc/cli: 0.1.51
@swc/core: 1.2.103

Support JSONSchema property

It would be super nice to support the $schema property inside .swcrc file.

{
		"$schema": "http://json.schemastore.org/swcrc",
		...
}

The schema url already works fine, but when I try to run the cli I get

    1: failed to deserialize .swcrc (json) file: unmatched data: 2:10
	2: unknown field `$schema`, expected one of ... 

immagine

Outdated dependencies causes 'vulnerabilities found' warnings

This project depends on the bin-wrapper package. Unfortunately this package hasn't had any new versions for 4 years.

Bin-wrapper eventually relies on outdated versions of packages (got and semver-regex), causing npm to complain about vulnerable packages.

3 vulnerabilities found
Severity: 1 low | 1 moderate | 1 high

Is there a way to stop relying on bin-wrapper? The package only seems +- 200 lines long anyway :)

Unable to disable source maps

Reproduction using @swc/[email protected].

scripts/.swcrc contents:

{
  "jsc": {
    "parser": {
      "syntax": "typescript"
    },
    "target": "es2021"
  }
}

Steps:

  1. node_modules/.bin/swc promiseSettledAggregate.ts -o dist/promiseSettledAggregate.js --config-file scripts/.swcrc
  2. See added promiseSettledAggregate.js.map in dist
  3. Delete dist/promiseSettledAggregate.js.map
  4. Run npm install @swc/[email protected] and re-run first step, and see now there is no longer promiseSettledAggregate.js.map

Expected behaviour:

Only emit promiseSettledAggregate.js.map if sourceMaps is enabled in config file. Do not emit if sourceMaps is omitted or set to false.

`spack` - Panic on arrays with 64 or more numbers

When an input file for spack contains a declaration of an array with 64 or more numbers, spack panics:

thread '<unnamed>' panicked at 'cannot access a scoped thread local variable without calling `set` first', C:\Users\runneradmin\.cargo\registry\src\github.com-1ecc6299db9ec823\scoped-tls-1.0.0\src\lib.rs:168:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace                                                                                                                                    
node:internal/process/promises:288                                                                                                                                                                               
            triggerUncaughtException(err, true /* fromPromise */);                                                                                                                                               
            ^                                                                                                                                                                                                    

[Error: panic detected] { code: 'GenericFailure' }

Node.js v18.0.0
With RUST_BACKTRACE=full
thread '<unnamed>' panicked at 'cannot access a scoped thread local variable without calling `set` first', C:\Users\runneradmin\.cargo\registry\src\github.com-1ecc6299db9ec823\scoped-tls-1.0.0\src\lib.rs:168:9
stack backtrace:
   0:     0x7ffb16013f5f - wasmer_vm_raise_trap
   1:     0x7ffb16030eba - wasmer_vm_raise_trap
   2:     0x7ffb1600db49 - wasmer_vm_raise_trap
   3:     0x7ffb160169cb - wasmer_vm_raise_trap
   4:     0x7ffb1601664b - wasmer_vm_raise_trap
   5:     0x7ffb16016f79 - wasmer_vm_raise_trap
   6:     0x7ffb16e5535a - wasmer_vm_raise_trap
   7:     0x7ffb16e55327 - wasmer_vm_raise_trap
   8:     0x7ffb1771a6fd - wasmer_vm_raise_trap
   9:     0x7ffb16e13443 - wasmer_vm_raise_trap
  10:     0x7ffb16df0bdc - wasmer_vm_raise_trap
  11:     0x7ffb15f482f1 - wasmer_vm_raise_trap
  12:     0x7ffb15f4b42f - wasmer_vm_raise_trap
  13:     0x7ffb16def03c - wasmer_vm_raise_trap
  14:     0x7ffb15f47df4 - wasmer_vm_raise_trap
  15:     0x7ffb15f4a9d1 - wasmer_vm_raise_trap
  16:     0x7ffb15f4a922 - wasmer_vm_raise_trap
  17:     0x7ffb15f48f76 - wasmer_vm_raise_trap
  18:     0x7ffb15c86836 - Ordinal0
  19:     0x7ffb15c7d3c3 - Ordinal0
  20:     0x7ffb15b4634a - Ordinal0
  21:     0x7ffb15b9aa39 - Ordinal0
  22:     0x7ffb15b59396 - Ordinal0
  23:     0x7ffb15bda5ab - Ordinal0
  24:     0x7ffb15b13479 - Ordinal0
  25:     0x7ff70e1ebc3e - uv_queue_work
  26:     0x7ff70e1d7d4d - uv_poll_stop
  27:     0x7ff70f182060 - v8::internal::compiler::ToString
  28:     0x7ffb89e47034 - BaseThreadInitThunk
  29:     0x7ffb8a5e26a1 - RtlUserThreadStart
node:internal/process/promises:288
            triggerUncaughtException(err, true /* fromPromise */);
            ^

[Error: panic detected] { code: 'GenericFailure' }

Node.js v18.0.0

Input:

// foo.js
const foo = [
    1, 1, 1, 1,
    1, 1, 1, 1,
    1, 1, 1, 1,
    1, 1, 1, 1,
    1, 1, 1, 1,
    1, 1, 1, 1,
    1, 1, 1, 1,
    1, 1, 1, 1,
    1, 1, 1, 1,
    1, 1, 1, 1,
    1, 1, 1, 1,
    1, 1, 1, 1,
    1, 1, 1, 1,
    1, 1, 1, 1,
    1, 1, 1, 1,
    1, 1, 1, 1,
];

spack.config.js

const { config } = require("@swc/core/spack");

module.exports = config({
    entry: 'foo.js',
    output: {
        path: __dirname,
        name: 'bar.js',
    },
    module: {},
});
  • @swc/core: 1.3.1
  • @swc/cli: 0.1.57

This might be related to #157 but the error is very generic and this might be a different cause, so I opened this issue.

spack size limitations

I tried to integrate spack in one of my projects with over 200k lines of JS and tried to bundle some modules with it.

In a conclusion, some module bundles worked very great (around 10 modules for 0.3 ms), while most failed ... badly.

From what I can deduct it has to do with the size of the files it requires to bundle - for example if I need to import 400 files in my index it can handle 20-ish... the rest it can't process. After a few hours of trial and error, I noticed it didn't have anything to do with the content, or encoding of the file, but with the size of the file. So excluding a bigger one can make place for others...

I do not know if this behavior is configurable, or if any other one has the same behavior.

I tried to compare it with esbuild which finishes everything in 6s, but unfortunately, I couldn't.

Is spack the official way to go? or did it change meanwhile to swcpack?
image

Nested src dir shows up in out dir

Using a nested src dir outputs the path in the out dir. Seams like changing --source-root does not solve the issue.

swc src/deep/nested/ --out-dir out/

Current output

project/
  src/deep/nested/
    main.ts
  out/deep/nested/
    main.js
    main.js.map

Expected output

project/
  src/deep/nested/
    main.ts
  out/
    main.js
    main.js.map

Version

"@swc/cli": "^0.1.55",
"@swc/core": "^1.2.128"

Chokidar watch options

Hi,

Is there a way to pass custom ignore switch to chokidar?

In my case, source and destination directory is same. Ex: swc ./src -d ./src -w --only **/*.ts

With this, .js files get generated in ./src/. But this is causing loop as chokidar detected file change in the src dir.

I see chokidar.watch() is only supporting dot files as of now. Can you please confirm if swc-cli support any custom ignore pattern for chokidar?

Thanks

no way to suppress console log of copied files

When run with --copy-files, the filenames of non-compilable files are output to the console. I'm not sure if this was even intended behavior, due to the way it was introduced in #32.

But even when run with -q, the output persists, which definitely seems like a bug.

swc_ecma_lints E0554 `#![feature]` may not be used on the stable release channel

I'm just installing the swc_cli for the first time and getting this error:

error[E0554]: `#![feature]` may not be used on the stable release channel
 --> /.cargo/registry/src/github.com-1ecc6299db9ec823/swc_ecma_lints-0.81.20/src/lib.rs:3:1
  |
3 | #![feature(box_patterns)]
  | ^^^^^^^^^^^^^^^^^^^^^^^^^

For more information about this error, try `rustc --explain E0554`.
error: could not compile `swc_ecma_lints` due to previous error
warning: build failed, waiting for other jobs to finish...
error: failed to compile `swc_cli v0.91.40`, intermediate artifacts can be found at `/var/folders/wx/q60_3qcd38jcs82nqbz7_7s80000gn/T/cargo-installM0Y7lb`

Currently not working on arm64, but easy to workaround/fix

https://www.npmjs.com/package/bin-wrapper uses an outdated library called https://www.npmjs.com/package/os-filter-obj which doesn't support non-Intel arch: kevva/os-filter-obj#3

This makes swcx currently not work via this wrapper.

.src(`${releaseBase}/${binaryName}`, platform, arch)

Removing platform and arch here, makes it work fine and should also cause no problems since with the getBinaryName() function we already download the correct platform and arch from the releases page.

arm64: "swc-darwin-arm64",

const binaryName = platformBinaryMap[platform][arch];

[Feature request]copy over `non-compilable` files

Feature request

Copy over non-compilable files

Currently, swc-project/cli use -D option to copy over non-compilable files.
Finally it only according extensions option to filter files.
code

Why

In some cli project, exist template dir(such as react template), which will be copied to another location.

How to implement

In my opinion, swc-project/cli can uses the exclude filed in .swcrc to filter files.
I think the excluded files are non-compilable files.

Feature Request: Provide CLI options via file

Hi!
I often find myself in the need to specify same CLI (note, not the SWC options, the CLI one like --out-dir) options with slight variations (for instance, in production I don't build source-maps).

It would be great if all the options could be specified in a file similar to .swcrc. Ideally the file should be a different one but use the same syntax. As a side idea, we could even use the same .swcrc and open a new section there (like cli).

Is this possible and/or in the roadmap? Would you accept a PR for it?

Not printing error detail when running `swc`

When running swc src -d lib -s when there is an error I get this unhelpful message:

Failed to compile 4 files with swc.
Error: Failed to compile
    at initialCompilation (/Users/Vaughan/dev/fork/+swc/cli/lib/swc/dir.js:159:19)
    at async dir (/Users/Vaughan/dev/fork/+swc/cli/lib/swc/dir.js:219:5)

Here is the place that prints errors:

cli/src/swc/dir.ts

Lines 132 to 174 in c68ace2

if (sync) {
for (const filename of compilable) {
try {
const result = await handleCompile(filename, outDir, sync, swcOptions);
results.set(filename, result);
} catch (err) {
console.error(err.message);
results.set(filename, CompileStatus.Failed);
}
}
for (const filename of copyable) {
try {
const result = await handleCopy(filename, outDir);
results.set(filename, result);
} catch (err) {
console.error(err.message);
results.set(filename, CompileStatus.Failed);
}
}
} else {
await Promise.all([
Promise.allSettled(compilable.map(file => handleCompile(file, outDir, sync, swcOptions))),
Promise.allSettled(copyable.map(file => handleCopy(file, outDir)))
]).then(([compiled, copied]) => {
compiled.forEach((result, index) => {
const filename = compilable[index];
if (result.status === "fulfilled") {
results.set(filename, result.value);
} else {
results.set(filename, CompileStatus.Failed);
}
});
copied.forEach((result, index) => {
const filename = copyable[index];
if (result.status === "fulfilled") {
results.set(filename, result.value);
} else {
results.set(filename, CompileStatus.Failed);
}
});
});
}

In the sync runner there are console.logs, but not in the async runner. If I add a console.log(result) it prints:

{
  status: 'rejected',
  reason: [Error: failed to process js file

  Caused by:
      0: failed to load config for file 'Real("src/foo/index.ts")'
      1: failed to read swcrc file (src/foo/index.ts)
      2: failed to deserialize .swcrc (json) file: syntax error: 17:3
      3: key must be a string at line 17 column 3] {
    code: 'GenericFailure'
  }
}

This error should be printed.

This error was caused by bad syntax in .swcrc:

{
  "jsc": {
    "target": "es2020",
    "parser": {
      "syntax": "typescript",
      "tsx": true,
      "decorators": true,
      "dynamicImport": true
    },
    "baseUrl": "src",
    "paths": {
      "@src/*": [
        "*"
      ]
    }
  },
  module: {
    type: 'commonjs',
  }
}

--config doesn't handle anything with commas

I'm attempting to configure swc to use a custom plugin via the command line as part of a larger build process. Essentially I'm trying to replicate this .swcrc:

{
    "jsc": {
        "experimental": {
            "plugins": [
                ["./my_plugin.wasm", {}]
            ]
        }
    }
}

Calling swc --out-dir=dist --config=jsc.experimental.plugins=[[\"my_plugin.wasm\", {}]] src/ fails with an error like this:

invalid type: string "[[\"my_plugin.wasm\"", expected a sequence at line 1 column 187
Failed to compile 1 file with swc.
Error: Failed to compile:
test/index.ts
    at initialCompilation (/Users/wburgin/.nvm/versions/node/v12.20.2/pnpm-global/4/node_modules/.pnpm/@swc/[email protected]_@[email protected]/node_modules/@swc/cli/lib/swc/dir.js:172:19)
    at async dir (/Users/wburgin/.nvm/versions/node/v12.20.2/pnpm-global/4/node_modules/.pnpm/@swc/[email protected]_@[email protected]/node_modules/@swc/cli/lib/swc/dir.js:16:5)

I poked around a little bit, and here's what swcOptions ends up set to:

{
  jsc: {
    parser: undefined,
    transform: {},
    experimental: { plugins: '[["my_plugin.wasm"' }
  },
  sourceFileName: undefined,
  sourceRoot: undefined,
  configFile: undefined,
  swcrc: true,
  '': true
}

I think the collect() function (here) splitting the input on commas is causing the truncation.

Source Map Format invalid

The source maps are emitted in a wrong format:

Example Output

{
  "version": 3,
  "sources": [
    "// import { add } from './add';\r\n// export {add} from './add'\r\n\r\nconsole.log(\"start\")\r\nexport function add(num1: number, num2: number){\r\n    return num1 + num2;\r\n}\r\nconst res = add(3, 4);\r\n\r\nconsole.log(res)\r\n"
  ],
  "names": [],
  "mappings": ";;;;Q,G,G,G;A,E,6B;A,E,0B;A,O,C,G,E,K;S,G,C,I,E,I;W,I,G,I;;I,G,G,G,C,C,E,C;A,O,C,G,C,G",
  "file": "index.js"
}

According to https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit

"sources": ["foo.js", "bar.js"],
"sourcesContent": [null, null],

"sources" should not contain the content, but path to the original files

bin-wrapper uses bin-check (6 years old now) which uses execa 0.x that has security issues

Recently the bin-wrapper dependency was added, which then was modified to use the @mole-inc fork since that one is maintained.

This still uses bin-check which depends on execa 0.7 which has a vulnerability (OS Command Injection in execa)

https://www.npmjs.com/package/bin-check
https://www.npmjs.com/package/execa

I've opened a ticket with mole-inc to see if they can fork bin-check as well and remove that old dependency mole-inc/bin-wrapper#10

Watch mode writes to output twice when using relative paths

Describe the bug

When I run the command npx swc ./src/index.js -o ./dist/output.js --watch the output.js file contains the output as expected on the first compilation.

When I alter index.js and then save, the watch mode triggers a re-compile. This time, the file contains the output from the first compile, and the output from the altered file.

If I remove the relative paths and instead do this: npx swc src/index.js -o dist/output.js --watch the output contains only the current altered file's compilation as expected.

Note: I used directories here but the behaviour is the same if you are just compiling and outputting at the root level i.e. npx swc ./index.js -o ./output.js --watch

Expected Behaviour

--watch mode does not include any previous compilations and only includes compiled output from the current file save even when using relative paths in command.

index.js:

console.log('Speedy Web Compiler');

output.js:

console.log('Speedy Web Compiler');

Updated index.js and Save:

console.log('Speedy Web Compiler is speedy');

Updated output.js:

console.log('Speedy Web Compiler is speedy');

Actual Behaviour

--watch mode includes first compiled output in output.js when relative paths are used in the command.

index.js:

console.log('Speedy Web Compiler');

output.js:

console.log('Speedy Web Compiler');

Updated index.js and Save:

console.log('Speedy Web Compiler is speedy');

Updated output.js:

console.log('Speedy Web Compiler');

console.log('Speedy Web Compiler is speedy');

This is confusing because the documentation uses relative paths in the usage section so I would expect that they would work everywhere.

see: https://swc.rs/docs/usage/cli#usage

May be related to #99 but I thought the extra detail may be helpful for context.

bundle failed - cannot access a scoped thread local variable without calling `set` first

It can't bundle @arco-design/web-react.

source code

import { Button } '@arco-design/web-react';

spack config

module.exports = {
  entry: {
    web: __dirname + '/entry.js',
  },
  output: {
    path: __dirname + '/dist',
  },
  module: {},
};

error message after running npx spack

hread '<unnamed>' panicked at 'cannot access a scoped thread local variable without calling `set` first', /Users/runner/.cargo/registry/src/github.com-1ecc6299db9ec823/scoped-tls-1.0.0/src/lib.rs:168:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
node:internal/process/promises:279
            triggerUncaughtException(err, true /* fromPromise */);
            ^

[Error: panic detected] { code: 'GenericFailure' }

version:
cli - 0.1.57
core - 1.2.223

Cannot read properties of undefined (reading 'stripLeadingPaths')

Related to #283

@swc/cli 0.3.1

swc src --config-file ./.swcrc --out-dir dist

.swcrc:

{
  "$schema": "https://json.schemastore.org/swcrc",
  "exclude": ["./**/*.test.ts", "./**/*.spec.ts", "test/**/*"],
  "module": {
    "type": "es6",
    "strictMode": true,
    "noInterop": false
  },
  "jsc": {
    "externalHelpers": false,
    "target": "es2022",
    "parser": {
      "syntax": "typescript",
      "dynamicImport": true
    },
    "keepClassNames": true
  }
}

--only and --ignore clarity

It seems these two flags:

  • --only
  • --ignore

are not yet present in the cli handle function.

Let's say I want to avoid to compile every js files under __tests__ folder.
That means the command would look more or less like this:

swc -d dist --ignore '**/__tests__/**'

But in the output folder, I would still have the __tests__ folder.


SWC version:

"@swc/cli": "0.1.36"
"@swc/core": "1.2.51"

I would be happy to open PR if you validate about this issue :)

Add an option to process files in parallel with worker processes

It looks like @swc/cli processes files in parallel on the main thread (here). It should be significantly faster to process files using a pool of worker sub-processes. This is straightforward to implement using @swc/core, but it would be really nice to be able to integrate the official CLI into our build system instead of this little custom wrapper.

I tried this out for minification on a large internal project with ~2400 output files:

  • Running the CLI with --sync takes ~3m24s
  • Running the CLI in parallel mode takes ~2m28s
  • Using a pool of 8 worker processes takes ~18s

Is this something the project would consider?

Maps generating even after setting `-s false`

Describe the bug

SWC still generating map even after setting --source-map or -s to false

Input code

package.json

"scripts": {
  "compile:ts": "swc source/main.dev.ts -w -s false -q -o dist/main.js"
},

Config

{
  "minify": true,
}

even after removing flags from the script and adding same configuration in .swcrc the output is same

{
  "minify": true,
  "sourceMaps": false
}

Expected behavior

The output should not generate *.js.map file after setting -s to false

Actual behavior

Generating source maps.

Input

image

Output

image

Version

@swc/cli - ^0.1.55, @swc/core - ^1.2.133

(Bug?) Outdir adds "baseUrl" to directory structure as of V0.3.0

When setting the baseUrl in .swcrc as such:

{
    "jsc": {
        "baseUrl": "./src"
    }
}

...And running swc with the outdir set like this:

npx swc --config-file .swcrc ./src -d dist

I end up with an extra /src/ in the outdir folder

image


Is this a breaking change for V0.0.3 or might this be a bug?

Comparison: V0.2.3 outputs vs V0.3.0 outputs

V0.2.3

image

V0.3.0 (wrapped in an additional src directory

Screenshot from 2024-01-25 18-37-57

lib/**/*.ts should match lib/index.ts, but it does not

My file list:

lib
├── base.ts
├── databaseClient.ts
├── index.ts
└── test
    └── a.ts

run swc via yarn build (this is required step!)

$ yarn build
yarn run v1.22.10
$ swc -d dist lib/**/*.ts
[ 'lib/test/a.ts' ] # I add console.log(program.args) into node_modules/@swc/cli/lib/swc/options.js line 65 for debugging
Successfully compiled: 1 file with swc (5.71ms)
Done in 0.22s.

then I change the build script to swc -d dist lib/*.ts lib/**/*.ts , run again

$ yarn build
yarn run v1.22.10
$ swc -d dist lib/*.ts lib/**/*.ts
[
  'lib/base.ts',
  'lib/databaseClient.ts',
  'lib/index.ts',
  'lib/test/a.ts'
]
Successfully compiled: 4 files with swc (9.43ms)
Done in 0.20s.

but, when I run swc in zsh, the bug disappears:

$ npx swc -d dist lib/**/*.ts
[
  'lib/base.ts',
  'lib/databaseClient.ts',
  'lib/index.ts',
  'lib/test/a.ts'
]
Successfully compiled: 4 files with swc (9.45ms)

It looks like a bug of commander.

Config output path name property does not work

Setting the name property inside output does not affect the output file name

E.g.

/// spack.config.js
const { config } = require("@swc/core/spack");

module.exports = config({
  entry: __dirname + "/src/index.ts",
  output: {
    path: __dirname + "/dist/scripts",
    name: "content.js",
  },
});
image

There is no reliable way to include/exclude files

I have a typescript project and I am using the following swc config:

{
  "$schema": "https://json.schemastore.org/swcrc",
  "jsc": {
    "parser": {
      "syntax": "typescript",
      "tsx": true,
      "decorators": true,
      "dynamicImport": true
    },
    "target": "es2018",
    "loose": false,
    "externalHelpers": false,
    "transform": {
      "react": {
        "runtime": "automatic"
      }
    }
  }
}

Then I run it with this command:

swc src --config-file ./configs/swc/.swcrc -C module.type=commonjs -d build --only **/*.{ts,mts,cts,tsx} --ignore **/*.d.{ts,mts,cts,tsx}

The problem is, the --only & --ignore properties don't work. It still grabs all the files, compiles them, and outputs them. The reason this is an issue is that I have some .d.ts files in my sources, and they get compiled into .d.js files. This is completely incorrect behavior.

I've tried --only/--ignore. I've tried the "exclude" property in the swcrc (which results in a parsing error of the swcrc). Nothing works.

I love what SWC can do in terms of its lightning-fast compilation, but from a configuration perspective it is just consistently painful to work with. I sincerely hope that there is work on a better, more reliable configuration system.

Search upwards for config file

When you run swc it should search upwards for the first .swcrc file similar to how Babel does it. Although this became quite complex with Babel in later releases.

`--ignore` and `--only` do not work

When compiling code, option --ignore provided pattern does not go into the glob config. That said the following command will compile tests even if they are ignored,

swc src --ignore **/__tests__/**/*.ts -d build

--copy-files does not seem to copy any files

Description

It seems the --copy-files option does not copy over the non-compilable files, as described in the help.

-D, --copy-files                            When compiling a directory copy over non-compilable files

Reproduction

I have the following folder structure:

├── src
│   ├── index.ts
│   └── message.txt

To build it, I run the following command:

yarn swc src -d build --copy-files

The resulting build does not include the message.txt.

├── build
│   └── index.js

Versions

  • @swc/cli: 0.1.34
  • @swc/core: 1.2.47

Empty output for latest swc/[email protected]

Input code

src/index.ts

export function log() {
  return 'Hello World'
}

package.json script

  "scripts": {
    "build": "swc ./src/index.ts -o ./dist/index.js"
  },

Config

{
  "jsc": {
    "parser": {
      "syntax": "typescript",
      "dynamicImport": true
    },
    "target": "es2020"
  }
}

Expected behavior

it should have build output

Version

@swc/cli@^0.1.54 and @swc/core@^1.2.120

Additional context

This works when cli is at version 0.1.52

Add code formatter/linter

@kdy1 Hi. How about adding code formatter (e. g. prettier)? I can help by opening PR with changes if you accept this idea.

Also, you can ping me if you need some help with other stuff. I have a great experience with TS/JS/web and open source projects.

Support for ESM in spack

My project uses ESM, but spack currently attempts to require('spack.config.js'). I can't use require with module: true, but I also cannot rename the config to spack.config.cjs or it won't be found since it's hardcoded to look for spack.config.js

TS + ES Module paths

is there a way to use swc + typescript to emit valid ES Module paths. e.g.

typescript source:

import foo from './foo';

output:

import foo from './foo.js';

--config with dot notation seems not working

Issue

According to the documentation, by using the command swc src -C module.type=commonjs, it should transpile the code with type option set to be commonjs.

But, when I have used that command, it threw some error like

Argument at `2` is not JsBuffer

Caused by:
    unknown field `module.type` at line 1 column 100

Suspect

When I have tried to fix the issue, I found out that src/swc/options.ts#L230 only assigns the value to the top level configuration.

So I have changed that line to something like the following code, and I could find out that it transpiles successfully.

const keyArray = key.split('.');
const options = keyArray
	.slice(0, -1)
	.reduce((config, currentKey) => {
		if (!config[currentKey]) {
			config[currentKey] = {};
		}

		return config[currentKey];
	}, swcOptions);

options[keyArray[keyArray.length - 1]] = value;

Now, I am curious whether this is the intended behavior or not.
Please let me know if I am using the swc cli inappropriately.

Thank you!

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.