vitest-dev / vitest

Next generation testing framework powered by Vite.
https://vitest.dev
MIT License
12.21k stars 1.07k forks source link

TypeScript accessor keyword throws rollup error: Unexpected token `...`. Expected * for generator, private key, identifier or async #5976

Closed khaosdoctor closed 6 days ago

khaosdoctor commented 1 week ago

Describe the bug

If you create a simple TypeScript file with a class like so:

class Foo {
    accessor bar: string

    constructor (s: string) {
        this.bar = s
    }
}

And try to write a test importing this file, rolloup throws an error Unexpected tokenbar. Expected * for generator, private key, identifier or async

Reproduction

I'm testing with the following file: https://github.com/Formacao-Typescript/projeto-3/blob/vitest/src/domain/Class.ts And this is the test: https://github.com/Formacao-Typescript/projeto-3/blob/vitest/src/domain/Class.test.ts

If I keep the accessor keyword: image

If I remove the keyword: image

System Info

System:
    OS: macOS 14.5
    CPU: (10) arm64 Apple M1 Max
    Memory: 729.30 MB / 32.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 22.2.0 - ~/.asdf/installs/nodejs/22.2.0/bin/node
    Yarn: 1.22.22 - ~/.asdf/installs/nodejs/22.2.0/bin/yarn
    npm: 10.7.0 - ~/.asdf/plugins/nodejs/shims/npm
    pnpm: 9.4.0 - ~/.asdf/installs/nodejs/22.2.0/bin/pnpm
    bun: 1.0.4 - ~/.asdf/shims/bun
    Watchman: 2024.05.06.00 - /opt/homebrew/bin/watchman
  Browsers:
    Safari: 17.5
  npmPackages:
    @vitest/coverage-v8: ^1.6.0 => 1.6.0 
    @vitest/ui: ^1.6.0 => 1.6.0 
    vitest: ^1.6.0 => 1.6.0

Used Package Manager

npm

Validations

AriPerkkio commented 1 week ago

Try changing target of esbuild:

import { defineConfig } from "vitest/config";

export default defineConfig({
  esbuild: {
    target: "es2022",
  },
  test: {
    // ...
  },
});

This is not part of Javascript syntax and ESBuild will just parse it and pass through. If the target is something else than esnext, it will be transformed: https://github.com/evanw/esbuild/blob/main/CHANGELOG-2023.md#0185

This syntax is not yet a part of JavaScript but it was added to TypeScript in version 4.9. More information about this feature can be found in https://github.com/microsoft/TypeScript/pull/49705. Auto-accessors will be transformed if the target is set to something other than esnext

When esbuild doesn't transform this non-JS syntax, Rollup will fail to parse the file.

sheremet-va commented 6 days ago

@AriPerkkio should we automatically lower esbuild target to the lowest Node.js we support?

khaosdoctor commented 6 days ago

Yep, that worked fine @AriPerkkio thanks!

AriPerkkio commented 5 days ago

should we automatically lower esbuild target to the lowest Node.js we support?

I'm not sure. As esbuild is only used for TS files, it would create a weird situation where different syntax would not work on JS file.