Настроить intellij idea для javascript

Node.js

Node.js is a lightweight runtime environment for executing JavaScript outside the browser, for example on the server or in the command line. IntelliJ IDEA integrates with Node.js providing assistance in configuring, editing, running, debugging, testing, profiling, and maintaining your applications.

If you need Node.js only as a local runtime for your application or for managing npm packages, running JavaScript linters, build tools, test frameworks, and so on, just install Node.js. If you follow the standard installation procedure, in most cases IntelliJ IDEA detects Node.js itself.

And even if you have no Node.js on your computer, you can install it when creating a new Node.js application in the Create New Project dialog , see Creating a new Node.js application below.

Читайте также:  Hdmi cec lg телевизор как настроить

If you want to switch among several Node.js installations, they must be configured as local Node.js interpreters. In most cases, IntelliJ IDEA detects Node.js installations, configures them as interpreters automatically, and adds them to the list where you can select the relevant one.

To run a Node.js application remotely, configure it as a remote interpreter. See Node.js with Docker for details.

Switching between Node.js versions

With IntelliJ IDEA, you can have several installations of Node.js and switch between them while working on the same project.

    Press Ctrl+Alt+S to open the IDE settings and select Languages and Frameworks | Node.js and NPM .

On the Node.js and NPM page that opens, select the required Node.js installation from the Node Interpreter list.

If you followed the standard installation procedure, in most cases the required Node.js installation is on the list. If the installation is missing, click and configure it as a local interpreter manually.

Using a system Node.js version

With IntelliJ IDEA, you can set the default system node alias as your project’s Node.js version. After that this version will be automatically used by all the tools that require Node.js and in all new run/debug configurations. In particular, this means that you will not have to update the settings for each tool if you install a new Node.js version and make it the default node alias in your system.

This functionality is especially helpful when you are using nvm.

    Press Ctrl+Alt+S to open the IDE settings and select Languages and Frameworks | Node.js and NPM .

From the Node interpreter list, select node .

Specify this new Node.js interpreter where applicable, for example in your run/debug configurations or settings of specific tools.

Configuring a local Node.js interpreter

You may need to configure Node.js installation as an interpreter manually, for example, if Node.js is installed in a non-default location so IntelliJ IDEA does not detect it automatically.

    Press Ctrl+Alt+S to open the IDE settings and select Languages and Frameworks | Node.js and NPM .

Click next to the Node Interpreter list.

In the Node.js Interpreters dialog that opens with a list of all the currently configured interpreters, click on the toolbar. In the dialog that opens, choose Add Local from the context menu and choose the installation of Node.js, then click OK . You return to the Node.js Interpreters dialog where the Node interpreter read-only field shows the path to the new interpreter.

In the Package manager field, choose the package manager (npm, Yarn, or pnpm) for the current project.

When you click OK , you return to the Node.js and NPM page where the Node interpreter field shows the new interpreter.

Using Node.js on Windows Subsystem for Linux

IntelliJ IDEA lets you run and debug Node.js applications using Node.js on Windows Subsystem for Linux. You can choose Node.js on WSL as the default interpreter for the current project or you can configure and use this node version in a Node.js Run/Debug configuration.

Configure Node.js on WSL as the default project node interpreter

In the Settings/Preferences dialog Ctrl+Alt+S , go to Languages and Frameworks | Node.js and NPM .

Click next to the Node Interpreter field, in the Node.js Interpreters dialog that opens, click , and then select Add WSL from the list.

In the Add WSL Node Interpreter dialog that opens, select the Linux distribution you’re using and specify the path to Node.js.

Creating a Node.js application

If you have no application yet, you can generate a IntelliJ IDEA project with Node.js-specific structure from a template or create an empty IntelliJ IDEA project and configure Node.js in it as described in Starting with an existing Node.js application below.

You can also create a module from an existing Node.js application.

Create a new Node.js application

Select File | New | Project from the main menu or click the New Project button on the Welcome screen.

In the New Project dialog, select JavaScript in the left-hand pane.

In the right-hand pane, choose Express and click Next .

On the second page of the wizard, specify the project folder, the Node.js interpreter, and the package manager (npm or Yarn, see npm, pnpm, and Yarn for details).

For Express applications, specify the express -generator in the express-generator field.

It is recommended that you use npx that downloads and runs the generator. To do that, select npx —package express-generator express from the express -generator list.

Alternatively, open the embedded Terminal ( Alt+F12 ) and type npm install —g express-generator and then select the downloaded generator from the express-generator list.

Select the template language and the Style Sheet language to use.

When you click Finish, IntelliJ IDEA downloads the necessary dependencies and enables code completion for them as well as for the Node.js core APIs, see Configuring node_modules library and Configuring Node.js Core library for details.

For Express , IntelliJ IDEA creates a run/debug configuration of the type Node.js with default settings and generates a basic Express-specific directory structure.

For Node.js , IntelliJ IDEA just runs the npm init command to generate a package.json file.

Create an empty IntelliJ IDEA project

Select File | New | Project from the main menu or click the New Project button on the Welcome screen.

In the New Project dialog, select JavaScript in the left-hand pane.

In the right-hand pane, again select JavaScript and click Next .

On the second page of the wizard, specify the project folder and name and click Finish .

Create a module from an existing Node.js app

Download your application sources and store them on your computer.

From the main menu, select File | New | Module from Existing Sources .

In the dialog that opens, select the location of your application sources.

Learn more from Modules.

Starting with an existing Node.js application

If you are going to continue developing an existing Node.js application, open it in IntelliJ IDEA, configure Node.js in it, and download the required 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

Click Get from VCS on the Welcome screen. Alternatively, select File | Project from Version Control or | Get from Version Control from the main menu.

stands for the Version Control System with which your currently opened project is associated.

In the dialog that opens, select your version control system from the list and specify the repository to check out the application sources from. See Check out a project (clone) for details.

Configure Node.js in a project

In the Settings/Preferences dialog Ctrl+Alt+S , go to Languages and Frameworks | Node.js and NPM .

In the Node Interpreter field, specify the default Node.js interpreter for the current project. IntelliJ IDEA will automatically use it every time you select the Project alias from Node Interpreter lists when creating run/debug configurations or configuring Node.js-dependent tools, for example, Prettier or ESLint.

Select a configured interpreter from the list or click and configure a new one in the dialog that opens as described in Configuring a local Node.js interpreter. If you select node , the system Node.js version is used.

Select the Coding assistance for Node.js checkbox to configure the Node.js Core module sources as a JavaScript library and associate it with your project. As a result, IntelliJ IDEA provides code completion, reference resolution, validation, and debugging capabilities for fs , path , http , and other parts of Node.js that are compiled into the Node.js binary.

When the configuration is completed, IntelliJ IDEA displays information about the currently configured version.

If you need code completion for Node.js APIs only in some parts of your project, you can configure that using the Manage scopes link. In the Usage dialog that opens, click the relevant directories and for each of them select the configured Node.js Core library from the list. Learn more from Configuring the scope of a library.

Download the project dependencies

In the embedded Terminal ( Alt+F12 ), type:

Источник

Configuring JavaScript debugger

Debugging of JavaScript code is only supported in Google Chrome and in other Chromium-based browsers.

Debugging JavaScript in IntelliJ IDEA is supported through the JavaScript Debugger plugin. The JavaScript Debugger plugin is bundled with IntelliJ IDEA and activated by default. If the plugin is disabled, enable it on the Installed tab of the Settings/Preferences | Plugins page, as described in Managing plugins.

To ensure successful debugging, it is enough to specify the built-in web server port and accept the default settings that IntelliJ IDEA suggests for other debugger options.

Before you start

Make sure the JavaScript Debugger plugin is enabled on the Settings/Preferences | Plugins page, tab Installed , see Managing plugins for details.

Set the built-in web server port

    Press Ctrl+Alt+S to open the IDE settings and select Build, Execution, Deployment | Debugger .

In the Built-in server area, specify the port where the built-in web server runs. By default this port is set to the default IntelliJ IDEA port 63342 through which IntelliJ IDEA accepts connections from services. You can set the port number to any other value starting from 1024.

Optionally

Suppress calls to the files on the built-in server from other computers or from outside IntelliJ IDEA by clearing the Can accept external connections or Allow unsigned requests checkbox respectively.

Choose the way to remove breakpoints, the default setting is Click .

On the settings page under the Debugger node, configure advanced debugger options: enable or disable Inline Debugging, specify when you want to see tooltips with object values and expressions evaluation results, and so on.

Whether you want object node properties to be shown. If so, specify the properties. Use and to manage the list of properties.

Starting a debugging session with your default Chrome user data

You may notice that your debugging session starts in a new window with a custom Chrome user data instead of your default one. As a result, the window looks unusual, for example, your bookmarks, the browser history, and the extensions are missing, which altogether breaks your development experience. That happens because IntelliJ IDEA uses Chrome Debugging Protocol and runs Chrome with the —remote-debugging-port option. However, if Chrome is already started, a debugging port can’t be opened for any new or existing Chrome instance that has the same user data. Therefore, when Chrome Debugging Protocol is used, IntelliJ IDEA always starts a debugging session with in a new window with a custom user data.

To open a new Chrome instance with your familiar look-and-feel, configure Chrome in IntelliJ IDEA to start with your user data. In this case, before starting a debugging session, always make sure that Chrome is not already running with your user data. Otherwise IntelliJ IDEA still launches another instance of Chrome with your user data but is unable to open a debugging port for it. As a result, IntelliJ IDEA debugger fails to connect to the application in the new Chrome instance and the debugging session does not start.

Configure Chrome in IntelliJ IDEA to start with your Chrome user data

Save your Chrome user data anywhere on your machine.

To create a new Chrome configuration, click . A new item appears in the list. In the Path field, specify the path to the Chrome installation folder.

Select the new configuration and click . The Chrome Settings dialog opens.

Select the Use custom user data directory checkbox and specify the path to your user data directory in the IntelliJ IDEA settings.

Mark your Chrome browser configuration default as described in Web Browsers, and don’t forget to choose Default from the Browser list when creating a run/debug configuration.

Alternatively, always choose this Chrome browser configuration from the Browser list.

Источник

Установка и настройка IntelliJ IDEA

Если вы только делаете свои первые шаги в мире IT – вот краткое руководство IntelliJ IDEA, как установить и создать свой первый проект. Рекомендуем также посмотреть мастер-класс по созданию сетевого чата в среде IntelliJ IDEA.

Установка

Существует две версии IntelliJ IDEA – Community и Unlimited. Первая – бесплатная, но ограниченная. В ней не поддерживаются фреймворки Spring, Vaadin, GWT, языки JavaScript и TypeScript, SQL и многое другое. Вторая включает в себя всевозможные фичи для коллективной разработки, но бесплатна будет только 30 дней пробного периода. Потом вам придётся заплатить минимум 533 доллара США.

Нам с головой хватит возможностей бесплатной версии, соответственно, ориентируемся на установочный файл с именем idealC.

Для установки в ОС Windows нам потребуется скачать с официального сайта исходник с расширением exe. Далее запускаем его и следуем инструкциям установщика.

В MacOS — двойной щелчок на файле ideaIC.dmg, монтируем архив и копируем исходники в папку Applications.

Для Linux необходимо распаковать ideaIC.gz в директорию, которая поддерживает выполнение файлов. Для иерархии формата FHS это /opt. После этого перейдите в подкаталог /bin и запустите файл idea.sh.

Теперь давайте разберёмся, как настроить IntelliJ IDEA.

Предварительная настройка

При первом запуске IntelliJ IDEA перед вами выскочит диалоговое окно с требованием указать путь до файла с настройками. Так как это наш первый опыт знакомства с IDE, то выбираем пункт «Do not import settings». Если данное окно вылезло после обновления или переустановки – выберите исходную директорию.

Следующим шагом настройки intellij idea будет выбор темы. ПО умолчанию их две – стандартная (светлая) и Darcula (тёмная).

Как уже было написано выше, IDEA поддерживает огромное количество вспомогательных инструментов. Разумеется, новичку они все не нужны. Поэтому следующим шагом будет их отключение для увеличения производительности. Для этого в очередном диалоговом окне выбираем «Disable All». Не переживайте, их можно подключить позднее в меню настроек.

Впрочем, среда программирования IntelliJ IDEA на этом и не думает успокаиваться, предлагая скачать дополнительные надстройки. Спасибо, нас это тоже не интересует!

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

С этим действием у вас вряд ли возникнут трудности, ведь новое диалоговое окно предлагает лишь 4 варианта: создать новый проект (Create New Project), открыть существующий (Open), импортировать проект (Import Project) или выйти из системы контроля версий (Check out from Version Control). Выбираем первый пункт. Подробнее о том, как создать проект IntelliJ IDEA, что делать уже внутри среды, лучше почитать на официальном сайте, потому что возможностей для кастомизации рабочего пространства здесь действительно много.

Проблемы и вопросы

Далее у вас наверняка возникнет несколько вопросов, один из которых касается активации IntelliJ IDEA. Ограниченная версия или 30-дневная триал-версия не требуют регистрации и дополнительных манипуляций. Но если вы хотите активировать купленную, необходимо выполнить следующие действия:

  • На приветственном экране, откуда мы создаём проект, найти в нижней части меню Configure->Manage License. Если вы уже находитесь внутри, тогда на верхней панели Help->Register.
  • Перед вами 3 возможных способа активации: через аккаунт (JetBrains account), с помощью кода (Activation Code), через сервер лицензий (License Server). В зависимости от того, каким образом вы или ваш работодатель приобретали лицензию и какими данными располагаете, выберите нужный пункт.
  • Вводим необходимые данные, нажимаем кнопку «Activate» и наслаждаемся безграничной работой.

Следующий традиционный вопрос касается обновления IDE. Здесь алгоритм такой же, как при установке: скачать-запустить-следовать инструкциям или удалить-установить заново-сослаться_на_существующий_файл_настроек в самом первом диалоговом окне.

И конечно ни один форум не обходится без вопроса: «Не запускается, что делать?». Ответ традиционный — ещё раз внимательно читаем, как установить IntelliJ IDEA. Если все сделано правильно — программа гарантированно запустится. Если же неполадки возникают непосредственно при работе IDEA, скорее всего, дело в неправильно установленных плагинах, ответы ищите на официальных сайтах их разработчиков.

На всякий случай вот ещё инструкция, как удалить IntelliJ IDEA:

  1. стандартным способом через панель управления в Windows. При желании добить остатки в реестре по пути: “HKEY_CLASSES_ROOT\IntelliJIDEAProjectFile”;
  2. в Linux потереть файлы вручную, а также удалить директории настроек “config” и “system”, если они лежат не в корне.
  3. В MacOS стандартно удалить через иконку программы и почистить кэш по направлению “settings/caches/plugins/logs”.

Перед тем, как вы решите с головой погрузиться в мир новой IDE, помните, что это сложный продукт с резкой кривой обучаемости. Поэтому правильным выбором для обучения будут курсы по Java с практическими уроками IntelliJ IDEA. Так вы и в профессию быстрее втянетесь, и мощным инструментом овладеете.

IntelliJ IDEA – одна из самых мощных универсальных сред разработки. Она поддерживает такие языки, как PHP, JavaScript, Sass, Ruby, Python и конечно же Java. Добавьте сюда поддержку популярных фреймворков и движков, тестов для кода, адаптацию под мобильные устройства, интеграцию с Git и Mercurial, инструменты для работы с серверами – и вы поймёте, что с IntelliJ IDEA программирование проще и продуктивнее.

Если вы только делаете свои первые шаги в мире IT – вот краткое руководство IntelliJ IDEA, как установить и создать свой первый проект. Рекомендуем также посмотреть мастер-класс по созданию сетевого чата в среде IntelliJ IDEA.

Установка

Существует две версии IntelliJ IDEA – Community и Unlimited. Первая – бесплатная, но ограниченная. В ней не поддерживаются фреймворки Spring, Vaadin, GWT, языки JavaScript и TypeScript, SQL и многое другое. Вторая включает в себя всевозможные фичи для коллективной разработки, но бесплатна будет только 30 дней пробного периода. Потом вам придётся заплатить минимум 533 доллара США.

Нам с головой хватит возможностей бесплатной версии, соответственно, ориентируемся на установочный файл с именем idealC.

Для установки в ОС Windows нам потребуется скачать с официального сайта исходник с расширением exe. Далее запускаем его и следуем инструкциям установщика.

В MacOS — двойной щелчок на файле ideaIC.dmg, монтируем архив и копируем исходники в папку Applications.

Для Linux необходимо распаковать ideaIC.gz в директорию, которая поддерживает выполнение файлов. Для иерархии формата FHS это /opt. После этого перейдите в подкаталог /bin и запустите файл idea.sh.

Теперь давайте разберёмся, как настроить IntelliJ IDEA.

Предварительная настройка

При первом запуске IntelliJ IDEA перед вами выскочит диалоговое окно с требованием указать путь до файла с настройками. Так как это наш первый опыт знакомства с IDE, то выбираем пункт «Do not import settings». Если данное окно вылезло после обновления или переустановки – выберите исходную директорию.

Следующим шагом настройки intellij idea будет выбор темы. ПО умолчанию их две – стандартная (светлая) и Darcula (тёмная).

Как уже было написано выше, IDEA поддерживает огромное количество вспомогательных инструментов. Разумеется, новичку они все не нужны. Поэтому следующим шагом будет их отключение для увеличения производительности. Для этого в очередном диалоговом окне выбираем «Disable All». Не переживайте, их можно подключить позднее в меню настроек.

Впрочем, среда программирования IntelliJ IDEA на этом и не думает успокаиваться, предлагая скачать дополнительные надстройки. Спасибо, нас это тоже не интересует!

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

С этим действием у вас вряд ли возникнут трудности, ведь новое диалоговое окно предлагает лишь 4 варианта: создать новый проект (Create New Project), открыть существующий (Open), импортировать проект (Import Project) или выйти из системы контроля версий (Check out from Version Control). Выбираем первый пункт. Подробнее о том, как создать проект IntelliJ IDEA, что делать уже внутри среды, лучше почитать на официальном сайте, потому что возможностей для кастомизации рабочего пространства здесь действительно много.

Проблемы и вопросы

Далее у вас наверняка возникнет несколько вопросов, один из которых касается активации IntelliJ IDEA. Ограниченная версия или 30-дневная триал-версия не требуют регистрации и дополнительных манипуляций. Но если вы хотите активировать купленную, необходимо выполнить следующие действия:

  • На приветственном экране, откуда мы создаём проект, найти в нижней части меню Configure->Manage License. Если вы уже находитесь внутри, тогда на верхней панели Help->Register.
  • Перед вами 3 возможных способа активации: через аккаунт (JetBrains account), с помощью кода (Activation Code), через сервер лицензий (License Server). В зависимости от того, каким образом вы или ваш работодатель приобретали лицензию и какими данными располагаете, выберите нужный пункт.
  • Вводим необходимые данные, нажимаем кнопку «Activate» и наслаждаемся безграничной работой.

Следующий традиционный вопрос касается обновления IDE. Здесь алгоритм такой же, как при установке: скачать-запустить-следовать инструкциям или удалить-установить заново-сослаться_на_существующий_файл_настроек в самом первом диалоговом окне.

И конечно ни один форум не обходится без вопроса: «Не запускается, что делать?». Ответ традиционный — ещё раз внимательно читаем, как установить IntelliJ IDEA. Если все сделано правильно — программа гарантированно запустится. Если же неполадки возникают непосредственно при работе IDEA, скорее всего, дело в неправильно установленных плагинах, ответы ищите на официальных сайтах их разработчиков.

На всякий случай вот ещё инструкция, как удалить IntelliJ IDEA:

  1. стандартным способом через панель управления в Windows. При желании добить остатки в реестре по пути: “HKEY_CLASSES_ROOT\IntelliJIDEAProjectFile”;
  2. в Linux потереть файлы вручную, а также удалить директории настроек “config” и “system”, если они лежат не в корне.
  3. В MacOS стандартно удалить через иконку программы и почистить кэш по направлению “settings/caches/plugins/logs”.

Перед тем, как вы решите с головой погрузиться в мир новой IDE, помните, что это сложный продукт с резкой кривой обучаемости. Поэтому правильным выбором для обучения будут курсы по Java с практическими уроками IntelliJ IDEA. Так вы и в профессию быстрее втянетесь, и мощным инструментом овладеете.

Источник

Оцените статью