Table of Contents
Rename
Refactoring operation
总结
Home Development Tools VSCode How to perform front-end reconstruction in VSCode? Brief analysis of methods

How to perform front-end reconstruction in VSCode? Brief analysis of methods

Mar 23, 2022 pm 08:12 PM
vscode

How to use VSCode for front-end reconstruction? The following article will introduce to you the method of front-end reconstruction in VSCode. I hope it will be helpful to you!

How to perform front-end reconstruction in VSCode? Brief analysis of methods

In daily development, we often encounter times when we need to refactor. The "Refactor" menu in VS Code provides us with a wealth of operation. It can help us complete the reconstruction work more efficiently. [Recommended study: "vscode introductory tutorial"]

However, the operations provided by this menu are different every time. If you use it temporarily, it will cause certain troubles. Therefore, many students often dare not touch this reconstruction function.

Here, we summarize some commonly used operations for your reference.

First, let’s warm up with a common renaming!

Rename

Why rename: The naming is not clear and cannot be understood.

Operation steps:

  • Select the variable name, right-click and select Rename Symbol , or use the shortcut key F2 ;

  • Input the name you want to modify in the pop-up box;

  • VSCode will change all subsequent related names.

How to perform front-end reconstruction in VSCode? Brief analysis of methods

The warm-up is completed, let’s get to the point!

Refactoring operation

How to perform front-end reconstruction in VSCode? Brief analysis of methods

  • Select the content to be reconstructed, right-click and select Refactor, or use Ctrl Shift R.

  • Depending on the selected content, the following content may appear for selection and reconstruction:

    • import/export

      • Convert default export to named export
      • Convert named export to default export
      • Convert namespace import to named export
      • Convert named imports to namepace export
    • Function/Class

      • Move to a new File
    • Variable/Expression

      • Extract constant
      • Extract to the constant in the closed scope
      • Extract to the constant in the Module scope
      • Convert to optional chain expression
      • Remove unused declarations
    • # characters before unused declarations String

      • Convert to template string Convert to template string
    • Expression/function

      • Extract function
      • Extract the inner function in the current function
      • Extract the function in the Module scope
      • Extract the function in the global scope
    • Object methods

      • generate 'get' and 'set' accessors generate get and set processors
    • Class

      • generate 'get' and 'set' accessors Generate get and set processors
      • Convert the function into ES2015 Class
      • Convert all functions into classes
      • Extracted to Method
      • Extracted to class 'xxx'Readonly field

Magic Number

Why do we need to change the magic number? Because except for base numbers, the actual meaning of numbers cannot be understood by humans.

Objective: Define a constant value and write down the actual meaning of the changed number.

Operation:

  • Select the magic number for reconstruction. Depending on your needs, it is recommended to choose:

    • Extract to the constant in the closed scope
    • Extract to the constant in the Module/global scope
    Both will define a constant, the former is defined in the current function, and the latter is in the entire module/file;
  • The code is extracted into a new variable, and the renamed input appears Box;

  • Use words in all capital letters and use "_" to separate words.

Example: This year’s Double Eleven lasts for 13 days, counting the time when the Double Eleven promotion ends.

function promotionEndDate() {
  return new Date(new Date('2022-11-11').getTime() + 13 * 60 * 60 * 24 * 1000);
}

/**
 * 修改后:
 * 将开始时间 START_DATE,持续的天数 LASTING_DAYS 抽取出来做成变量
 * 如果只有一处使用,则在使用到的函数内定义;
 * 如果多处都有用,可以考虑放在函数外,模块内。
 */
function promotionEndDate() {
    const START_DATE = '2022-11-11';
    const LASTING_DAYS = 13;
    return new Date(new Date(START_DATE).getTime() + LASTING_DAYS * 60 * 60 * 24 * 1000);
}
Copy after login

Complex logical conditions

Why do we need to modify complex logic? Complex logic often has many conditional judgments and is difficult to read.

Operation:

  • Select complex logical conditions for reconstruction. As needed, select:

    • Extract to the closed scope constant
    • Extract to the inner function in the current function
    • Extract function into Module/global scope
  • The code is extracted into a new variable/function, and a renamed input box appears ;

  • Use camel case naming, start with is/has, and capitalize the first letter of each word.

例子:返回指定的某个月有多少天

function monthDay(year, month) {
    var day31 = [1, 3, 5, 7, 8, 10, 12];
    var day30 = [4, 6, 9, 11];
    if (day31.indexOf(month) > -1) {
        return 31;
    } else if (day30.indexOf(month) > -1) {
        return 30;
    } else {
        if ((year % 4 == 0) && (year % 100 != 0 || year % 400 == 0)) {
            return 29;
        } else {
            return 28;
        }
    }
}

/**
 * 修改后
 * 是否闰年在日期处理函数中会经常使用,所以将其提取到当前模块的最外层了
 */
function monthDay(year, month) {
    ...
    if (day31.indexOf(month) > -1) {
        return 31;
    } else if (day30.indexOf(month) > -1) {
        return 30;
    } else {
        if (isLeapYear(year)) {
            return 29;
        } else {
            return 28;
        }
    }
}

function isLeapYear(year) {
    return (year % 4 == 0) && (year % 100 != 0 || year % 400 == 0);
}
Copy after login

写了注释的代码片段

更推荐代码即注释的理念。我们写注释之前要想明白为什么需要注释?

  • 如果代码本身已经很清晰,应该删除注释。
  • 如果抽取代码片段,取个合适的名字,能让代码易于阅读,也可以删除注释。

目标:将代码片段抽取出来做成函数,函数以此代码块的具体功能做命名。

操作:

  • 选择代码块,重构(Refactor)。选择:

    • 提取到当前函数里的 inner function

例子:ajax 请求

function ajax(options) {
  options = options || {};
  options.type = (options.type || 'GET').toUpperCase();
  options.dataType = options.dataType || 'json';
  const READY_STATE = 4;
  const NET_STATUS = {
    OK: 200,
    RIDERCT: 300
  };
  const params = this.formatAjaxParams(options.data);
  let xhr;

  // 创建 - 非IE6 - 第一步
  if (window.XMLHttpRequest) {
    xhr = new window.XMLHttpRequest();
  } else { // IE6及其以下版本浏览器
    xhr = new window.ActiveXObject('Microsoft.XMLHTTP');
  }

  // 连接 和 发送 - 第二步
  if (options.type === 'GET') {
    ...
  } else if (options.type === 'POST') {
    ...
  }
  
  // 接收 - 第三步
  xhr.onreadystatechange = function () {
    if (xhr.readyState === READY_STATE) {
      ...
    }
  };
}

// 修改后
function ajax(options) {
  ...
  let xhr;

  create();
  connectAndSend();
  recieve();

  function create() {...}
  function connectAndSend() {...}
  function recieve() {...}
}
Copy after login

过长的函数

功能拆分做成外部函数,再在内部调用。

操作:

  • 选择代码块重构,选择:

    • 提取到 Module/Global 范围的 function
  • 代码块会生成一个函数,并携带必要的参数

例子:上个例子中,可以将 ajax 的接收模块独立成模块的function

function ajax(options) {
  ...

  create();
  recieve();
  connectAndSend(options, xhr, params);
}
function connectAndSend(options, xhr, params) {
  if (options.type === 'GET') {
    ...
  } else if (options.type === 'POST') {
    ...
  }
}
Copy after login

重复的代码/过长的文件

操作:

  • 选择代码块重构,选择 Move to a new file

  • 代码会迁移到以当前函数/类作为文件名的文件中;如果有多个类/函数,会以第一个类/函数做命明

  • 将函数/类使用 export 暴露出去;

  • 在原文件中用 import 引入函数/类。

例子:日期处理函数:

How to perform front-end reconstruction in VSCode? Brief analysis of methods

移动到新文件后:

How to perform front-end reconstruction in VSCode? Brief analysis of methods

index.js 中,还能跳转到定义的代码,但是实际上并没有引入。

How to perform front-end reconstruction in VSCode? Brief analysis of methods

重命名,修复 import/export;

How to perform front-end reconstruction in VSCode? Brief analysis of methods

import/export

default 和命名、命名空间和命名的转换。

// named
export function nextMonthDay(year, month) {}

// default
export default function nextMonthDay(year, month) {}

// namepace 
import * as refactor from './refactor';

// named
import { nextMonthDay } from './refactor';
Copy after login

对象方法

生成get、set处理器

const person = {
  age: 32
};

// 生成get、set处理器
const person = {
  _age: 32,
  get age() {
    return this._age;
  },
  set age(value) {
    this._age = value;
  },
};
Copy after login

模板字符串

字符串拼接,快速转换成模板字符串:

class Person{
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
  getFullName() {
    return this.firstName + ' ' + this.lastName;
  }
}

// 模板字符串
class Person{
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
  getFullName() {
    return `${this.firstName} ${this.lastName}`;
  }
}
Copy after login

生成get、set处理器,与对象方法的结果类似。

提取到 class xxx 的 Method, 与上面写注释的代码、重复代码提取的类似。

在此不再复述。

提供 ES 2015 类转换,支持原型方法转换。

const Person = function() {
  this.age = 32;
};
Person.prototype.getAge = function() {
  return this.age;
}
Person.prototype.setAge = function(value) {
  return this.age = value;
}

// ES 2015 类
class Person {
  constructor() {
    this.age = 32;
  }
  getAge() {
    return this.age;
  }
  setAge(value) {
    return this.age = value;
  }
}
Copy after login

总结

重构代码的方法还有很多,这里暂时列了一些。希望对大家有所帮助。

剩下的内容,大家可以在重构代码时,多点点这个重构菜单,看看是否有惊喜。

更多关于VSCode的相关知识,请访问:vscode教程!!

The above is the detailed content of How to perform front-end reconstruction in VSCode? Brief analysis of methods. 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

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.

Undress AI Tool

Undress AI Tool

Undress images for free

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)

How to define header files for vscode How to define header files for vscode Apr 15, 2025 pm 09:09 PM

How to define header files using Visual Studio Code? Create a header file and declare symbols in the header file using the .h or .hpp suffix name (such as classes, functions, variables) Compile the program using the #include directive to include the header file in the source file. The header file will be included and the declared symbols are available.

What computer configuration is required for vscode What computer configuration is required for vscode Apr 15, 2025 pm 09:48 PM

VS Code system requirements: Operating system: Windows 10 and above, macOS 10.12 and above, Linux distribution processor: minimum 1.6 GHz, recommended 2.0 GHz and above memory: minimum 512 MB, recommended 4 GB and above storage space: minimum 250 MB, recommended 1 GB and above other requirements: stable network connection, Xorg/Wayland (Linux)

How to solve the problem of vscode Chinese annotations becoming question marks How to solve the problem of vscode Chinese annotations becoming question marks Apr 15, 2025 pm 11:36 PM

How to solve the problem that Chinese comments in Visual Studio Code become question marks: Check the file encoding and make sure it is "UTF-8 without BOM". Change the font to a font that supports Chinese characters, such as "Song Style" or "Microsoft Yahei". Reinstall the font. Enable Unicode support. Upgrade VSCode, restart the computer, and recreate the source file.

How to use VSCode How to use VSCode Apr 15, 2025 pm 11:21 PM

Visual Studio Code (VSCode) is a cross-platform, open source and free code editor developed by Microsoft. It is known for its lightweight, scalability and support for a wide range of programming languages. To install VSCode, please visit the official website to download and run the installer. When using VSCode, you can create new projects, edit code, debug code, navigate projects, expand VSCode, and manage settings. VSCode is available for Windows, macOS, and Linux, supports multiple programming languages ​​and provides various extensions through Marketplace. Its advantages include lightweight, scalability, extensive language support, rich features and version

Common commands for vscode terminal Common commands for vscode terminal Apr 15, 2025 pm 10:06 PM

Common commands for VS Code terminals include: Clear the terminal screen (clear), list the current directory file (ls), change the current working directory (cd), print the current working directory path (pwd), create a new directory (mkdir), delete empty directory (rmdir), create a new file (touch) delete a file or directory (rm), copy a file or directory (cp), move or rename a file or directory (mv) display file content (cat) view file content and scroll (less) view file content only scroll down (more) display the first few lines of the file (head)

vscode terminal usage tutorial vscode terminal usage tutorial Apr 15, 2025 pm 10:09 PM

vscode built-in terminal is a development tool that allows running commands and scripts within the editor to simplify the development process. How to use vscode terminal: Open the terminal with the shortcut key (Ctrl/Cmd). Enter a command or run the script. Use hotkeys (such as Ctrl L to clear the terminal). Change the working directory (such as the cd command). Advanced features include debug mode, automatic code snippet completion, and interactive command history.

How to switch Chinese mode with vscode How to switch Chinese mode with vscode Apr 15, 2025 pm 11:39 PM

VS Code To switch Chinese mode: Open the settings interface (Windows/Linux: Ctrl, macOS: Cmd,) Search for "Editor: Language" settings Select "Chinese" in the drop-down menu Save settings and restart VS Code

vscode Previous Next Shortcut Key vscode Previous Next Shortcut Key Apr 15, 2025 pm 10:51 PM

VS Code One-step/Next step shortcut key usage: One-step (backward): Windows/Linux: Ctrl ←; macOS: Cmd ←Next step (forward): Windows/Linux: Ctrl →; macOS: Cmd →

See all articles