Файли
openidea/docs/en/languages/javascript.mdx
T
LU XIANGRUIтаwildcatDownstairs 5785ebadd8 feat(typescript): import style code style settings, sent to tsserver (#6342)
Editor > Code Style > JavaScript and TypeScript get an Imports tab: import paths (shortest / relative / non-relative / relative within the project), import path ending (automatic / minimal / index / .js), and glob and regex lists of what not to auto-import. They are stored with the code style, added to the servers' typescript/javascript preferences under both vtsls and typescript-language-server key names, and sent to running servers with didChangeConfiguration; a server's own Language Servers settings still win. The two exclusion lists are always sent (as [] when unset) so clearing one takes effect without a restart. Adds the typescript_import_style language smoke test.

Closes #6072

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 15:26:29 +08:00

143 рядки
21 KiB
Plaintext
Неформатований Анотація Історія

Цей файл містить неоднозначні символи Юнікоду
Цей файл містить символи Юнікоду, які можна сплутати з іншими символами. Якщо ви вважаєте, що це зроблено навмисно, можете сміливо ігнорувати це попередження. Щоб показати їх, скористайтеся кнопкою Escape.
---
title: "JavaScript and TypeScript"
description: "Language servers, Node.js detection, npm scripts, tests, debugging and framework support for JavaScript, TypeScript, Vue, Svelte, Astro and Angular."
---
OpenIDEA edits JavaScript (`.js`, `.mjs`, `.cjs`, `.jsx`) and TypeScript (`.ts`, `.mts`, `.cts`, `.tsx`) with highlighting and structure that work without any setup, and gets completion, navigation, refactoring and diagnostics from a TypeScript language server. Vue, Svelte, Astro and Angular projects get their framework's own server on top. See the [support matrix](/en/languages/index) for every language at a glance.
## Language servers
| Files | Server | Notes |
| ------------------------------- | -------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| JS, JSX, TS, TSX | `vtsls` | Default TypeScript server. |
| JS, JSX, TS, TSX | `typescript-language-server` | Fallback: used only while `vtsls` is not installed. |
| `.vue` | `vue-language-server` + `vtsls` | Vue's hybrid mode: TypeScript inside `.vue` files comes from `vtsls` with `@vue/typescript-plugin`. |
| `.svelte` | `svelte-language-server` | |
| `.astro` | `astro-ls` | Needs Node.js and a TypeScript library. |
| TS and HTML in Angular projects | `angular-language-server` (`ngserver`) | Only below `angular.json` or `node_modules/@angular/core`. |
| All of the above | `oxlint` | Only below an `.oxlintrc.json`, `.oxlintrc.jsonc`, `oxlint.config.ts` or `oxlint.config.mts`. |
| All of the above | `vscode-eslint-language-server` (ESLint) | Only below an ESLint configuration (`eslint.config.*`, `.eslintrc*` or `eslintConfig` in `package.json`); runs the project's own `eslint`. |
| JS, JSX, TS, TSX, JSON, CSS | `biome lsp-proxy` (Biome) | Only below a `biome.json` / `biome.jsonc` or an installed `@biomejs/biome`; runs the project's own `biome`. |
| All of the above, HTML and CSS | `tailwindcss-language-server` (Tailwind CSS) | Only below a `tailwind.config.*` or a `package.json` that depends on `tailwindcss`: class completion, hover with the generated CSS, and class diagnostics. |
The TypeScript servers start for a workspace marked by `tsconfig.json`, `jsconfig.json` or `package.json`. Files outside any `tsconfig.json` / `jsconfig.json` are still registered with tsserver, so loose scripts get code insight too.
Path aliases from `vite.config.*` (`resolve.alias`), `rollup.config.*` (`@rollup/plugin-alias` `entries`) and `esbuild.config.*` (`alias`) are added to tsserver's `paths`; in a monorepo each package (`apps/web`, …) gets its own configuration's aliases, so imports such as `@/components/Button` resolve, navigate and complete. The configuration is read without running it: object and `[{ find, replacement }]` forms with string, `path.resolve(__dirname, …)` or `fileURLToPath(new URL(…, import.meta.url))` targets; aliases computed any other way are skipped. `paths` in `tsconfig.json` / `jsconfig.json` take priority. Aliases are read when the language server starts.
Two behaviours differ from the servers' defaults: renaming a symbol never introduces an `import { a as b }` alias, and moving a file does not make the server rewrite imports on its own; the IDE asks for the import updates first and shows them as a preview you can undo.
Inlay hints show parameter names at literal arguments, inferred variable types and enum member values; turn kinds off in **Settings › Editor › Inlay Hints**.
### Project-wide type errors
The language server checks open files only. To keep the type errors of the whole project in the Problems tool window, turn on **TypeScript Project Errors (tsc --watch)** in the Problems tool window's ⋮ menu (off by default, saved in the project settings). The IDE then runs the project's own `node_modules/.bin/tsc --noEmit --watch` for each `tsconfig.json` that no other one references (`tsc -b --watch` for a solution with project references) and replaces the errors after every compilation. It never writes into the project: outputs and `.tsbuildinfo` files go to a temporary folder. Configurations in folders that are ignored (`.gitignore`), excluded, hidden, or named `fixtures`, `examples` or `testdata` are skipped. Files open in an editor show the language server's errors instead, and an error that Build also reported is listed once. Nothing runs without a local `typescript` or in Restricted Mode.
### TypeScript version
**Settings › Languages & Frameworks › TypeScript** picks the TypeScript that `vtsls` and `typescript-language-server` load:
- **Bundled** (default): the language server's own TypeScript.
- The project's `node_modules/typescript`, when it is installed.
- Any TypeScript `lib` directory, chosen with the folder button.
The Vue, Astro and Angular servers use the selected version too. TypeScript 7 (the native port) has no language-service API, so the IDE installs `typescript-language-server`, Vue, Svelte and Astro servers together with `typescript@6`.
The native TypeScript 7 server and the tsserver-based servers use the same **JavaScript and TypeScript** colour-scheme entries. Module-level functions use **Global function**; local calls use **Function call**. **Predefined function** applies when the server marks a symbol as a standard-library member. TypeScript 7.0.2 can omit that marker on case-insensitive filesystems ([TypeScript fix](https://github.com/microsoft/typescript-go/pull/4654)).
## Setup
### Installing the servers
When you open a file whose server is missing, a notification names it (for example "vtsls (TypeScript) is not installed") with **Install** and **Language Servers…** buttons. **Install** runs npm (or pnpm) and puts the package in the IDE's own tools folder, so nothing is installed globally and no `sudo` is needed. This needs `npm` or `pnpm` on `PATH`.
All servers, debuggers and formatters are listed in **Settings › Languages & Frameworks › Language Servers**, where you can install, reinstall, point a server at your own executable, or change its arguments, environment and initialization options. A server already on your `PATH` is used as well.
| Tool | Installed with |
| -------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- |
| `vtsls`, `typescript-language-server` | npm (`@vtsls/language-server`; `typescript-language-server` + `typescript@6`) |
| `vue-language-server`, `svelte-language-server`, `astro-ls`, `angular-language-server` | npm |
| `oxlint` | npm |
| `tailwindcss-language-server` | npm (`@tailwindcss/language-server`) |
| Prettier, oxfmt, Biome, dprint | npm |
| JavaScript Debugger (vscode-js-debug) | GitHub release (`microsoft/vscode-js-debug`) |
The Astro and Angular servers also run from the project's own `node_modules/.bin` when it has them.
### JavaScript runtime
**Settings › Languages & Frameworks › JavaScript Runtime** has:
- **Preferred runtime**: what runs JavaScript and TypeScript files from the gutter and the editor's **Run** action: Node.js, Bun or Deno. **Auto** looks for the nearest `deno.json` / `deno.jsonc` (Deno) or `bun.lock` / `bun.lockb` (Bun) up to the project root, and otherwise uses Node.js.
- **Node interpreter**: the `node` that runs npm scripts, Node files and the Node-based language servers. **Default** uses `node` on `PATH`. The list shows every Node.js found on `PATH` and those installed by nvm, Volta, fnm, mise and asdf.
- **Run in target**: run Node and package-manager commands locally or in one of the run targets from **Settings › Build, Execution, Deployment › Run Targets**.
- **Package manager**: `npm`, `pnpm`, `yarn` or `bun` for the detected script configurations. **Auto** reads `packageManager` in `package.json`, then the lock file (`pnpm-lock.yaml`, `yarn.lock`, `bun.lock` / `bun.lockb`, `package-lock.json`), and otherwise uses npm.
## Formatting
**Reformat Code** (`⌥⌘L` / `Ctrl+Alt+L`) uses the language server unless an external formatter is configured to win:
- **Prettier** (**Settings › Languages & Frameworks › Prettier**) formats JavaScript, JSX, TypeScript, TSX, JSON, Vue, HTML, CSS, SCSS, Less, GraphQL, YAML and Markdown by default. The executable is found in the project's `node_modules`, then the managed installation, then `PATH`, unless you set **Prettier path**.
- **oxfmt** (**Settings › Languages & Frameworks › oxfmt**) replaces Prettier for an enabled language in files below an oxfmt configuration (`.oxfmtrc.json`, `oxfmt.config.ts`), or when it is the selected provider.
- **Biome** (**Settings › Languages & Frameworks › Biome**) replaces Prettier and oxfmt for JavaScript, JSX, TypeScript, TSX, JSON, CSS and GraphQL in files below a `biome.json` / `biome.jsonc` or an installed `@biomejs/biome` (unless the configuration sets `formatter.enabled` to `false`), or when it is the selected provider. It formats whole files and reads its own configuration.
- **dprint** (**Settings › Languages & Frameworks › dprint**) formats every file its configuration's plugins cover (`dprint editor-info`), whatever the language, in files below a `dprint.json` / `.dprint.json` / `dprint.jsonc` or an installed `dprint`, or when it is the selected provider. It runs the project's own `dprint fmt --stdin` and formats whole files; files its plugins don't cover keep their usual formatter, and so do all files when dprint can't run there (not installed, plugins not downloadable); **Reformat with dprint** reports why. With **Format on save** on, saving runs it too.
On these pages, **Formatting provider** chooses between **Automatic (language server first)** and the tool itself, **Run on save** formats on save, and **Enabled languages** limits which languages the tool handles.
With **Automatic**, a JavaScript or TypeScript file below the tool's own configuration (a Prettier configuration file or `prettier` key in `package.json`, an oxfmt configuration, or Biome's) is formatted by that tool rather than by the language server, once the tool is installed (before `npm install`, the language server formats). **Settings › Editor › General › Reformat code on save** then runs the tool too.
### Code style
**Settings › Editor › Code Style › JavaScript** and **TypeScript** have **Spaces** (after commas, around operators, within braces and so on) and **Punctuation** (semicolons: keep, use or don't use; quotes: as in the file, single or double). They are saved per project with the other code style settings and sent to the TypeScript server, which applies them to **Reformat Code** and to the code it adds: quick fixes, auto-imports, refactorings and **Optimize Imports**. JSX files follow JavaScript and TSX files TypeScript. When EditorConfig support is on, the project's `.editorconfig` comes first where it sets `quote_type` or the IntelliJ properties `ij_typescript_use_semicolon_after_statement`, `ij_typescript_use_double_quotes`, `ij_typescript_space_after_comma`, `ij_typescript_spaces_within_object_literal_braces` and the like (`ij_javascript_*` for JavaScript). tsserver has no trailing-comma option, so trailing commas stay as written.
The **Imports** tab sets how the TypeScript server writes the imports it adds (auto-import, quick fixes, moving files): **Import paths** (shortest, relative, non-relative through `paths` / `baseUrl`, or relative within the project), **Import path ending** (automatic, `./components`, `./components/index` or `./components/index.js`), **Do not auto-import from** (globs such as `**/index.ts` to keep barrel files out) and **Do not auto-import specifiers matching** (regular expressions for the import path, such as `^node:`). Like the other tabs, they are saved per project, separately for JavaScript and TypeScript, and apply to a running server without a restart.
### Biome lint
In a Biome project, Biome's diagnostics show in the editor and the Problems tool window, and `⌥⏎` / `Alt+Enter` offers its quick fixes and suppressions. Biome's safe fixes (`source.fixAll.biome`) run with **Code › Code Cleanup** and, when **Settings › Tools › Actions on Save › Run code cleanup** is on, on save. When Biome's formatter is enabled, its fix-all formats the file too.
## Run and test
OpenIDEA detects run configurations when the project opens:
- One configuration per `package.json` script (`npm run build`, `pnpm run dev`, …), for the root package, nested packages and workspace members. Scripts named `test`, `jest`, `vitest` or `test:*`, and scripts that run `playwright test`, `node --test`, `mocha` or `jasmine`, are test configurations.
- `playwright test` (through `npx`) for a package with a `playwright.config.*` that no script runs.
- `cypress run` (through `npx`) for a package that depends on `cypress` or has a `cypress.config.*`, when no script runs `cypress run` (scripts that do are test configurations). Its **Cypress** configuration chooses the testing type (end-to-end or component), the browser, the specs and further options.
- One per task in `deno.json` / `deno.jsonc` (`deno task <name>`).
In `package.json`, the gutter shows run icons on each `scripts` entry to run or debug it.
**Run Context Configuration** (`⌃⇧R` / `Ctrl+Shift+F10`) on a source file:
- A test file (`*.test.*`, `*.spec.*`, or anything under `__tests__/`) runs through the closest test script with the file added. The gutter icons on `test`, `it` and `describe` blocks run one test or suite by adding `-t <name>`.
- Any other `.js` file runs with `node` (with `deno run` or `bun run` in a project with `deno.json` or `bun.lock`).
- A `.ts` file runs with Node.js directly on 22.18+ / 23.6+, with `--experimental-strip-types` on 22.6–22.17 and 23.0–23.5, else through `tsx` or `ts-node`.
Jest, Vitest, Playwright Test, `node --test`, Mocha and Jasmine output is turned into the test tree, with **Rerun Failed Tests**. Playwright runs report through its `list` reporter unless the configuration names another; a test in the gutter runs by its line (`file:line`), and runs with several projects show each project under its file. `node --test` runs report through the IDE's reporter next to `spec`, added to `NODE_OPTIONS` (a script that chooses its own `--test-reporter` runs without the tree); single tests and reruns are selected by full name (`--test-name-pattern`). Mocha runs keep their reporter and load an IDE hook through `NODE_OPTIONS` that reports each test with its line; single tests and reruns use `--grep`, and in projects that test with Mocha or `node --test`, tests in `test/` get gutter icons whatever their file name. Jasmine runs work the same way, with `--filter=` in place of `--grep`; `fdescribe`, `fit` and `xit` get gutter icons too, and in projects that test with Jasmine so do specs in `spec/` (`cartSpec.js`). **Run with Coverage** works for scripts that run `vitest` or `jest` (Vitest needs a coverage provider such as `@vitest/coverage-v8`; the IDE offers to add it) and for `node` / `tsx` / `ts-node` runs through `c8`. See [Testing](/en/guide/testing) and [Coverage](/en/guide/coverage).
Cypress runs report through Cypress's built-in `teamcity` reporter unless the configuration names another, and show each spec's suites and tests in the test tree; selecting a test opens its declaration. `*.cy.*` files get gutter icons, and run on the project's Cypress configuration (other tests stay on its other runner); a spec runs with `--spec`, and a spec that mounts components (`cy.mount`) or sits in `cypress/component/` runs with `--component`. `cypress run` can't select tests by name, so single tests, suites and **Rerun Failed Tests** pass their full titles to the [`@cypress/grep`](https://github.com/cypress-io/cypress/tree/develop/npm/grep) plugin: as `--expose grep=…` on Cypress 15.10 and later (`@cypress/grep` 7), and in the `CYPRESS_grep` environment variable (earlier versions). Without a grep plugin among the dependencies (`@cypress/grep`, `cypress-grep`), they run their whole spec files, a notification says so, and the tree shows every test that ran.
## Debugging
Debugging uses the JavaScript Debugger (vscode-js-debug); if it is missing, the first debug session offers to install it.
- **Debug** works for npm script configurations, Node.js files and `deno run` / `deno test`. Child processes are attached automatically.
- **Attach to Node.js** is a run configuration type for a process started with `--inspect` on this or another machine (default port 9229), with local and remote root mapping. With **Reconnect automatically** on, the session waits while the process restarts (nodemon, `node --watch`, `tsx watch`) and attaches to it again with the same breakpoints.
- **Attach to Process…** in the Run menu lists running Node.js processes.
- **JavaScript Debug** is a run configuration type that opens a URL in Chrome or Edge and debugs the page's JavaScript and TypeScript through source maps. Start the page's server first (for example with the `dev` npm script); **Web root** is the folder the URL serves, the project root by default.
With **Do not step into library scripts** (**Settings › Build, Execution, Deployment › Debugger › Stepping**, on by default), stepping skips Node.js internals and `node_modules`. More in [Debugging](/en/guide/debugging).
## Framework support
- **React**: JSX and TSX get their own highlighting modes and full TypeScript server support. Typing `>` closes the tag, renaming an opening or closing tag renames its partner, and completing a prop name or typing `=` after one inserts `""` for string props or `{}` for others (from the prop's type). `⇥` / `Tab` expands Emmet abbreviations among an element's children or after `return` / `=>`: `.card` becomes `<div className="card"></div>`.
- **Vue**: `.vue` files are highlighted per block and served by Vue Language Server in hybrid mode. In a Vue CLI project without `tsconfig.json`, webpack's `resolve.alias` entries (such as `@/`) are read so imports resolve. Prettier formats `.vue` files. Emmet works in templates.
- **Svelte**: Svelte Language Server; highlighting uses the HTML mode (script as TypeScript, style as CSS). Emmet works in markup.
- **Astro**: Astro Language Server with its own highlighting mode. It needs Node.js; if it can't find one, select it in **Settings › Languages & Frameworks › JavaScript Runtime**.
- **Angular**: in projects with `angular.json` or `@angular/core` installed, templates in HTML files and inline `template:` strings get Angular highlighting, and the Angular Language Server adds template completion, navigation and rename. The server is configured for the project's Angular version.
## Limitations
- Debugging Bun needs `bun-dap`, which has no release yet: build it from `morf-bls/bun-dap` and put it on `PATH` (the IDE shows the steps when it is missing). vscode-js-debug can't attach to Bun's WebKit-protocol inspector.
- Deno has run and debug support but no Deno language server; Deno files use the TypeScript servers.
- Coverage of Deno tasks is not supported.