vue-cli3 項目優化之自動生成組件

介紹

做前端的大家都知道通過 vue 開發的項目每次創建新組建的時候,都要新建一個目錄,然後新增 .vue 文件,在這個文件中再寫入 templatescriptstyle 這些內容,雖然在寫入的時候大家都有自己的自動補全共計,不過這些都是模板性的,每次都要這樣重複操作,很麻煩有沒有。

clipboard.png

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

clipboard.png


1.1 chalk工具

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

npm install chalk --save-dev

1.2 創建views

  • 在根目錄中創建一個 scripts 文件夾
  • scripts 中創建 generateView 文件夾
  • generateView 中新建 index.js ,放置生成組件的代碼
  • generateView 中新建 template.js ,放置組件模板的代碼,模板內容可根據項目需求自行修改

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('請輸入要生成的頁面組件名稱、會生成在 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)
        })
    })
}
// 遞歸創建目錄
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.3 配置package.json

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

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


1.4 結果

clipboard.png

clipboard.png

clipboard.png

clipboard.png


稍後再補上生成公用component的代碼,基本差不多,改吧改吧就行了
clipboard.png

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章