Как установить javascript
Перейти к содержимому

Как установить javascript

  • автор:

JavaScript

With IntelliJ IDEA, you can develop modern web, mobile, and desktop applications with JavaScript and Node.js .

IntelliJ IDEA also supports React , Angular , Vue.js , and other frameworks and provides tight integration with various tools for web development.

JavaScript-aware coding assistance includes completion for keywords, labels, variables, parameters, and functions, error and syntax highlighting, formatting, code inspections and quick-fixes, as well as common and JavaScript-specific refactoring. IntelliJ IDEA also integrates with JavaScript linters and the Flow type checker.

With the built-in debugger, you can debug both your client-side and server-side code and even run JavaScript code snippets in the interactive debugger console. Note that IntelliJ IDEA supports debugging JavaScript only in Chrome or any other browser of the Chrome family. Learn more from Debug JavaScript in Chrome.

IntelliJ IDEA integrates with Jest, Karma, Protractor, Cucumber, and Mocha testing frameworks. IntelliJ IDEA supports running and debugging tests as well as navigation between tests and subjects or between a failed test and the fragment of code that caused the problem.

On this page you will find a short Getting Started Guide that will walk you step by step from creating a web application to debugging and testing it.

Before you start

Make sure the JavaScript and TypeScript plugin is enabled in the settings. Press Control+Alt+S to open the IDE settings and then select Plugins . Click the Installed tab. In the search field, type JavaScript and TypeScript . For more information about plugins, refer to Managing plugins.

Create a new application

  1. Select File | New | Project from the main menu or click the New Project button on the Welcome screen.
  2. In the New Project dialog, select New Project in the left-hand pane.
  3. In the right-hand pane, select JavaScript in the Language area.
  4. Name the new project and change its location if necessary, then click Create .

Start with an existing JavaScript application

If you are going to continue developing an existing JavaScript application, open it in IntelliJ IDEA, choose the JavaScript version to use, and configure the libraries in it. Optionally download the required npm dependencies.

Open the application sources that are already on your machine

  • Click Open or Import on the Welcome screen or select File | Open from the main menu. In the dialog that opens, select the folder where your sources are stored.

Check out the application sources from your version control

  1. Click Get from VCS on the Welcome screen. Alternatively, select File | New | Project from Version Control or Git | Clone… from the main menu. Instead of Git in the main menu, you may see any other Version Control System that is associated with your project. For example, Mercurial or Perforce .
  2. In the dialog that opens, select your version control system from the list and specify the repository to check out the application sources from. For more information, refer to Check out a project (clone).

Project security

When you open a project that was created outside IntelliJ IDEA and was imported into it, IntelliJ IDEA displays a dialog where you can decide how to handle this project with unfamiliar source code.

Untrusted project warning

Select one of the following options:

  • Preview in Safe Mode : in this case, IntelliJ IDEA opens the project in a preview mode. It means that you can browse the project’s sources but you cannot run tasks and script or run/debug your project. IntelliJ IDEA displays a notification on top of the editor area, and you can click the Trust project… link and load your project at any time.
  • Trust Project : in this case, IntelliJ IDEA opens and loads a project. That means the project is initialized, project’s plugins are resolved, dependencies are added, and all IntelliJ IDEA features are available.
  • Don’t Open : in this case, IntelliJ IDEA doesn’t open the project.

Projects created from the Welcome screen or via File | New | Project as described in are automatically considered trusted.

Choose the JavaScript language version

To get reliable and efficient coding assistance, you need to specify the language version that will be used in all JavaScript files of your project by default.

  1. In the Settings dialog ( Control+Alt+S ), go to Languages & Frameworks | JavaScript . The JavaScript page opens.
  2. From the list, choose one of the supported JavaScript language versions:
    • ECMAScript 5.1
    • ECMAScript 6+: This version adds support for the features introduced in ECMAScript 2015-2020 and for JSX syntax as well as some current proposals to the standard.
    • Flow: This version adds support for the Flow syntax.

Use multiple JavaScript versions

If you are working on an application that uses both ECMAScript 5.1 and a newer version of ECMAScript, the easiest way is to choose the highest language version for the whole project from the list on the JavaScript page ( Settings | Languages & Frameworks | JavaScript ).

Choose language versions for separate folders

  1. On the JavaScript page, click next to the JavaScript language version list. The JavaScript Language Versions dialog opens.
  2. Click and in the dialog that opens select the folder where you need a custom language version. IntelliJ IDEA brings you back to the JavaScript Language Versions dialog where the selected folder is shown in the Path field.
  3. From the Language list, choose the language version for the files in the selected folder. In all the other JavaScript files in the project IntelliJ IDEA will use the version chosen on the JavaScript page.

JSX syntax in JavaScript code

If you are using JSX syntax in your JavaScript code, enable ECMAScript 6+ .

Enable the React JSX syntax inspection

  • In the Settings dialog ( Control+Alt+S ), go to Languages & Frameworks | JavaScript , and select ECMAScript 6+ from the JavaScript language version list.
  • To be warned when JSX syntax is used by mistake, open the Settings dialog ( Control+Alt+S ), go to Editor | Inspections , and enable the React JSX syntax inspection under JavaScript and TypeScript | General node. Use the search field to locate the inspection. Optionally, configure the inspection severity and scope. Learn more from Code inspections.

Download project dependencies

If your application uses some tools, libraries, or frameworks, download the required packages. To manage your project dependencies, you can use npm, Yarn 1, or Yarn 2, refer to npm and Yarn for details.

Install a package in an empty project

  • In the embedded Terminal ( Alt+F12 ) , type: npm install .

If you already have a package.json file in your project

  • Right-click the package.json file in the editor or in the Project tool window and choose Run ‘npm install’ from the context menu.
  • Alternatively, run npm install in the Terminal Alt+F12 .

Before you start, make sure you have Node.js on your computer.

Configure code completion for project dependencies

To provide code completion for project dependencies, IntelliJ IDEA automatically creates a node_modules library. In context of the language and the IDE, a library is a file or a set of files. Functions and methods of these files are added to IntelliJ IDEA’s internal knowledge in addition to the functions and methods that IntelliJ IDEA retrieves from the project code that you edit. For more information, refer to Configure JavaScript libraries and Code completion.

View inlay hints

Inlay hints appear in the editor and provide you with additional information about your code to make it easier to read and navigate.

Parameter hints

Parameter hints show the names of parameters in methods and functions to make your code easier to read. By default, parameter hints are shown only for values that are literals or function expressions but not for named objects.

Parameter hints in JavaScript

Configure parameter hints

  1. Open the Settings dialog ( Control+Alt+S ) and go to Editor | Inlay Hints .
  2. Expand JavaScript under Parameter names .
  3. Specify the context in which you want parameter hints shown by selecting the corresponding checkboxes. The preview shows how the changes you make in the settings affect the code appearance.
  4. For some methods and functions, IntelliJ IDEA does not show parameter hints in any context. Click Exclude list. to view these methods and functions, possibly enable parameter hints for them, or add new items to the list.
  5. To hide parameter hints for any value type in any context, clear the JavaScript checkbox under Parameter names .

Return type hints

IntelliJ IDEA can display function return types in function calls and call chains.

  • Function return type hints are inferred from a JSDoc comment or based on the static analysis of your code.
  • Return type hints in method chains are displayed if the method calls are split between multiple lines and return at least 2 different types.

Configure method return type hints

  1. Open the Settings dialog ( Control+Alt+S ) and go to Editor | Inlay Hints .
  2. Under Types , expand the JavaScript node, and then select the Function return types checkbox.
  3. To show return type hints in method chains, expand the Method chains node and select the JavaScript checkbox.

The preview shows how the changes you make in the settings affect the code appearance.

Type hints

Type hints show the types of variables, fields, or parameters. The types of variables and fields are displayed next to their definition. Type hints for parameters are shown in function calls. Type hints are inferred from JSDoc comments or static analysis of your code.

Type annotations in JavaScript

Configure type annotations

JavaScript type annotation

  1. Open the Settings dialog ( Control+Alt+S ) and go to Editor | Inlay Hints .
  2. In the tree of categories, expand Types | JavaScript .
  3. Expand the Type annotations node and specify the context where you want type hints to be shown. The preview shows how the changes you make in the settings affect the code appearance.
  4. To hide parameter parameter type and return type hints for any value type in any context, clear the JavaScript checkbox under Types .

Auto-import in JavaScript

IntelliJ IDEA can generate import statements for modules, classes, components, and any other symbols that are exported. IntelliJ IDEA can add missing import statements on the fly when you complete ES6 symbols or CommonJS modules. IntelliJ IDEA either decides on the style of the import statement itself or displays a popup where you can choose the style you need.

Add ES6 import statements

If you are importing a symbol from your project into a file that is a ES6 module or that already contains ES import statements, IntelliJ IDEA automatically inserts an ES6 import on symbol completion.

For earlier JavaScript versions or when auto-import on completion is disabled, IntelliJ IDEA marks the symbol as unresolved and shows a tooltip with the suggested quick-fix:

Auto import with quick-fix: information tooltip

Alternatively, press Alt+Enter :

Auto import with quick-fix: suggestion list

If there’s more than one possible source of import, IntelliJ IDEA shows a list of suggestions:

Auto import with quick-fix: multiple choices

IntelliJ IDEA can also generate import statements for symbols defined in the project’s dependencies. Auto-import works for symbols from packages that contain TypeScript definition files (like in moment or redux) or sources written as ES modules.

If the current file already contains a ES6 import statement, IntelliJ IDEA inserts a new one also in the ES6 style.

Add CommonJS (require) import statements

If you are importing a symbol from your project into a file that already is a CommonJS module (with a require statement or module.export ), IntelliJ IDEA automatically inserts a CommonJS import on symbol completion.

Alternatively, place the caret at the symbol to import, press Alt+Enter , and select a quick-fix with the CommonJS ( require ) import style.

Quick fix: select import style

Whenever IntelliJ IDEA cannot define automatically what syntax should be used in a file, it displays a popup where you can choose between using the ES6 and CommonJS syntax.

Configure auto import

  1. To automatically add ES6 import statements on code completion, open the Settings dialog ( Control+Alt+S ), go to Editor | General | Auto Import , and select the Add JavaScript imports automatically checkbox in the TypeScript / JavaScript area.
  2. To configure the appearance of import statements, open the Settings dialog ( Control+Alt+S ), go to Editor | Code Style | JavaScript , and use the controls in the Imports tab. For more information, refer to Imports tab.

Configure syntax highlighting

You can configure JavaScript-aware syntax highlighting according to your preferences and habits.

  1. In the Settings dialog ( Control+Alt+S ), go to Editor | Color Scheme | JavaScript .
  2. Select the color scheme, accept the highlighting settings inherited from the defaults or customize them as described in Colors and fonts.

Run JavaScript in browser

  1. In the editor, open the HTML file with the JavaScript reference. This HTML file does not necessarily have to be the one that implements the starting page of the application.
  2. Do one of the following:
    • Choose View | Open in Browser from the main menu or press Alt F2 . Then select the desired browser from the list.
    • Hover over the code to show the browser icons bar: . Click the icon that indicates the desired browser.

Debug JavaScript

IntelliJ IDEA provides a built-in debugger for your client-side JavaScript code that works with Chrome or any other browser of the Chrome family. With IntelliJ IDEA, you can debug JavaScript applications running on the built-in server, on an external server, or on a remote server. For more information, refer to Debug JavaScript in Chrome.

Установка JavaScript — JS: Настройка окружения

Начнем с установки Node.js и знакомства с REPL.

Если на вашем компьютере пока не стоит Node.js, то выполните установку по нашей инструкции . После установки перезагрузите компьютер.

Теперь убедимся в том, что Node.js установился и работает. Для этого наберите в терминале node —version . Вывод должен быть примерно такой:

# Версия, которую вы увидите, должна быть не ниже, чем показана здесь # Иначе возможно появление ошибок node --version v17.6 

Интерактивный запуск кода

Самое время запустить код на JavaScript с помощью такой команды:

Запуск программы node запустит REPL — это программа, которая работает как командная оболочка. Она:

  • Ожидает ввод от пользователя (Read)
  • Выполняет введенный код (Eval)
  • Печатает на экран результат (Print)
  • Затем снова входит в режим ожидания (Loop)

REPL — это среда, похожая на обычный терминал, только вместо Bash-команд мы вводим в нее код на JavaScript. С помощью REPL можно набрать строчку кода и тут же выполнить ее, нажав Enter :

> 1 + 5 6 # Результат выполнения сразу отображается на экране > 7 % 2 1 

Такой способ помогает быстро проверять гипотезы, отлаживать код и делать простые вычисления.

REPL позволяет использовать переменные и запоминает предыдущий ввод:

> a = 5 5 > b = 10 10 > a + b 15 

Чтобы выйти из REPL, воспользуйтесь одним из этих вариантов:

  1. Наберите команду .exit и нажмите Enter
  2. Два раза нажмите CTRL + C
  3. Нажмите CTRL + D

После этого мы окажемся внутри обычной командной оболочки:

".help" for more information. > 1 + 5 6 > (To exit, press ^C again or ^D or type .exit) > $ 

Обратите внимание на разницу между понятиями REPL Node.js и командная оболочка. Когда мы набираем node, то запускается программа. Она не имеет никакого отношения к оболочке, в которой она запустилась.

Если мы попробуем ввести в этот REPL команду для командной оболочки, это приведет к разным синтаксическим ошибкам:

> cd ~ cd ~ ^ SyntaxError: Unexpected token ~ 

Пример установки и запуска Node.js на Ubuntu

Запуск кода из файлов

Для полноценной разработки REPL уже не подходит — в нем становится неудобно. Поэтому на практике разработчики записывают код в обычные текстовые файлы на своем компьютере.

Какой редактор для этого использовать? Сейчас самым распространенным и удобным редактором для кода считается VS Code . Скачайте его, установите и поизучайте интерфейс. У него много встроенных возможностей, которые расширяются плагинами.

Чтобы запустить VS Code из терминала, используйте команду code и дополнительно укажите директорию с проектом. Например, такой командой можно открыть редактор в текущей директории:

Откройте редактор, создайте в нем файл с именем index.js и следующим содержимым:

console.log("Hello, Hexlet!"); 

VS Code имеет встроенные механизмы, которые запускают код автоматически. Но пока вы только учитесь, поэтому стоит научиться запускать код вручную.

Для этого откройте терминал в той директории, где вы создали файл в редакторе. В терминале выполните такую команду:

# Сначала перейдите в директорию с файлом index.js 

Открыть доступ

Курсы программирования для новичков и опытных разработчиков. Начните обучение бесплатно

  • 130 курсов, 2000+ часов теории
  • 1000 практических заданий в браузере
  • 360 000 студентов

Наши выпускники работают в компаниях:

Fedora Developer Portal

Open-source cross-platform server-side JavaScript runtime environment.

Have a question? Ask Fedora.

Node.js

Node.js and npm installation

Starting from Fedora 24, npm is a part of Node.js package and does not need to be installed separately. Therefore, to install both npm and Node.js, you need to run:

$ sudo dnf install nodejs 

This will install V8 Javascript Engine, Node.js runtime and npm package manager and their dependencies. Versions present in repositories are usually current or to-be (in Rawhide) Node.js LTS releases, including npm and V8 engine that come with them.

Alternative versions

There are alternative versions available as Fedora Modules.

Note: Modules are available for all editions from Fedora 29, and on the Server Edition from Fedora 28.

To list all available versions, run:

$ dnf module list 

And to install an alternative version, run a command similar to this:

$ sudo dnf module install nodejs:8 

Managing multiple versions with nvm

nvm (Node Version Manager) is a bash script to manage multiple Node.js versions. nvm makes it easier to install, uninstall, and switch between different versions. Visit it’s Github page to follow the latest installation instructions.

Yarn

Yarn package manager is available since Fedora 29. You can install it by running:

$ sudo dnf install yarnpkg 

Yarn can be used in the following manner:

$ yarnpkg add request $ yarn add request 

Installing npm modules

Installing Node.js modules is covered in Node.js modules.

Installing Global Modules

Create a directory for global installations inside your home directory:

mkdir ~/.npm-global 

Set the new directory path for npm:

npm config set prefix '~/.npm-global' 

Open/create the ~/.profile file and add the following line:

export PATH=~/.npm-global/bin:$PATH 

Update your system variables with this command:

source ~/.profile 

Download TypeScript

TypeScript can be installed through three installation routes depending on how you intend to use it: an npm module, a NuGet package or a Visual Studio Extension.

If you are using Node.js, you want the npm version. If you are using MSBuild in your project, you want the NuGet package or Visual Studio extension.

TypeScript in Your Project

Having TypeScript set up on a per-project basis lets you have many projects with many different versions of TypeScript, this keeps each project working consistently.

via npm

TypeScript is available as a package on the npm registry available as «typescript» .

You will need a copy of Node.js as an environment to run the package. Then you use a dependency manager like npm, yarn or pnpm to download TypeScript into your project.

npm install typescript —save-dev

All of these dependency managers support lockfiles, ensuring that everyone on your team is using the same version of the language. You can then run the TypeScript compiler using one of the following commands:

with Visual Studio

For most project types, you can get TypeScript as a package in Nuget for your MSBuild projects, for example an ASP.NET Core app.

  • The Manage NuGet Packages window (which you can get to by right-clicking on a project node)
  • The Nuget Package Manager Console (found in Tools > NuGet Package Manager > Package Manager Console) and then running:
    Install-Package Microsoft.TypeScript.MSBuild

For project types which don’t support Nuget, you can use the TypeScript Visual Studio extension. You can install the extension using Extensions > Manage Extensions in Visual Studio.

The examples below are for more advanced use cases.

Globally Installing TypeScript

It can be handy to have TypeScript available across all projects, often to test one-off ideas. Long-term, codebases should prefer a project-wide installation over a global install so that they can benefit from reproducible builds across different machines.

via npm

You can use npm to install TypeScript globally, this means that you can use the tsc command anywhere in your terminal.

To do this, run npm install -g typescript . This will install the latest version (currently 5.2 ).

via Visual Studio Marketplace

You can install TypeScript as a Visual Studio extension, which will allow you to use TypeScript across many MSBuild projects in Visual Studio.

Working with TypeScript-compatible transpilers

There are other tools which convert TypeScript files to JavaScript files. You might use these tools for speed or consistency with your existing build tooling.

Each of these projects handle the file conversion, but do not handle the type-checking aspects of the TypeScript compiler. So it’s likely that you will still need to keep the above TypeScript dependency around, and you will want to enable isolatedModules .

Babel

Babel is a very popular JavaScript transpiler which supports TypeScript files via the plugin @babel/plugin-transform-typescript.

swc

swc is a fast transpiler created in Rust which supports many of Babel’s features including TypeScript.

Sucrase

Sucrase is a Babel fork focused on speed for using in development mode. Sucrase supports TypeScript natively.

Next Steps

Get Started
  • JS to TS
  • New to Programming
  • OOP to JS
  • Functional to JS
  • Installation

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *