Home > Web Front-end > JS Tutorial > How to Set Up VS Code for React Development

How to Set Up VS Code for React Development

Lisa Kudrow
Release: 2025-02-10 15:59:10
Original
978 people have browsed it

How to Set Up VS Code for React Development

VS Code Configuration Guide for Efficient React Development: Improve Your Coding Efficiency

React developers need a code editor that can efficiently write React code. There are thousands of free extensions on the market for VS Code that can help you improve your development workflow. This article will focus on some extensions and settings that will bring your React encoding efficiency to professional level.

Some of the extensions listed in the article are not React-specific, but they can still improve your efficiency and encoding speed. In fact, there are only a few extensions that are really useful in your daily coding.

The tools and technologies listed in this article may save you hours of development work—this time would have been wasted on solving many small but crucial problems. They can also help you reduce coding errors. The key to improving productivity is to automate as many tasks as possible. The following extensions and settings will help you achieve this goal.

Key Points

  • Installing JavaScript language extensions in VS Code: Improve React development efficiency by providing functions such as Intellisense, code snippets and automatic import.
  • Use TypeScript for Large Projects: Provides type safety and reduces errors, which is critical for complex React applications. Remember, VS Code does not include the TypeScript compiler; please install one globally through Node.js.
  • Configure Emmet for JSX: Make sure VS Code recognizes the .js file as a React file, or renames it to .jsx for better Emmet support, thus improving HTML code efficiency.
  • Consistent formatting with Prettier and EditorConfig: Automate code formatting to keep React code base consistent, which is crucial for collaborative projects.
  • Code quality check with ESLint: Integrate with VS Code to highlight and fix encoding errors in real time, promoting best practices and a clean code base.
  • Use React-specific extensions: Extensions such as ES7 React/Redux/GraphQL/React-Native snippets improve encoding speed by providing instant code snippets.

Language Support

When you first install VS Code, it will provide you with many out-of-the-box features—such as JavaScript syntax highlighting and support for TypeScript and JSX code.

The following is a snapshot of the Welcome tab. You can always find it under the Help menu.

How to Set Up VS Code for React Development

You need to do the initial setup here. Since our focus is React, we will start by setting up JavaScript language extensions, which will provide us with additional features that are essential to our coding efficiency workflow.

JavaScript Language Extensions

In the "Tools and Languages" section of the Welcome tab, click the JavaScript link to install it. A reload prompt will appear, and you should click on it to make the new feature take effect.

JavaScript language extension provides a variety of features, including:

  • Intellisense
  • Code snippet
  • JSDoc support
  • Hoom information
  • Automatic import

A complete list and documentation of these features can be found in the VS Code documentation. I highly recommend you read each feature to understand how to use them in your development workflow.

The following figure is an example of Intellisense and automatic import actual operation.

How to Set Up VS Code for React Development

When the Tab key is pressed, the Header component will be imported to the top. The ending symbol must be entered, and the code will be automatically completed as:.

After installing JavaScript language features, VS Code may prompt you to provide a jsconfig.json file in the root directory of the project. This is not required, but setting this file will help IntelliSense provide more accurate tips. Here is a sample configuration:

<code>{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es6",
    "baseUrl": ".",
    "paths": {
      "~/*": ["./*"],
      "@/*": ["./src/*"],
      "~~/*": ["./*"],
      "@@/*": ["./*"]
    }
  },
  "exclude": ["node_modules", ".cache", "dist"]
}</code>
Copy after login
Copy after login
Copy after login

The above configuration tells the JavaScript language server which files belong to your source code and which files do not belong. This ensures that the language service only analyzes your source code, so performance is fast. The full configuration is documented here, explaining all possible values ​​that can be used in jsconfig.js.

TypeScript support

If you plan to build large, complex React projects, it is highly recommended to use TypeScript. This is because TypeScript provides type safety, reducing the possibility of delivering error codes in front-end applications. VS Code provides TypeScript language support out of the box by providing many features (e.g.: :: :

    Syntax and semantic highlighting
  • IntelliSense
  • Code snippet
  • JS Doc Support
  • Hoom information and signature help
  • Format
  • JSX and auto-closed tags
The full list is documented here. When using TypeScript, JSX code is written with the .tsx file extension. After compilation, the output will generate a file with the extension .jsx.

Please note that VS Code does not provide a TypeScript compiler. You must install one in the global Node.js environment as follows:

<code>npm install -g typescript</code>
Copy after login
Copy after login
Copy after login
Alternatively, you can install the Compile Hero Pro extension, which provides compilers for TypeScript and many other languages, including:

    Less
  • Sass, SCSS
  • Stylus
  • Jade
  • Pug
The extension provides more configurable options in terms of when and how to compile TypeScript and style code. If you want to learn more about setting up React and TypeScript, I suggest you check out our other article, “React with TypeScript: Best Practices” for a more detailed explanation.

Flow

Flow is Facebook's alternative to TypeScript. It offers the same functionality, but only works on React projects and is not very popular. VS Code does not support it natively, but you can install the Flow Language Support extension, which provides a limited number of features such as IntelliSense and renaming.

(The following part is similar to the original text, but the wording and sentence structure have been adjusted to achieve the purpose of pseudo-originality.)

Key Mapping Settings

If you are migrating from another code editor to VS Code, you will be happy to know that you can continue to use the same keyboard shortcuts you are already accustomed to. If you are not familiar with the code editor, please skip this section. However, if you have used a code editor before, you may know that retraining muscle memory is inefficient and takes time to adjust.

In the "Settings and Key Binding" section of the Welcome tab, you will see links to install Vim, Sublime, Atom and other keyboard shortcuts. If you click on the "Other" link, you will get a complete list of keymaps that can be installed.

How to Set Up VS Code for React Development

I used to be an Atom user before switching to VS Code. Setting up Atom's key mapping in VS Code is as simple as clicking on the Atom link. This will install the Atom Keymap extension for me. The following configuration is required in settings.json to make VS Code more like "Atom":

<code>{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es6",
    "baseUrl": ".",
    "paths": {
      "~/*": ["./*"],
      "@/*": ["./src/*"],
      "~~/*": ["./*"],
      "@@/*": ["./*"]
    }
  },
  "exclude": ["node_modules", ".cache", "dist"]
}</code>
Copy after login
Copy after login
Copy after login

Please read the instructions provided by your keyboard shortcut extension to learn how to set your shortcut keys. Documents can be found by simply clicking on the keymap extension in the expansion bar.

Emmet JSX support

Emmet is a web development toolkit that allows you to write HTML code more efficiently. If you are not familiar with Emmet, check out the demo to see how it works.

VS Code has built-in Emmet and already supports JSX syntax. Unfortunately, most React starter projects use the .js extension. The problem is that VS Code does not recognize such files as React code, so the JSX feature is not activated. There are two solutions:

  1. Rename all files containing JSX code to .jsx extension (recommended)
  2. Configure VS Code to recognize all .js files as React files. Update your settings.json as follows:
<code>npm install -g typescript</code>
Copy after login
Copy after login
Copy after login

To access settings.json, simply go to the top menu tab and click "View" > "Command Panel". Enter "settings" and select the "Preferences: Open Settings (JSON)" option. Alternatively, you can press Ctrl P and enter "settings.json" to quickly open the file. You can also use the shortcut keys Ctrl , to open the set UI version in the new tab. When you click on the icon button in the first upper right corner, it will open settings.json.

The second option seems to be the easiest way. Unfortunately, this causes problems with other JavaScript development tools such as eslint-config-airbnb, which has a rule set that forces the use of .jsx file extensions for React code. Disabling this rule later can cause other problems.

The official React team does recommend using the .js extension for React code. In my personal experience, it is best to rename all files containing React code to .jsx and use the .js extension for files containing pure JavaScript code. This way, you can use all the development tools more easily.

Format

Writing high-quality code requires you to write consistent code. As developers, we are humans and it is easy to forget the standards we set for ourselves. In this section, we will learn about some essential tools that will help us write consistent code automatically.

EditorConfig

EditorConfig is a simple configuration file that contains only formatting rules. You have to install an extension to have VS Code read these rules and overwrite their own rules. Just follow the steps below to set it up:

  1. Install the EditorConfig extension for VS Code. Note that this will override the user/workspace settings using the settings found in the .editorconfig file.
  2. Create a .editorconfig file in the root directory of the project and copy this sample configuration:
<code>{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es6",
    "baseUrl": ".",
    "paths": {
      "~/*": ["./*"],
      "@/*": ["./src/*"],
      "~~/*": ["./*"],
      "@@/*": ["./*"]
    }
  },
  "exclude": ["node_modules", ".cache", "dist"]
}</code>
Copy after login
Copy after login
Copy after login

VS Code will now follow these rules to format your code. Let's quickly discuss newlines. Windows uses CRLF to indicate the termination of rows, while UNIX-based systems use LF. If you happen to use a file with mixed line breaks, you will have many problems when submitting the file. You can configure how Git handles newlines.

My preferred method is to force all project files to use LF newlines on any platform. Note that EditorConfig does not convert line breaks to existing files. It will only set LF for the new file. To convert all existing files, you have two options:

  • Do it manually (click the text CRLF on the status bar to switch)
  • Format all files with Prettier

Next, let's take a look at Prettier.

Prettier

Prettier is the easiest code formatter to set up for JavaScript code. It supports JavaScript, TypeScript, JSX, CSS, SCSS, Less and GraphQL. To set it up, follow these steps:

  1. Install the Prettier Code Formatizer extension.
  2. Make sure VS Code uses Prettier as its default formatter. Update settings.json as follows:
<code>npm install -g typescript</code>
Copy after login
Copy after login
Copy after login
  1. Install Prettier as development dependency in your project: npm install --save-dev prettier or yarn add -D prettier.
  2. Create .prettierrc and copy the following example rules:
<code>// 控制提示是否显示
"atomKeymap.promptV3Features": true,

// 更改多光标鼠标绑定
"editor.multiCursorModifier": "ctrlCmd",

// 在新窗口中打开文件夹(项目),而不会替换当前窗口
"window.openFoldersInNewWindow": "on",</code>
Copy after login
  1. Update package.json by adding this command to your scripts section:
<code>    "emmet.includeLanguages": {
      "javascript": "javascriptreact"
    }</code>
Copy after login

For steps 3-5, you must do this for each project you want Prettier to support. You can now click on the format command under the npm script panel on VS Code, as shown in the screenshot below.

How to Set Up VS Code for React Development

Alternatively, you can run the command npm run format to run Prettier.

This will cause all files to be reformatted correctly and consistently according to Prettier's default rules and the rules you override in the .prettierrc and .editorconfig files. Line breaks will also remain consistent.

You may have noticed that the code formatting is now in three different locations. You might be wondering what would happen if we had conflicting rules. After activation of Prettier, it will handle these rules according to the following priorities:

  1. Prettier configuration file
  2. .editorconfig
  3. VS Code settings (ignored if any other configuration exists)

In the event of a conflict, the Prettier configuration will be preferred.

HTML to JSX

Any real developer knows that it is common to copy HTML code from somewhere on the internet and paste it into your React code. This usually requires you to convert HTML attributes to valid JSX syntax. Fortunately, there is an extension called html to JSX that performs the conversion for you. After installation, it can easily:

  • Convert existing HTML code to JSX
  • Convert HTML code to valid JSX syntax when pasting

This means that properties such as class will be converted to className. This is a very good time-saving method.

(The rest of the content is similar to the original text, but the wording and sentence structure are adjusted to achieve the purpose of pseudo-originality. Keep the image format unchanged.)

The above is the detailed content of How to Set Up VS Code for React Development. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template