最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

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

介紹

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

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

chalk工具

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

npm install chalk --save-dev

1. 創(chuàng)建views

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

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

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('請輸入要生成的頁面組件名稱、會生成在 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}頁面組件已存在,請重新輸入`)
    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ù)項目需求自行修改

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('請輸入要生成的組件名稱、如需生成全局組件,請加 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}組件目錄已存在,請重新輸入`)
    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)化,我們項目在開發(fā)的過程中就能非常方便的通過命令快速創(chuàng)建公共組件和其他頁面了,在頁面、組件比較多的項目中,可以為我們提高一些效率,也可以通過這樣的命令,來控制團(tuán)隊內(nèi)不同人員新建文件的格式規(guī)范。

總結(jié)

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

相關(guān)文章

  • vue3?reactive數(shù)據(jù)更新視圖不更新問題解決

    vue3?reactive數(shù)據(jù)更新視圖不更新問題解決

    這篇文章主要為大家介紹了vue3?reactive數(shù)據(jù)更新視圖不更新問題解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-06-06
  • Vue.js中computed的基本使用方法

    Vue.js中computed的基本使用方法

    Vue.js中,computed屬性根據(jù)依賴進(jìn)行緩存,只有依賴改變時才重新計算,這樣有效提高性能,computed屬性是響應(yīng)式的,可以自動更新,并且默認(rèn)是只讀的,它與methods的主要區(qū)別在于計算屬性具有緩存性,而方法每次調(diào)用都會執(zhí)行,使用computed可以使模板更加簡潔,提高應(yīng)用性能
    2024-09-09
  • 前端儲存之localStrage、sessionStrage和Vuex使用

    前端儲存之localStrage、sessionStrage和Vuex使用

    localStorage、sessionStorage和Vuex是三種不同的客戶端存儲方式,用于在瀏覽器中保存數(shù)據(jù),localStorage和sessionStorage都是以鍵值對的形式存儲數(shù)據(jù),但localStorage存儲的數(shù)據(jù)在關(guān)閉瀏覽器后仍然存在
    2025-01-01
  • UniApp中實現(xiàn)類似錨點定位滾動效果

    UniApp中實現(xiàn)類似錨點定位滾動效果

    一個uniapp小程序的項目,我們需要實現(xiàn)一個非常實用的功能——類似于錨點定位的交互效果,即在首頁中有多個tab(分類標(biāo)簽),每個tab對應(yīng)著不同的模塊,當(dāng)用戶點擊某個分類的tab時,需要流暢地滾動到對應(yīng)的內(nèi)容位置,提供更好的用戶體驗,
    2023-10-10
  • 關(guān)于vue組件的更新機(jī)制?resize()?callResize()

    關(guān)于vue組件的更新機(jī)制?resize()?callResize()

    這篇文章主要介紹了關(guān)于vue組件的更新機(jī)制?resize()?callResize(),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-04-04
  • 使用vue3+TS實現(xiàn)簡易組件庫的全過程

    使用vue3+TS實現(xiàn)簡易組件庫的全過程

    當(dāng)市面上主流的組件庫不能滿足我們業(yè)務(wù)需求的時候,那么我們就有必要開發(fā)一套屬于自己團(tuán)隊的組件庫,下面這篇文章主要給大家介紹了如何使用vue3+TS實現(xiàn)簡易組件庫的相關(guān)資料,需要的朋友可以參考下
    2022-03-03
  • vue3項目啟動自動打開瀏覽器以及server配置過程

    vue3項目啟動自動打開瀏覽器以及server配置過程

    這篇文章主要介紹了vue3項目啟動自動打開瀏覽器以及server配置過程,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-03-03
  • vue子組件通過.sync修飾符修改props屬性方式

    vue子組件通過.sync修飾符修改props屬性方式

    這篇文章主要介紹了vue子組件通過.sync修飾符修改props屬性方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-08-08
  • ElementUI下拉框選擇后不顯示值問題及解決

    ElementUI下拉框選擇后不顯示值問題及解決

    這篇文章主要介紹了ElementUI下拉框選擇后不顯示值問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-02-02
  • element表格組件實現(xiàn)右鍵菜單的功能

    element表格組件實現(xiàn)右鍵菜單的功能

    本文主要介紹了element表格組件實現(xiàn)右鍵菜單的功能,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-03-03

最新評論

永康市| 安岳县| 壤塘县| 河北省| 邳州市| 抚州市| 方城县| 龙山县| 苍溪县| 邵阳市| 莆田市| 榆树市| 区。| 广饶县| 长岛县| 阿鲁科尔沁旗| 鸡西市| 屯门区| 靖边县| 明光市| 阿克| 天津市| 荆门市| 酉阳| 米脂县| 马鞍山市| 东城区| 博白县| 崇义县| 凤山县| 汨罗市| 新平| 平潭县| 六枝特区| 永康市| 徐闻县| 都兰县| 黑河市| 桓台县| 红桥区| 响水县|