Moment For Technology

Projects require good code standardization standards

Posted on Dec. 2, 2022, 1:38 p.m. by 李鈺婷
Category: The front end Tag: The front end Code specification

Introduction to Normalization

Why should there be a standard?

  • Software development requires collaboration of many people
  • Different developers have different coding habits
  • Different preferences increase project maintenance costs
  • Each project or team needs to have clear and consistent standards

Where is standardization required?

  • Code, documentation, even the commit log
  • The product that is considered written during development
  • Code standardization is of Paramount importance

Methods to implement standardization:

  • Standard conventions for coding predecessors
  • Lint is implemented by tools

Common implementations of normalization:

  • ESLint tool
  • Customize ESLint validation rules
  • ESLint support for TypeScript
  • ESLint combines automation tools or Webpack
  • A derivative of ESLint
  • Use of the Stylelint tool


ESLint is the most mainstream JavaScript Lint tool that monitors JS code quality.

To install ESLint:

  • Initialize the projectnpm init -y
  • Install ESLint modules as development dependenciesnpm i eslint -D
  • Verify the installation by running cli commands

ESLint configuration file parsing

ESLint initialization: NPX ESLint --init, which generates.eslintrc.js

Use ESLint to check js files: NPX ESLint xxx.js

// .eslintrc.js
module.exports = {
  // Mark the current code runtime environment
  env: {
    browser: true.es2020: true
  // Used to inherit the shared configuration
  extends: [
    'standard'].// To set the syntax parser configuration
  parserOptions: {
    ecmaVersion: 2015
  // Set the warn, OFF, and ERROR values for each verification rule
  rules: {
    'no-alert': "error"
  // Configure global variables
  globals: {
    "jQuery": "readonly"}}Copy the code

Annotation configuration

const str1 = "${name} is a coder" // eslint-disable-line no-template-curly-in-string 

Copy the code

ESLint combines automation tools

  • After integration, ESLint will definitely work
  • Unified with the project, more convenient management
// gulpfile.js
const { src, dest, parallel, series, watch } = require('gulp')
const eslint = require('gulp-eslint');

const del = require('del')
const browserSync = require('browser-sync')

const loadPlugins = require('gulp-load-plugins')

const plugins = loadPlugins()
const bs = browserSync.create()

const data = {
  menus: [{name: 'Home'.icon: 'aperture'.link: 'index.html'
      name: 'Features'.link: 'features.html'
      name: 'About'.link: 'about.html'
      name: 'Contact'.link: The '#'.children: [{name: 'Twitter'.link: ''
          name: 'About'.link: ''
          name: 'divider'
          name: 'About'.link: ''}}]].pkg: require('./package.json'),
  date: new Date()}const clean = () =  {
  return del(['dist'.'temp'])}const style = () =  {
  return src('src/assets/styles/*.scss', { base: 'src' })
    .pipe(plugins.sass({ outputStyle: 'expanded' }))
    .pipe(bs.reload({ stream: true}}))const script = () =  {
  return src('src/assets/scripts/*.js', { base: 'src' })
    .pipe(plugins.babel({ presets: ['@babel/preset-env'] }))
    .pipe(bs.reload({ stream: true}}))const page = () =  {
  return src('src/*.html', { base: 'src' })
    .pipe(plugins.swig({ data, defaults: { cache: false}}))// Prevent the page from being updated due to template caching
    .pipe(bs.reload({ stream: true}}))const image = () =  {
  return src('src/assets/images/**', { base: 'src' })
    .pipe(dest('dist'))}const font = () =  {
  return src('src/assets/fonts/**', { base: 'src' })
    .pipe(dest('dist'))}const extra = () =  {
  return src('public/**', { base: 'public' })
    .pipe(dest('dist'))}const serve = () =  {
  watch('src/assets/styles/*.scss', style)
  watch('src/assets/scripts/*.js', script)
  watch('src/*.html', page)
  ], bs.reload)

    notify: false.port: 2080.// open: false,
    // files: 'dist/**',
    server: {
      baseDir: ['temp'.'src'.'public'].routes: {
        '/node_modules': 'node_modules'}}})}const useref = () =  {
  return src('temp/*.html', { base: 'temp' })
    .pipe(plugins.useref({ searchPath: ['temp'.'. ']}))// html js css
    .pipe(plugins.if(/\.js$/, plugins.uglify()))
    .pipe(plugins.if(/\.css$/, plugins.cleanCss()))
    .pipe(plugins.if(/\.html$/, plugins.htmlmin({
      collapseWhitespace: true.minifyCSS: true.minifyJS: true
    .pipe(dest('dist'))}const compile = parallel(style, script, page)

// Tasks performed before going online
const build =  series(
    series(compile, useref),

const develop = series(compile, serve)

module.exports = {
Copy the code

ESLint combining webpack

// webpack.config.js

const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  mode: 'production'.entry: './src/main.js'.module: {
    rules: [{test: /\.js$/, 
        exclude: /node_modules/, 
        use: 'babel-loader'
        test: /\.js$/, 
        exclude: /node_modules/, 
        use: 'eslint-loader'.//eslint-loader should be executed last
        enforce: "pre"
        test: /\.css$/, 
        use: [
          'style-loader'.'css-loader']]}},plugins: [
    new HtmlWebpackPlugin({
      template: 'src/index.html'}})]Copy the code

Check ESLint TypeScript

// .eslintrc.js
module.exports = {
  env: {
    browser: true.es2020: true
  extends: [
    'standard'].// Specify the syntax parser
  parser: '@typescript-eslint/parser'.parserOptions: {
    ecmaVersion: 11
  / / the plugin
  plugins: [
    '@typescript-eslint'].rules: {}}Copy the code


Stylelint Stylelint

  • Provides default code checking rules
  • Provides the CLI tool for quick invocation
  • Knowledge of Sass, Less, PostCSS through plug-ins
  • Supports Gulp or WebPack integration

Install: NPM I stylelint -d

Add the configuration file.stylelintr.js

module.exports = {
  // Share files
  extends: [
    "stylelint-config-standard".//npm i stylelint-config-standard -D
    "stylelint-config-sass-guidelines" // Verify Sass NPM I stylelint-config-sass-guidelines -d]}Copy the code


Prettier is a common front-end code formatting tool that automatically formats code.

Prettier Prettier has the following advantages:

  • Can be configured to change
  • Support for multiple languages
  • Integrated with most editors
  • Simple configuration items

Install: NPM install --save-dev --save-exact prettier

You only need to use eslint-plugin-prettier to add prettier for ESLint rule configuration.

npm i -D prettier eslint-plugin-prettier

// .stylelintrc.js
module.exports = {
  // Share files
  extends: [ "prettier"].rules: {
    "prettier/prettier": "error"}}Copy the code

ESLint implements Git Hooks to check code before committing

Git Hooks


  • Git Hooks are also called Git Hooks, and each hook corresponds to a task
  • Shell scripts allow you to write specific actions to be performed when the hook task is triggered

Action: Creates a directory and initializes the Git repository. Open.git and see the hooks directory.

The hooks directory contains a number of sample files, each of which is actually a git hook.

The only hook we need to focus on is the pre-commit. Sample hook, which corresponds to the commit operation, triggers some of the tasks defined in the hook when we commit.

Make a copy of the pre-commit. Sample and rename it to pre-commit. Change the content to the following:Then create a TXT file for the test in the project directory, write some content, and then execute git operation


We hope that through the git hook prior to submit code to enforce the code execution lint operating, but here we met a very real problem, for example, the present a lot of front-end developer is not good at using shell script to write function, and the current function is we must to use, so they developed a NPM module, A simple implementation of Git Hooks directly is Husky.

With the Husky module, you can use some of the functionality of git hooks without having to write shell scripts.

Install: NPM i-d Husky

Configuration package. Json

"scripts": {"lint":"eslint ./index.js --fix"
"husky": {"hooks": {"pre-commit":"npm run lint"}}Copy the code

NPM run lint will be executed when we commit code using Git, which is eslint./index.js --fix


With Husky, you can lint code before committing, but if you want to do something later, such as formatting, then Husky isn't enough. So we used another module called Lint-Staged. It can work with Husky and continue to do some other things with the code.

To install Lint-staged: NPM I Lint-staged -d

Configuration package. Json

"scripts": {
"husky": {
  "hooks": {
    "pre-commit": "npm run precommit"}},"lint-staged": {"*.js": [// Here we configure some tasks that we want to perform later
    "eslint --fix"."git add"]}Copy the code

In this way, we modified the code, the implementation of the git add., then perform the git commit -m "111" to submit code that is executed eslint - fix command, check the code no problem after will continue to follow the git add orders, Finally, you can push your code to a remote repository through Git Push.

About (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.