欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

vue-cli3 項(xiàng)目優(yōu)化之通過 node 自動(dòng)生成組件模板 generate View、Component

 更新時(shí)間:2019年04月30日 14:43:15   作者:多多ing  
這篇文章主要介紹了vue-cli3 項(xiàng)目優(yōu)化之通過 node 自動(dòng)生成組件模板 generate View、Component的相關(guān)知識(shí),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

介紹

做前端的大家都知道通過 vue 開發(fā)的項(xiàng)目每次創(chuàng)建新組建的時(shí)候,都要新建一個(gè)目錄,然后新增 .vue 文件,在這個(gè)文件中再寫入 template 、 script 、 style 這些內(nèi)容,雖然在寫入的時(shí)候大家都有自己的自動(dòng)補(bǔ)全共計(jì),不過這些都是模板性的,每次都要這樣重復(fù)操作,很麻煩有沒有。

本文就是通過node來幫助我們,自動(dòng)去執(zhí)行這些重復(fù)操作,而我們只需要告訴控制臺(tái)我們需要?jiǎng)?chuàng)建的組件名字就可以了。
本文自動(dòng)創(chuàng)建的組件包含兩個(gè)文件:入口文件 index.js 、vue文件 main.vue

chalk工具

為了方便我們能看清控制臺(tái)輸出的各種語句,我們先安裝一下 chalk

npm install chalk --save-dev

1. 創(chuàng)建views

在根目錄中創(chuàng)建一個(gè) scripts 文件夾

  • 在 scripts 中創(chuàng)建 generateView 文件夾
  • 在 generateView 中新建 index.js ,放置生成組件的代碼
  • 在 generateView 中新建 template.js ,放置組件模板的代碼,模板內(nèi)容可根據(jù)項(xiàng)目需求自行修改

index.js

// index.js
const chalk = require('chalk')
const path = require('path')
const fs = require('fs')
const resolve = (...file) => path.resolve(__dirname, ...file)
const log = message => console.log(chalk.green(`${message}`))
const successLog = message => console.log(chalk.blue(`${message}`))
const errorLog = error => console.log(chalk.red(`${error}`))
// 導(dǎo)入模板
const {
  vueTemplate,
  entryTemplate
} = require('./template')
// 生成文件
const generateFile = (path, data) => {
  if (fs.existsSync(path)) {
    errorLog(`${path}文件已存在`)
    return
  }
  return new Promise((resolve, reject) => {
    fs.writeFile(path, data, 'utf8', err => {
      if (err) {
        errorLog(err.message)
        reject(err)
      } else {
        resolve(true)
      }
    })
  })
}
log('請(qǐng)輸入要生成的頁面組件名稱、會(huì)生成在 views/目錄下')
let componentName = ''
process.stdin.on('data', async chunk => {
  // 組件名稱
  const inputName = String(chunk).trim().toString()
  // Vue頁面組件路徑
  const componentPath = resolve('../../src/views', inputName)
  // vue文件
  const vueFile = resolve(componentPath, 'main.vue')
  // 入口文件
  const entryFile = resolve(componentPath, 'entry.js')
  // 判斷組件文件夾是否存在
  const hasComponentExists = fs.existsSync(componentPath)
  if (hasComponentExists) {
    errorLog(`${inputName}頁面組件已存在,請(qǐng)重新輸入`)
    return
  } else {
    log(`正在生成 component 目錄 ${componentPath}`)
    await dotExistDirectoryCreate(componentPath)
  }
  try {
    // 獲取組件名
    if (inputName.includes('/')) {
      const inputArr = inputName.split('/')
      componentName = inputArr[inputArr.length - 1]
    } else {
      componentName = inputName
    }
    log(`正在生成 vue 文件 ${vueFile}`)
    await generateFile(vueFile, vueTemplate(componentName))
    log(`正在生成 entry 文件 ${entryFile}`)
    await generateFile(entryFile, entryTemplate(componentName))
    successLog('生成成功')
  } catch (e) {
    errorLog(e.message)
  }
  process.stdin.emit('end')
})
process.stdin.on('end', () => {
  log('exit')
  process.exit()
})
function dotExistDirectoryCreate(directory) {
  return new Promise((resolve) => {
    mkdirs(directory, function() {
      resolve(true)
    })
  })
}
// 遞歸創(chuàng)建目錄
function mkdirs(directory, callback) {
  var exists = fs.existsSync(directory)
  if (exists) {
    callback()
  } else {
    mkdirs(path.dirname(directory), function() {
      fs.mkdirSync(directory)
      callback()
    })
  }
}

template.js

// template.js
module.exports = {
  vueTemplate: compoenntName => {
    return `<template>
 <div class="${compoenntName}">
 ${compoenntName}組件
 </div>
</template>
<script>
export default {
 name: '${compoenntName}'
};
</script>
<style lang="stylus" scoped>
.${compoenntName} {
};
</style>`
  },
  entryTemplate: compoenntName => {
    return `import ${compoenntName} from './main.vue'
export default [{
 path: "/${compoenntName}",
 name: "${compoenntName}",
 component: ${compoenntName}
}]`
  }
}

1.1 配置package.json

"new:view": "node ./scripts/generateView/index"

如果使用 npm 的話 就是 npm run new:view
如果是 yarn 自行修改命令

1.2 結(jié)果

2. 創(chuàng)建component

跟views基本一樣的步驟

  • 在 scripts 中創(chuàng)建 generateComponent 文件夾
  • 在 generateComponent 中新建 index.js ,放置生成組件的代碼
  • 在 generateComponent 中新建 template.js ,放置組件模板的代碼,模板內(nèi)容可根據(jù)項(xiàng)目需求自行修改

index.js

// index.js`
const chalk = require('chalk')
const path = require('path')
const fs = require('fs')
const resolve = (...file) => path.resolve(__dirname, ...file)
const log = message => console.log(chalk.green(`${message}`))
const successLog = message => console.log(chalk.blue(`${message}`))
const errorLog = error => console.log(chalk.red(`${error}`))
const {
  vueTemplate,
  entryTemplate
} = require('./template')
const generateFile = (path, data) => {
  if (fs.existsSync(path)) {
    errorLog(`${path}文件已存在`)
    return
  }
  return new Promise((resolve, reject) => {
    fs.writeFile(path, data, 'utf8', err => {
      if (err) {
        errorLog(err.message)
        reject(err)
      } else {
        resolve(true)
      }
    })
  })
}
log('請(qǐng)輸入要生成的組件名稱、如需生成全局組件,請(qǐng)加 global/ 前綴')
let componentName = ''
process.stdin.on('data', async chunk => {
  const inputName = String(chunk).trim().toString()
    /**
     * 組件目錄路徑
     */
  const componentDirectory = resolve('../../src/components', inputName)
  /**
   * vue組件路徑
   */
  const componentVueName = resolve(componentDirectory, 'main.vue')
    /**
     * 入口文件路徑
     */
  const entryComponentName = resolve(componentDirectory, 'index.js')
  const hasComponentDirectory = fs.existsSync(componentDirectory)
  if (hasComponentDirectory) {
    errorLog(`${inputName}組件目錄已存在,請(qǐng)重新輸入`)
    return
  } else {
    log(`正在生成 component 目錄 ${componentDirectory}`)
    await dotExistDirectoryCreate(componentDirectory)
      // fs.mkdirSync(componentDirectory);
  }
  try {
    if (inputName.includes('/')) {
      const inputArr = inputName.split('/')
      componentName = inputArr[inputArr.length - 1]
    } else {
      componentName = inputName
    }
    log(`正在生成 vue 文件 ${componentVueName}`)
    await generateFile(componentVueName, vueTemplate(componentName))
    log(`正在生成 entry 文件 ${entryComponentName}`)
    await generateFile(entryComponentName, entryTemplate)
    successLog('生成成功')
  } catch (e) {
    errorLog(e.message)
  }
  process.stdin.emit('end')
})
process.stdin.on('end', () => {
  log('exit')
  process.exit()
})
function dotExistDirectoryCreate(directory) {
  return new Promise((resolve) => {
    mkdirs(directory, function() {
      resolve(true)
    })
  })
}
// 遞歸創(chuàng)建目錄
function mkdirs(directory, callback) {
  var exists = fs.existsSync(directory)
  if (exists) {
    callback()
  } else {
    mkdirs(path.dirname(directory), function() {
      fs.mkdirSync(directory)
      callback()
    })
  }
}

template.js

// template.js
module.exports = {
  vueTemplate: compoenntName => {
    return `<template>
 <div class="${compoenntName}">
 ${compoenntName}組件
 </div>
</template>
<script>
export default {
 name: '${compoenntName}'
};
</script>
<style lang="stylus" scoped>
.${compoenntName} {
};
</style>`
  },
  entryTemplate: `import Main from './main.vue'
export default Main`
}

2.1 配置package.json

"new:comp": "node ./scripts/generateComponent/index"

  • 如果使用 npm 的話 就是 npm run new:comp
  • 如果是 yarn 自行修改命令

2.2 結(jié)果

通過以上的 vue-cli3 優(yōu)化,我們項(xiàng)目在開發(fā)的過程中就能非常方便的通過命令快速創(chuàng)建公共組件和其他頁面了,在頁面、組件比較多的項(xiàng)目中,可以為我們提高一些效率,也可以通過這樣的命令,來控制團(tuán)隊(duì)內(nèi)不同人員新建文件的格式規(guī)范。

總結(jié)

以上所述是小編給大家介紹的vue-cli3 項(xiàng)目優(yōu)化之通過 node 自動(dòng)生成組件模板 generate View、Component,希望對(duì)大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會(huì)及時(shí)回復(fù)大家的!

相關(guān)文章

  • cdn模式下vue的基本用法詳解

    cdn模式下vue的基本用法詳解

    這篇文章主要介紹了cdn模式下vue的基本用法,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友參考下吧
    2018-10-10
  • Vue利用openlayers實(shí)現(xiàn)點(diǎn)擊彈窗的方法詳解

    Vue利用openlayers實(shí)現(xiàn)點(diǎn)擊彈窗的方法詳解

    點(diǎn)擊彈窗其實(shí)就是添加一個(gè)彈窗圖層,然后在點(diǎn)擊的時(shí)候讓他顯示出來罷了。本文將利用openlayers實(shí)現(xiàn)這一效果,快跟隨小編一起學(xué)習(xí)一下吧
    2022-06-06
  • vuejs父子組件通信的問題

    vuejs父子組件通信的問題

    本篇文章主要介紹了vue父子組件通信 ,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-01-01
  • Vue中常用rules校驗(yàn)規(guī)則(實(shí)例代碼)

    Vue中常用rules校驗(yàn)規(guī)則(實(shí)例代碼)

    這篇文章主要介紹了Vue中常用rules校驗(yàn)規(guī)則,本文通過實(shí)例代碼個(gè)大家介紹了一些校驗(yàn)方法,需要的朋友可以參考下
    2019-11-11
  • Vue的data、computed、watch源碼淺談

    Vue的data、computed、watch源碼淺談

    這篇文章主要介紹了Vue的data、computed、watch源碼淺談,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-04-04
  • vue+elementUI如何實(shí)現(xiàn)頂部路由標(biāo)簽跳轉(zhuǎn)

    vue+elementUI如何實(shí)現(xiàn)頂部路由標(biāo)簽跳轉(zhuǎn)

    這篇文章主要介紹了vue+elementUI如何實(shí)現(xiàn)頂部路由標(biāo)簽跳轉(zhuǎn)問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-03-03
  • Vue中的change事件無效問題及解決

    Vue中的change事件無效問題及解決

    這篇文章主要介紹了Vue中的change事件無效問題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-06-06
  • Vite?vue如何使用cdn引入element-plus

    Vite?vue如何使用cdn引入element-plus

    這篇文章主要介紹了Vite?vue使用cdn引入element-plus的相關(guān)知識(shí),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-04-04
  • Vue如何比較字符串變化并高亮變化的部分

    Vue如何比較字符串變化并高亮變化的部分

    這篇文章主要介紹了Vue如何比較字符串變化并高亮變化的部分問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-12-12
  • vue使用video.js依賴接入視頻流((hls(m3u8)、flv))的示例代碼

    vue使用video.js依賴接入視頻流((hls(m3u8)、flv))的示例代碼

    這篇文章給大家介紹了vue如和使用video.js依賴接入視頻流((hls(m3u8)、flv)),文章通過代碼示例給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下
    2024-01-01

最新評(píng)論