Nuxt2.X-Optimization: Quickly start the nuxt2.x project / 38.61s optimized to 15.84s / shelljs + inquirer + extendRoutes

1. Understanding shelljs

ShellJS is a Node.js module that allows developers to easily use shell script commands in Node.js. It provides many useful functions to help programmers execute common Shell commands and Unix tools, such as cd, pwd, ls, grep, sed, awk, etc. It also enables Node.js programs to perform some system tasks, such as copying and deleting files, and creating and managing child processes. Therefore, ShellJS can help developers process files, execute commands, and manage processes more conveniently in Node.js projects.

2. shelljs startup project

2.1. Project of this article

NUXT 2.X

2.2、package.josn

{
    scripts: {
        "TEST": "cross-env MODE=TEST nuxt",
        "lessStart": "node less-start.js"
    }
}

2.3、less-start.js

const { exec } = require('shelljs')

const env = process.argv[2]

if(env){
  // 启动项目
  exec(`yarn ${env}`)
}

2.4、yarn lessStart TEST

The project started successfully.

The startup time is as shown in the figure: 38.61s

In the process of starting the project, we hope to do some work to speed up the project launch.

In this way it is possible to optimize the startup speed, let's try it.

3. Optimization ideas

You can first specify the route to be developed, and then start the project,
In this way, only the directory to be started will be started, and the startup speed will be improved,
If the project accumulates more content, there should be a more obvious improvement.

4. Start optimizing/quickly start the nuxt2.x project

4.1. Simplified directory

m-front-common // 组件
m-front-common/.cache/path.js // 启动目录
m-front-common/extendRoutes.js // 拓展路由
src // 源码
less-start.js // 快速启动
nuxt.config.js
package.json

4.2. Create less-start.js in the root directory

const fs = require('fs')
const path = require('path')
// eslint-disable-next-line import/no-extraneous-dependencies
const { exec } = require('shelljs')
// eslint-disable-next-line import/no-extraneous-dependencies
const inquirer = require('inquirer');

const env = process.argv[2]

// 获取目录
function getChoicesDirs() {
  const getDirs = (dir) => fs.readdirSync(dir).map(item => item.replace('.vue', '').replace('.js', '').replace('.ts', ''))
  const choices = [];
  const dir = path.resolve(__dirname, './src/pages')
  const itemDirs = getDirs(dir).map(d => d)
  choices.push(...itemDirs)
  return choices
}
// 选择需要的目录
function getCompileDirs() {
  const questions = [{
    type: "checkbox",
    message: `选择模块:`,
    name: "dir",
    choices: getChoicesDirs().map(name => ({ name, checked: ['worktable', 'login'].includes(name) }))
  }];
  const dirs = inquirer
    .prompt(
      questions
    )
    .then(answers => answers.dir)
    .catch(error => {
      console.log('error:', error)
    })
  return dirs
}
Promise.resolve(getCompileDirs()).then(async (res) => {
  // 新建文件./m-front-common/.cache
  if (!fs.existsSync(path.resolve(__dirname, './m-front-common/.cache'))) {
    fs.mkdirSync(path.resolve(__dirname, './m-front-common/.cache'))
  }
  // [ 'cms', 'login', 'worktable' ] 等目录 转化为 ./m-front-common/.cache/path.js 文件的内容
  const defaultStr = JSON.stringify(res)
    .replace(/([\[\]])/g, '$1\n')
    .replace(/("[^(")]*?",?)/g, '  $1\n')
    .replace(/(\/)_([\w\d_-]*?)([\/"]+)/g, '$1:$2?$3')
  fs.writeFileSync(path.resolve(__dirname, './m-front-common/.cache/path.js'), `exports.default = ${defaultStr}`)
  if (env) {
    exec(`yarn ${env}`)
  }
})

4.3、package.json

{
    scripts: {
        "TEST": "cross-env MODE=TEST nuxt",
        "lessStart": "node less-start.js"
    }
}

4.4、./m-front-common/.cache/path.js

Automatically generated after starting the project

exports.default = [
  "cms",
  "login",
  "worktable"
]

4.5、extendRoutes.js

const { default: entries } = require('./.cache/path')

exports.extendRoutes = function extendRoutes(routes, resolve) {
  const routeList = routes
  // console.log('编译模块:', entries)
  const newRoutes = routeList.filter(route => {
    if (route.path === '/') {
      return true
    }
    return entries.some(entry => {
      if (entry.endsWith('/index')) {
        return route.path === `/${entry.replace('/index', '')}`
      }
      return route.path.startsWith(`/${entry}/`) || route.path === `/${entry}`
    })
  })
  routeList.length = 0;
  routeList.push(...newRoutes)
}

4.6、nuxt.config.js

router.extendRoutes to configure

router: {
    base: process.env.ROUTER_BASE,
    middleware: ['meta', 'auth'],
    mode: 'hash',
    extendRoutes(routes, resolve) {
      if (!(process.env.NODE_ENV === 'prodution')) {
        require('./m-front-common/extendRoutes').extendRoutes(routes, resolve)
      }
    },
  },

4.7. Optimization completed, start testing

Startup time: 15.84s

Select the page to start, and the access is successful. The page that is not selected cannot be accessed, achieving the expected effect.

5. Process records

5.1、nuxtCli

const nuxtCli = require('@nuxt/cli/dist/cli')

NuxtCli.run() // 同样可以执行启动项目

5.2、inquirer

const inquirer = require('inquirer'); 

The function of this code is to import the inquirer module, so that we can use the interactive command line tool provided in the inquirer library in the Node.js environment. Use the const keyword to declare a constant named inquirer, and use the require() function in the variable declaration statement. This function is used to introduce the Node.js module and return the object of the corresponding module. Here, require('inquirer') returns the object of the inquirer module, allowing us to use the API it provides in our code.​ 

5.3、extendRoutes

nuxt extendRoutes is a method in Nuxt.js for extending routes and can be configured in the nuxt.config.js file. This method can customize the generated routes during the construction process, such as adding additional routing rules, modifying existing routing rules, etc.

5.4. Can Vue projects use this method?

The idea of ​​vue2 is similar and can be used.

The vue3 + vite project startup speed is already very fast, so there is no need to waste time.

6. Welcome exchanges and corrections

7. Reference links

Configuration - NuxtJS | Nuxt.js Chinese website

shelljs front-end automation - Jianshu

Guess you like

Origin blog.csdn.net/snowball_li/article/details/124214127