亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
JavaScript Language Extensions
TypeScript support
EditorConfig
Prettier
HTML to JSX
Home Web Front-end JS Tutorial How to Set Up VS Code for React Development

How to Set Up VS Code for React Development

Feb 10, 2025 pm 03:59 PM

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>

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>
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>

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>

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>

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>
  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,

// 更改多光標(biāo)鼠標(biāo)綁定
"editor.multiCursorModifier": "ctrlCmd",

// 在新窗口中打開(kāi)文件夾(項(xiàng)目),而不會(huì)替換當(dāng)前窗口
"window.openFoldersInNewWindow": "on",</code>
  1. Update package.json by adding this command to your scripts section:
<code>    "emmet.includeLanguages": {
      "javascript": "javascriptreact"
    }</code>

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
How does garbage collection work in JavaScript? How does garbage collection work in JavaScript? Jul 04, 2025 am 12:42 AM

JavaScript's garbage collection mechanism automatically manages memory through a tag-clearing algorithm to reduce the risk of memory leakage. The engine traverses and marks the active object from the root object, and unmarked is treated as garbage and cleared. For example, when the object is no longer referenced (such as setting the variable to null), it will be released in the next round of recycling. Common causes of memory leaks include: ① Uncleared timers or event listeners; ② References to external variables in closures; ③ Global variables continue to hold a large amount of data. The V8 engine optimizes recycling efficiency through strategies such as generational recycling, incremental marking, parallel/concurrent recycling, and reduces the main thread blocking time. During development, unnecessary global references should be avoided and object associations should be promptly decorated to improve performance and stability.

How to make an HTTP request in Node.js? How to make an HTTP request in Node.js? Jul 13, 2025 am 02:18 AM

There are three common ways to initiate HTTP requests in Node.js: use built-in modules, axios, and node-fetch. 1. Use the built-in http/https module without dependencies, which is suitable for basic scenarios, but requires manual processing of data stitching and error monitoring, such as using https.get() to obtain data or send POST requests through .write(); 2.axios is a third-party library based on Promise. It has concise syntax and powerful functions, supports async/await, automatic JSON conversion, interceptor, etc. It is recommended to simplify asynchronous request operations; 3.node-fetch provides a style similar to browser fetch, based on Promise and simple syntax

JavaScript Data Types: Primitive vs Reference JavaScript Data Types: Primitive vs Reference Jul 13, 2025 am 02:43 AM

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

React vs Angular vs Vue: which js framework is best? React vs Angular vs Vue: which js framework is best? Jul 05, 2025 am 02:24 AM

Which JavaScript framework is the best choice? The answer is to choose the most suitable one according to your needs. 1.React is flexible and free, suitable for medium and large projects that require high customization and team architecture capabilities; 2. Angular provides complete solutions, suitable for enterprise-level applications and long-term maintenance; 3. Vue is easy to use, suitable for small and medium-sized projects or rapid development. In addition, whether there is an existing technology stack, team size, project life cycle and whether SSR is needed are also important factors in choosing a framework. In short, there is no absolutely the best framework, the best choice is the one that suits your needs.

JavaScript time object, someone builds an eactexe, faster website on Google Chrome, etc. JavaScript time object, someone builds an eactexe, faster website on Google Chrome, etc. Jul 08, 2025 pm 02:27 PM

Hello, JavaScript developers! Welcome to this week's JavaScript news! This week we will focus on: Oracle's trademark dispute with Deno, new JavaScript time objects are supported by browsers, Google Chrome updates, and some powerful developer tools. Let's get started! Oracle's trademark dispute with Deno Oracle's attempt to register a "JavaScript" trademark has caused controversy. Ryan Dahl, the creator of Node.js and Deno, has filed a petition to cancel the trademark, and he believes that JavaScript is an open standard and should not be used by Oracle

Understanding Immediately Invoked Function Expressions (IIFE) in JavaScript Understanding Immediately Invoked Function Expressions (IIFE) in JavaScript Jul 04, 2025 am 02:42 AM

IIFE (ImmediatelyInvokedFunctionExpression) is a function expression executed immediately after definition, used to isolate variables and avoid contaminating global scope. It is called by wrapping the function in parentheses to make it an expression and a pair of brackets immediately followed by it, such as (function(){/code/})();. Its core uses include: 1. Avoid variable conflicts and prevent duplication of naming between multiple scripts; 2. Create a private scope to make the internal variables invisible; 3. Modular code to facilitate initialization without exposing too many variables. Common writing methods include versions passed with parameters and versions of ES6 arrow function, but note that expressions and ties must be used.

Handling Promises: Chaining, Error Handling, and Promise Combinators in JavaScript Handling Promises: Chaining, Error Handling, and Promise Combinators in JavaScript Jul 08, 2025 am 02:40 AM

Promise is the core mechanism for handling asynchronous operations in JavaScript. Understanding chain calls, error handling and combiners is the key to mastering their applications. 1. The chain call returns a new Promise through .then() to realize asynchronous process concatenation. Each .then() receives the previous result and can return a value or a Promise; 2. Error handling should use .catch() to catch exceptions to avoid silent failures, and can return the default value in catch to continue the process; 3. Combinators such as Promise.all() (successfully successful only after all success), Promise.race() (the first completion is returned) and Promise.allSettled() (waiting for all completions)

What is the cache API and how is it used with Service Workers? What is the cache API and how is it used with Service Workers? Jul 08, 2025 am 02:43 AM

CacheAPI is a tool provided by the browser to cache network requests, which is often used in conjunction with ServiceWorker to improve website performance and offline experience. 1. It allows developers to manually store resources such as scripts, style sheets, pictures, etc.; 2. It can match cache responses according to requests; 3. It supports deleting specific caches or clearing the entire cache; 4. It can implement cache priority or network priority strategies through ServiceWorker listening to fetch events; 5. It is often used for offline support, speed up repeated access speed, preloading key resources and background update content; 6. When using it, you need to pay attention to cache version control, storage restrictions and the difference from HTTP caching mechanism.

See all articles