Intellij – React Debugger

https://subscription.packtpub.com/book/application_development/9781784396930/8/ch08lvl1sec46/setting-up-the-javascript-debugger

IntellJ Basic Overview DebugginsIntellJ Debug BreakdownDebug JS in Chrome with IntelljChrome Extension

https://www.jetbrains.com/help/idea/debugging-code.html

Debugger Essentials covers basic topics like line breakpoints, stepping, controlling the debug session, watches, expression evaluation, and breakpoint conditions.

Debugger Advanced covers breakpoint types and settings, advanced stepping, remote debug, rendererers, and more.




Debug code

Last modified: 20 August 2021

IntelliJ IDEA provides a debugger for Java code. Depending on the installed/enabled plugins, you can also debug code written in other languages.

During a debugging session, you launch your program with the debugger attached to it. The purpose of the debugger is to interfere with the program execution and provide you with the information on what’s happening under the hood. This facilitates the process of detecting and fixing bugs in your program.

 

There is a variety of ways how you can run a debugging session, however, for simplicity this documentation assumes that you are building and running your project from IntelliJ IDEA. This is the most common case, and it has fewer limitations as compared to more advanced techniques. The procedures for attaching to a process and debugging a remote application are covered in separate sections.

Before debugging
  1. Make sure the Generate debugging info option is turned on (the default setting) in Settings/Preferences | Build, Execution, Deployment | Compiler | Java Compiler.

    This setting is not absolutely required for debugging, however we recommend leaving it enabled. Disabling it allows you to save disk space at the cost of some debugger functionality.

  2. Configure common debugging properties and behavior in Settings/Preferences | Build, Execution, Deployment | Debugger.

    If you are new to debugging, the out-of-the-box configuration will work for you. The topics about each debugger functionality provide references and explain the related settings where applicable. If you are an advanced user and looking for some particular property, see the Debugger reference section.

  3. Define a run/debug configuration if you are going to use a custom one. This is required if you need some arguments to be passed to the program or some special activity to be performed before launch. For more information on how to set up run/debug configurations, refer to the Run/debug configurations section. Most of the time, you don't need this to debug a simple program that doesn't expect arguments or have any special requirements.

General debugging procedure

There is no one-size-fits-all procedure for debugging applications. Depending on actual requirements you may have to use different actions in different order. This topic provides general guidelines, which represent typical debugging steps. The details on how and when to use particular features are provided in the respective topics.

  1. Define where the program needs to be stopped. This is done using breakpoints. Breakpoints are special markers, which represent places and/or conditions when the debugger needs to step in and freeze the program state. A program, which has been frozen by the debugger is referred to as suspended.

    The alternative to using breakpoints is manually suspending the program at an arbitrary moment, however this method imposes some limitations on the debugger functionality and doesn't allow for much precision as to when to suspend the program.

  2. Run your program in debug mode.

    Just like with regular running of the program, you can run multiple debugging sessions at the same time.

  3. After the program has been suspended, use the debugger to get the information about the state of the program and how it changes during running.

    The debugger provides you with the information about variable values, the current state of the threads, breakdown of objects that are currently in the heap, and so on. It also allows you to test your program in various conditions by throwing exceptions (for example, to check how they are handled) or running arbitrary code right in the middle of the program execution.

    While these tools let you examine the program state at a particular instant, the stepping feature gives you the control over step-by-step execution of the program. By combining the tools you can deduce where the bug is coming from and test your program for robustness.

  4. When you have determined what needs to be fixed, you can do it without terminating the session. For this purpose, IntelliJ IDEA provides a functionality allowing you to adjust and reload pieces of your code on the fly. This approach is covered in the Reload modified classes topic.

 

If you are new to debugging, we recommend that you complete the Debugging Your First Java Application tutorial.

Debugger refreshers

If you are already familiar with IntelliJ IDEA debugger and want to get an overview of various useful features and approaches, take a look at Debugger Refresher video series.

Debugger Essentials covers basic topics like line breakpoints, stepping, controlling the debug session, watches, expression evaluation, and breakpoint conditions.

 

Debugger Advanced covers breakpoint types and settings, advanced stepping, remote debug, rendererers, and more.

 

https://www.jetbrains.com/help/idea/react.html

ReactUltimate

Last modified: 02 August 2021

Required plugins: Javascript and TypeScript, JavaScript Debugger

The plugins are available only in IntelliJ IDEA Ultimate, where they are enabled by default.

React is a JavaScript library for building complex interactive User Interfaces from encapsulated components. Learn more about the library from the React official website.

IntelliJ IDEA integrates with React providing assistance in configuring, editing, linting, running, debugging, and maintaining your applications.

Before you start
  1. Make sure you have Node.js on your computer.
  2. Make sure the JavaScript and TypeScript plugin is enabled on the Settings/Preferences | Plugins page, tab Installed, see Managing plugins for details.
Create a new React application

The recommended way to start building a new React single page application is create-react-app package, which IntelliJ IDEA downloads and runs for you using npx. As a result, your development environment is preconfigured to use webpack, Babel, ESLint, and other tools.

Of course, you can still download Create React App yourself or create an empty IntelliJ IDEA project and install React in it.

 

Learn more about installing React and creating React applications from the React official website.

Generate a React application with create-react-app
  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 JavaScript in the left-hand pane.

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

  4. On the second page of the wizard, specify the project name and the folder to create it in.

    In the Node Interpreter field, specify the Node.js interpreter to use. Select a configured interpreter from the list or choose Add to configure a new one.

     

    From the create-react-app list, select npx create-react-app.

    Alternatively, for npm version 5.1 and earlier, install the create-react-app package yourself by running npm install --g create-react-app in the Terminal ⌥F12. When creating an application, select the folder where the create-react-app package is stored.

     

  5. Optionally: To use TSX instead of JSX, select the Create TypeScript project checkbox. IntelliJ IDEA will generate .tsx files for your application and a tsconfig.json configuration file.

  6. When you click Finish, IntelliJ IDEA generates a React -specific project with all the required configuration files and downloads the required dependencies. IntelliJ IDEA also creates an npm start and JavaScript Debug configurations with default settings for running or debugging your application.

 

Alternatively, open the built-in Terminal and type:

  1. npx create-react-app <application-name> to create an application.
  2. cd <application-name> to switch to the application folder.
  3. npm start to start the Node.js server.
Install React in an empty IntelliJ IDEA project

In this case, you will have to configure the build pipeline yourself as described in Building a React application below. Learn more about adding React to a project from the React official website.

Create an empty IntelliJ IDEA project
  1.  

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

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

  4.  

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

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

Install React in an empty project
  1. Open the empty project where you will use React.

  2. In the embedded Terminal (⌥F12), type:

    npm install --save react react-dom

    You can also install the packages on the Node.js and NPM page as described in npm, pnpm, and Yarn.

Start with an existing React application

To continue developing an existing React application, open it in IntelliJ IDEA 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
  1. Click Get from VCS on the Welcome screen. Alternatively, select File | Project from Version Control or <Your_VCS> | Get from Version Control from the main menu.

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

  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. See Check out a project (clone) for details.

Download the dependencies
Project security

When you open a JavaScript file with import statements in a React project with webpack, IntelliJ IDEA executes the webpack configuration file, which may contain some potentially malicious code. To avoid problems, IntelliJ IDEA displays a warning and lets you decide on how to proceed.

Untrusted project warning

If you click Skip, IntelliJ IDEA disables analysis of the webpack configuration in the current project. As a result, IntelliJ IDEA might not resolve some of the imports in the project or add imports that don't use resolution rules configured in the webpack configuration.

Learn more from Webpack and Project security.

 

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

Code completion

IntelliJ IDEA provides code completion for React APIs and JSX in JavaScript code. Code completion works for React methods, React-specific attributes, HTML tags and component names, React events, component properties, and so on. Learn more from the React official website.

To get code completion for React methods and React-specific attributes, you need to have the react.js library file somewhere in your project. Usually the library is already in your node_modules folder.

Complete React methods, attributes, and events

By default, the code completion popup is displayed automatically as you type. For example:

Completion popup

In JSX tags, IntelliJ IDEA provides coding assistance for React-specific attributes, such as className or classID, and non-DOM attributes, such as key or ref. Moreover, auto-completion also works for names of classes defined in the project’s CSS files:

Completion for CSS class names

All React events, such as onClick or onChange, can also be completed automatically together with curly braces ={} or quotes "".

https://resources.jetbrains.com/help/img/idea/2021.2/ws_react_events_light.png

Gif

By default, curly braces are inserted. You can have IntelliJ IDEA always add quotes or choose between quotes or braces based on the type from a TypeScript definition file (d.ts) file. To change the default setting, open the Settings/Preferences dialog ⌘,, go to Editor | Code Style | HTML and select the applicable option from the Add for JSX attributes list.

Completion also works for JavaScript expressions inside curly braces. This applies to all the methods and functions that you have defined:

Completing JavaScript expressions inside curly braces

Complete HTML tags and component names

IntelliJ IDEA provides code completion for HTML tags and component names that you have defined inside methods in JavaScript or inside other components:

Completion for HTML tags and component names

Completion also works for imported components with ES6 style syntax:

Completion for imported components with ES6 syntax

Complete component properties

IntelliJ IDEA provides code completion for component properties defined using propTypes and resolves them so you can quickly jump or preview their definitions:

https://resources.jetbrains.com/help/img/idea/2021.2/ws_react_component_properties_light.png

Gif

When you autocomplete the name of a component, IntelliJ IDEA adds all its required properties automatically. If some of the required properties are missing in the usage of a component, IntelliJ IDEA warns you about that.

Transfer HTML attributes to JSX

When you copy a piece of HTML code with class attributes or on-event handlers and paste it into JSX, IntelliJ IDEA automatically replaces these attributes with React-specific ones (className, onClick, onChange, and so on.)

https://resources.jetbrains.com/help/img/idea/2021.2/ws_paste_from_html_to_jsx_light.png

Gif

This also works for TSX:

https://resources.jetbrains.com/help/img/idea/2021.2/ws_paste_from_html_to_tsx_light.png

Gif

To copy HTML code to JSX or TSX "as is", use Paste Simple ⌥⇧⌘V or open the Settings/Preferences dialog ⌘,, go to Editor | General | Smart Keys | JavaScript, and clear the Convert attributes when pasting HTML to JSX files checkbox.

React code snippets

IntelliJ IDEA comes with a collection of more than 50 code snippets that expand into different statements and blocks of code often used in React apps. The example below shows how you can use the rcjc abbreviation to create a class that defines a new React component:

https://resources.jetbrains.com/help/img/idea/2021.2/ws_react_live_template_light.png

Gif

Create a React code construct from a snippet
  • Type the required abbreviation in the editor and press ⇥.
  • Press ⌘J and choose the relevant snippet. To narrow down the search, start typing the abbreviation and then select it from the completion list.

See Live Templates for details.

View the list of all available React snippets
  • In the Settings/Preferences dialog ⌘,, click Live Templates under Editor, and then expand the React node.
Emmet in JSX

With IntelliJ IDEA, you can use Emmet not only in HTML but also in your JSX code taking advantage of some special React twists. For example, the abbreviation div.my-class expands in JSX to <div className=”my-class"></div> but not to <div class=”my-class"></div> as it would in HTML:

https://resources.jetbrains.com/help/img/idea/2021.2/ws_react_emmet_light.png

Gif

Besides the basic navigation, IntelliJ IDEA helps you jump between React-specific code elements.

  • To jump to the declaration of a method or a JavaScript expression inside curly braces {}, select the method or expression and press ⌘B.

    To jump to the declaration of a component, select the component name and press ⌘B.

     

    Alternatively, use ⌘+Click: keeping ⌘ pressed, hover your mouse pointer over the symbol. When the symbol turns into a hyperlink, its declaration will be displayed in the tooltip. Click the hyperlink without releasing the key to open the declaration in the editor. Learn more from Go to declaration and its type.

  • To view component definition, press ⌥Space.

    View quick definition of a component in a popup

    View quick definition of a component in a popup

  • To view quick documentation for a component, press F1. Learn more from JavaScript documentation look-up.

    Quick documentation popup for React component

  • IntelliJ IDEA lets you easily navigate through JSX tags using breadcrumbs and colorful highlighting for the tag tree in the editor gutter. See Navigating with breadcrumbs for details.

    Highlighting and breadcrumbs for JSX tags in a React application

Lint a React application

All the IntelliJ IDEA built-in code inspections for JavaScript and HTML also work in JSX code. IntelliJ IDEA alerts you in case of unused variables and functions, missing closing tags, missing statements, and much more.

JavaSxript inspections in React application

For some inspections IntelliJ IDEA provides quick-fixes, for example, suggests adding a missing method. To view the quick-fix popup, press ⌥⏎.

To customize the list of inspections, open the Settings/Preferences dialog ⌘,, go to Editor | Inspections, and disable the inspections you don’t want to see or change their severity levels. Learn more from Disable and suppress inspections and Change inspection severity.

ESLint

Besides providing built-in code inspections, IntelliJ IDEA also integrates with linters, such as ESLint, for JSX code. ESLint brings a wide range of linting rules that can also be extended with plugins. IntelliJ IDEA shows warnings and errors reported by ESLint right in the editor, as you type. With ESLint, you can also use JavaScript Standard Style as well as lint your TypeScript code.

See ESLint for details.

To have ESLint properly understand React JSX syntax, you need eslint-plugin-react. With this plugin, you are warned, for example, when the display name is not set for a React component, or when some dangerous JSX properties are used:

ESLint with React: errors and warnings are highlighted, the description of a problem is shown in a tooltip.

 

If you created your application with create-react-app, your development environment is already preconfigured to use ESLint.

Install and configure ESLint in a React project
  1. In the built-in Terminal (View | Tool Windows | Terminal), type:

    npm install --save-dev eslint
    
    npm install --save-dev eslint-plugin-react
    
  2. Add a ESLint configuration file .eslintrc.* to your project. This can be a .eslintrc, .eslintrc.json, or .eslintrc.yaml file, or a file in another supported format, see the ESLint official website for details.

  3. In the Settings/Preferences dialog ⌘,, go to Languages and Frameworks | JavaScript | Code Quality Tools | ESLint, and select Automatic ESLint configuration. IntelliJ IDEA will automatically locate ESLint in your project node_modules folder, and then use the default configuration from .eslintrc.* file or from eslintConfig property in a package.json.

    Alternatively, select Manual ESLint configuration to use a custom ESLint package and configuration.

    See Activating and configuring ESLint in IntelliJ IDEA for details.

Example of .eslintrc structure (ESLint 1.x with react plugin)
  1. In the ecmaFeatures object, add "jsx" = true. Here you can also specify additional language features you’d like to use, for example ES6 classes, modules, and so on.

  2. In the plugins object, add react.

  3. In the rules object, you can list ESLint built-in rules that you would like to enable, as well as rules available via the react plugin.

    {
      "parser": "babel-eslint",
      "env": {
        "browser": true,
        "es6": true,
        "jest": true
      },
    
      "rules": {
        "arrow-parens": ["error", "as-needed", {
          "requireForBlockBody": true
        }],
        "react/jsx-props-no-spreading": "off",
        "react/jsx-sort-props": ["error", {
          "reservedFirst": ["key"]
        }],
        "react/require-default-props": "off",
        "react/sort-prop-types": "error",
        "react/state-in-constructor": ["error", "never"],
        "semi-spacing": "warn"
      },
      "overrides": [
        {
          "files": [
            "sample/**",
            "test/**"
          ],
          "rules": {
            "import/no-unresolved": "off"
          }
        }
      ]
    }
    

    Copied!

Learn more about ESLint and react plugin configuration from the ESLint official website.

Code refactoring in a React application

Besides the common IntelliJ IDEA refactorings, in a React application you can also run Rename for React components and use Extract Component to create new components.

Rename a component

Below is an example of renaming a component that is defined and used in only one file:

https://resources.jetbrains.com/help/img/idea/2021.2/ws_react_rename_component_light.png

Gif

In the same way, you can rename components defined in one file and then imported to another file using a named export:

https://resources.jetbrains.com/help/img/idea/2021.2/ws_react_rename_component_from_another_file_light.png

Gif

  1. Place the caret within the component name and press ⇧F6 or select Refactor | Rename from the main menu of from the context menu.
  2. Specify the new component name in compliance with React naming conventions.
Rename a state value

When you rename a state value, IntelliJ IDEA suggests renaming the corresponding setter (the function that updates this state value in a React useState hook).

https://resources.jetbrains.com/help/img/idea/2021.2/clickety-clack-site/sept2021/ws_react_rename_state.png

Gif

  1. Place the caret within the name of the state value and press ⇧F6 or select Refactor | Rename from the main menu of from the context menu.
  2. Specify the new value name and press ⏎. The focus moves to the setter where the new name of the value is suggested. Press ⏎ to accept the suggestion.
Extract a component

You can create a new React component by extracting the JSX code from the render method of an existing component. The new component can be defined as a function or as a class, see Function and Class Components on the React official website.

https://resources.jetbrains.com/help/img/idea/2021.2/ws_react_extract_functional_component_light.png

Gif

  1. Select the code you want to extract and choose Refactor | Extract Component from the context menu.

    Alternatively, go to Refactor | Extract/Introduce | Extract Component on the main menu or press ⌃T and select Extract Component from the popup.

  2. In the dialog that opens, specify the name of the new component and its type. By default, a functional component is created. If you want to define the new component as a class, select Class.

  3. Click OK. The new component will be defined next to the existing one and used in it.

  4. Optionally: use the Move Symbol refactoring to move the new component and all the required imports to a separate file.

  5. Optionally: modify the code templates that IntelliJ IDEA uses for new components. In the Settings/Preferences dialog ⌘,, go to Editor | File and Code Templates, open the Code tab, and update the templates as necessary using the Apache Velocity template language.

Convert a function to a class component

With the Convert to Class Component refactoring, IntelliJ IDEA generates a ES6 class with the name of the function which you want to convert. This class extends React .Component and contains a render() method where the function body is moved. Learn more from the React official website.

https://resources.jetbrains.com/help/img/idea/2021.2/ws_react_convert_to_class_component_light.png

Gif

  • Place the caret anywhere inside the function to convert and select Refactor | Convert to Class Component from the main menu or from the context menu.
  • Alternatively, press ⌃T and select Convert to Class Component from the popup.
Convert a class to a functional component

With the Convert to Functional Component refactoring, IntelliJ IDEA generates a function with the name of the class which you want to convert and moves the contents of the render() method to the function body.

https://resources.jetbrains.com/help/img/idea/2021.2/ws_react_convert_to_functional_component_light.png

Gif

  • Place the caret anywhere inside the class to convert and select Refactor | Convert to Functional Component from the main menu or from the context menu.
  • Alternatively, press ⌃T and select Convert to Functional Component from the popup.
Destructuring in a React application

Destructuring lets you easily unpack values from arrays and objects into variables. This functionality has a very concise syntax that is often used when you need to pass data in your application.

When working with React class components, consider using the Introduce object/array destructuring intention action. Learn more from Destructuring in JavaScript.

https://resources.jetbrains.com/help/img/idea/2021.2/ws_js_destructuring_react_class_706_light.png

Gif

Run and debug a React application

The recommended way to start building a new React single page application is Create React App. Only in this case your development environment is preconfigured to use webpack and Babel. Otherwise, you need to configure a build pipeline first.

For applications created with Create React App as described above, IntelliJ IDEA generates two run/debug configurations with default settings:

  • An npm configuration with the default name npm start. This configuration runs the npm start command that launches the development server and starts your application in the development mode.
  • A JavaScript Debug configuration with the default name Debug Application. This configuration launches a debugging session.
Run a React application

 

Only for applications created with create-react-app.

  1. Select the npm start run configuration from the list on the toolbar and click Run next to the list.

    Alternatively, run npm start in the Terminal ⌥F12 or double-click the start task in the npm tool window (View | Tool Windows | npm).

  2. Wait till the application is compiled and the Webpack development server is ready.

    The Run tool window or the Terminal shows the URL at which your application is running, by default it is http://localhost:3000/. Click this link to view the application.

    React app is running

 

Thanks to the Webpack Hot Module Replacement, when the development server is running, your application is automatically reloaded as soon as you change any of the source files and save the updates.

Debug a React application

 

  1. Set the breakpoints in your code.

  2. Start the application in the development mode as described above and wait till the application is compiled and the development server is ready.

  3. Select the autogenerated Debug Application configuration from the list and click the Debug button next to the list.

    https://resources.jetbrains.com/help/img/idea/2021.2/ws_react_debug_start_debugger_with_debug_app_configuration_light.png

    Gif

You can start a debugging session in different ways depending on where your application is running.

Debug applications running on localhost
  1. Set the breakpoints in your code.

  2. Start the application in the development mode as described above and wait till the application is compiled and the Webpack development server is ready.

  3. The Run tool window or the Terminal shows the URL at which your application is running, by default it is http://localhost:3000/. Hold ⌘⇧ and click this URL link. IntelliJ IDEA starts a debugging session with an automatically generated Debug Application configuration of the type JavaScript Debug.

    https://resources.jetbrains.com/help/img/idea/2021.2/ws_react_start_debugging_from_run_tool_window_light.png

    Gif

Debug applications running on custom URLs
  1. Set the breakpoints in your code.
  2. Start the application in the development mode as described above and wait till the application is compiled and the Webpack development server is ready.
  3. The Run tool window or the Terminal shows the URL at which your application is running. Copy this URL address, you will later specify it in a debug configuration. To view your application, just click the link.
  4. Create a JavaScript Debug configuration. To do that, go to Run | Edit Configurations on the main menu, click the Add icon, and select JavaScript Debug from the list. In the Run/Debug Configuration: JavaScript Debug dialog, paste the saved URL in the URL field and save the configuration.
  5. To launch your newly created configuration, select it from the list of configurations and click the Debug button next to the list.

When the first breakpoint is hit, switch to the Debug tool window and proceed as usual: step through the program, stop and resume program execution, examine it when suspended, explore the call stack and variables, set watches, evaluate variables, view actual HTML DOM, and so on.

Build a React application

You need to set up the build process if you installed React in an existing IntelliJ IDEA project. Learn about various ways to configure a build pipeline for your React application from React official website.

 

If you created your application with create-react-app your development environment is already preconfigured to use Webpack and Babel.

Test a React application

You can run and debug Jest tests in React applications created with create-react-app. Before you start, make sure the react-scripts package is added to the dependencies object of your package.json.

You can run and debug Jest tests right from the editor, or from the Project tool window, or via a run/debug configuration, see Jest for details.

Run a test from the editor
  • Click the Run icon or the Rerun icon in the gutter and select Run <test_name> from the list.

    Run one test from the editor

    You can also see whether a test has passed or failed right in the editor, thanks to the

    test status

    icons

     

    and

     

    in the gutter.

Create a Jest run/debug configuration
  1. Open the Run/Debug Configuration dialog (Run | Edit Configurations on the main menu), click the Add button in the left-hand pane, and select Jest from the list. The Run/Debug Configuration: Jest dialog opens.

     

    Alternatively, select a test file in the Project tool window and select Create from the context menu.

  2. Specify the Node interpreter to use and the working directory of the application. By default, the Working directory field shows the project root folder. To change this predefined setting, specify the path to the desired folder or choose a previously used folder from the list.

  3. In the Jest package field, specify the path to the react-scripts package.

  4. In the Jest options field, type --env=jsdom.

    Testing React: Jest run configuration

Run tests
  1. Select the Jest run/debug configuration from the list on the main toolbar and click the Run icon to the right of the list.
  2. The test server starts automatically without any steps from your side. View and analyze messages from the test server in the Run tool window.
  3. Monitor test execution and analyze test results in the Test Runner tab of the Run tool window, see Explore test results for details.
Debug tests
  1. Select the Jest run/debug configuration from the list on the main toolbar and click the Debug button to the right of the list.
  2. In the Debug tool window that opens, proceed as usual: step through the tests, stop and resume test execution, examine the test when suspended, run JavaScript code snippets in the Console, and so on.
Known limitations

When you open an application during a debugging session for the first time, it may happen that some of the breakpoints in the code executed on page load are not hit. The reason is that to stop on a breakpoint in the original source code, IntelliJ IDEA needs to get the source maps from the browser. However the browser can pass these source maps only after the page has been fully loaded at least once. As a workaround, reload the page in the browser yourself.

https://www.jetbrains.com/help/idea/debugging-javascript-in-chrome.html

Debug JavaScript in ChromeUltimate

Last modified: 26 August 2021

Required plugins: Javascript and TypeScript, JavaScript Debugger

The plugins are available only in IntelliJ IDEA Ultimate, where they are enabled by default.

IntelliJ IDEA provides a built-in debugger for your client-side JavaScript code.

 

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

The instructions below walk you through the basic steps to get started with this debugger.

 

Before you start

  1. Make sure the JavaScript and TypeScript and JavaScript Debugger required plugins are enabled on the Settings/Preferences | Plugins page, tab Installed, see Managing plugins for details.

  2. Configure the built-in debugger as described in Configuring JavaScript debugger.

    To have the changes you make to your HTML, CSS, or JavaScript code immediately shown in the browser without reloading the page, activate the Live Edit functionality. See Live Edit in HTML, CSS, and JavaScript for details.

Debug an application that is running on the built-in server

IntelliJ IDEA has a built-in web server that can be used to preview and debug your application. This server is always running and does not require any manual configuration. All the project files are served on the built-in server with the root URL http://localhost:/, with respect to the project structure.

Start debugging
  1. Set the breakpoints in the JavaScript code, as required.

  2. Open the HTML file that references the JavaScript to debug or select the HTML file in the Project tool window.

  3. From the context menu of the editor or the selection, choose Debug <HTML_file_name>. IntelliJ IDEA generates a debug configuration and starts a debugging session through it. The file opens in the browser, and the Debug tool window appears.

     

    To save the automatically generated configuration for further re-use, choose Save <HTML_file_name> from the context menu after the debugging session is over.

  4. In the Debug tool window, proceed as usual: step through the program, stop and resume the program execution, examine it when suspended, view actual HTML DOM, run JavaScript code snippets in the Console, and so on..

 

By default, a debugging session starts in a new window with a custom Chrome 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, see Starting a debugging session with your default Chrome user data for details.

Example

Suppose you have a simple application that consists of an index.html file and an index.js file, where index.html references index.js. To start debugging this application using the built-in server, open index.html in the editor and choose Debug 'index.html' from the context menu:

ws_quick_start_debug_built_in_server_1.png

IntelliJ IDEA creates a run/debug configuration automatically, and a debugging session starts:

ws_quick_start_debug_built_in_server_2.png

To restart the new run/debug configuration, click the Debug button in the upper right-hand corner of the IntelliJ IDEA window or choose Run | Debug from the main menu:

ws_quick_start_debug_built_in_server_3.png

Reload the current page in browser

Besides restarting your application by clicking the Rerun button in the Debug tool window, you can also click the Reload in Browser to reload the page where you have currently navigated. This works the same way as the Reload Page functionality (⌘R) in Chrome.

The example below shows a simple application that consists of two HTML pages and a JavaScript script. The starting home.html page has a Submit button on pressing which the calculator.html page opens with the results of the Calculator.js script execution.

During a debugging session, clicking the Rerun button would reload the home.html page with the Submit button. Clicking the Reload in Browser button reloads the calculator.html page so all the previous script output is cleared and the debugger returns to line 1 in Calculator.js.

https://resources.jetbrains.com/help/img/idea/2021.2/ws_js_debug_reload_in_browser.png

Gif

Debug an application that is running on the localhost in the development mode

If your application is running in the development mode on localhost, you can start debugging it from the built-in Terminal (⌥F12), from the Run tool window, or from the Debug tool window. Just hold ⌘⇧ and click the URL at which the application is running.

https://resources.jetbrains.com/help/img/idea/2021.2/ws_js_start_debugging_from_run_tool_window_light.png

Gif

  1. Set the breakpoints in your code.
  2. Start the application in the development mode, for example, using an npm script.
  3. The Run tool window or the Terminal shows the URL at which your application is running. Hold ⌘⇧ and click this URL link. IntelliJ IDEA starts a debugging session with an automatically generated configuration of the type JavaScript Debug.

This also works for debugging Vue.js, Angular, React, and Node.js applications.

Debug an application that is running on an external web server

Often you may want to debug client-side JavaScript of an application that is running on an external development web server, for example powered by Node.js.

  1. Set the breakpoints in the JavaScript code, as required.

  2. Run the application in the development mode. Often you need to run npm start for that.

    When the development server is ready, copy the URL address at which the application is running in the browser – you will need to specify this URL address in the run/debug configuration.

  3. Create a debug configuration of the type JavaScript Debug: from the main menu, select Run | Edit Configuration, click the Add button on the toolbar and select JavaScript Debug from the list. In the Run/Debug Configuration: JavaScript Debug dialog that opens, specify the URL address at which the application is running. This URL can be copied from the address bar of your browser as described in Step 2 above. Click OK to save the configuration settings.

  4. Select the newly created configuration from the Select run/debug configuration list on the toolbar and click the Debug button next to the list. The URL address specified in the run configuration opens in the browser and the Debug tool window appears.

  5. In the Debug tool window, proceed as usual: step through the program, stop and resume the program execution, examine it when suspended, view actual HTML DOM, run JavaScript code snippets in the Console, and so on..

See Debugging React Applications and Debugging Angular Applications for examples.

Debug asynchronous code

IntelliJ IDEA supports debugging asynchronous client-side JavaScript code. IntelliJ IDEA recognizes breakpoints inside asynchronous code, stops at them, and lets you step into such code. As soon as a breakpoint inside an asynchronous function is hit or you step into asynchronous code, a new element Async call from <caller> is added in the Frames pane of the Debugger tab. IntelliJ IDEA displays a full call stack, including the caller and the entire way to the beginning of the asynchronous actions.

The image below shows an example of a JavaScript debugging session.

Debugging asynchronous JavaScript code

The debugger stops at line3(breakpoint), then at line5(breakpoint). On clicking Step into, the debugger will stop at line5 (on function), then will move to line6.

The asynchronous debugging mode is turned on by default. To disable asynchronous stack traces, set js.debugger.async.call.stack.depth in Registry to 0.

Debug workers

IntelliJ IDEA supports debugging Service Workers and Web Workers. IntelliJ IDEA recognizes breakpoints in each worker and shows the debug data for it as a separate thread in the Frames pane on the Debugger tab of the Debug tool window.

Note that IntelliJ IDEA can debug only dedicated workers, debugging for shared workers is currently not supported.

  1. Set the breakpoints in the Workers to debug.

  2. If you are using Service Workers, make sure the Allow unsigned requests checkbox is selected on the Debugger page (Settings/Preferences| Build, Execution, Deployment | Debugger). Otherwise your service workers may be unavailable during a debug session.

  3. Create a debug configuration of the type JavaScript Debug as described above in Debugging client-side JavaScript running on an external web server.

  4. Select the newly created configuration from the Select run/debug configuration list on the toolbar and click Debug the Debug button.

    The HTML file specified in the run configuration opens in the browser and the Debug tool window opens with the Frames list showing all the Workers:

    Debugging Service Workers

    To examine the data (variables, watches, and so on) for a Worker, select its thread in the list and view its data in the Variables and Watches panes. When you select another Worker, the contents of the panes are updated accordingly.

https://medium.com/ableneo/javascript-debugging-in-intellij-idea-997287f15e91

Debugging without IDE

The most used way to debug is simpleconsole.log but you can do better. At least you can use output objects or use console.table.

img

console.log objects or console.table for arrays or arrays of objects

img

Sarcasm

Using a debugger in chrome

Starting debugger without the use of breakpoints simply by adding a word debugger; in the code.

img

Start debugger only when conditions meet.

if (isConditionTrue) {
  debugger;
}

Adding breakpoints in chrome

Placing a breakpoint in chrome Sources tab for a javascript file.

 

img

Adding a breakpoint and resuming the script execution

 

img

Serious debugging using IntelliJ IDEA

At first add extension JetBrains IDE Support to your chrome.

 

img

Start your project in chrome

Open extension by right-clicking on the icon and selecting Inspect in IDEA.

 

img

A javascript debugging session is running

The Javascript debugging session now ready in the IDE.

Add breakpoints and debug directly in IDE

img

img

Adding breakpoint and stoping the program on a breakpoint

👏Clap, 👂follow for more awesome 💟#Javascript and ⚛️#React content.

Scroll to Top