<h1 id="articleHeader0">介绍</h1> <p>做前端的大家都知道通过 <code>vue</code> 开发的项目每次创建新组建的时候,都要新建一个目录,然后新增 <code>.vue</code> 文件,在这个文件中再写入 <code>template</code> 、 <code>script</code> 、 <code>style</code> 这些内容,虽然在写入的时候大家都有自己的自动补全共计,不过这些都是模板性的,每次都要这样重复操作,很麻烦有没有。</p> <p><span class="img-wrap"><img data-src="/img/bVbnU7p?w=500&amp;h=500" src="/img/bVbnU7p?w=500&amp;h=500" alt="clipboard.png" title="clipboard.png" style="cursor: pointer; display: inline;"></span></p> <p>本文就是通过<code><a href="http://www.js-code.com/tag/node" title="node" target="_blank">node</a></code>来帮助我们,自动去执行这些重复操作,而我们只需要告诉控制台我们需要创建的组件名字就可以了。<br />本文自动创建的组件包含两个文件:入口文件 <code>index.js</code> 、vue文件 <code>main.vue</code> </p> <p><span class="img-wrap"><img data-src="/img/bVbnVcj?w=276&amp;h=315" src="https://static.segmentfault.com/v-5cc2cd8e/global/img/squares.svg" alt="clipboard.png" title="clipboard.png" style="cursor: pointer;"></span></p> <hr> <h2 id="articleHeader1">1.1 chalk工具</h2> <p>为了方便我们能看清控制台输出的各种语句,我们先安装一下 <code>chalk</code></p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="npm install chalk --save-dev " title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs sql"><code>npm <span class="hljs-keyword">install</span> chalk <span class="hljs-comment">--save-dev</span> </code></pre> <hr> <h2 id="articleHeader2">1.2 创建views</h2> <ul> <li>在根目录中创建一个 <code>scripts</code> 文件夹</li> <li>在 <code>scripts</code> 中创建 <code>generateView</code> 文件夹</li> <li>在 <code>generateView</code> 中新建 <code>index.js</code> ,放置生成组件的代码</li> <li>在 <code>generateView</code> 中新建 <code>template.js</code> ,放置组件模板的代码,模板内容可根据项目需求自行修改</li> </ul> <h3 id="articleHeader3">index.js</h3> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="// index.js const chalk = require('chalk') const path = require('path') const fs = require('fs') const resolve = (...file) => path.resolve(__dirname, ...file)<br /> const log = message => console.log(chalk.green(`${message}`))<br /> const successLog = message => console.log(chalk.blue(`${message}`))<br /> const errorLog = error => console.log(chalk.red(`${error}`))<br /> // 导入模板<br /> const {<br /> vueTemplate,<br /> entryTemplate<br /> } = require('./template')<br /> // 生成文件<br /> const generateFile = (path, data) => {<br /> if (fs.existsSync(path)) {<br /> errorLog(`${path}文件已存在`)<br /> return<br /> }<br /> return new Promise((resolve, reject) => {<br /> fs.writeFile(path, data, 'utf8', err => {<br /> if (err) {<br /> errorLog(err.message)<br /> reject(err)<br /> } else {<br /> resolve(true)<br /> }<br /> })<br /> })<br /> }<br /> log('请输入要生成的页面组件名称、会生成在 views/目录下')<br /> let componentName = ''<br /> process.stdin.on('data', async chunk => {<br /> // 组件名称<br /> const inputName = String(chunk).trim().toString()<br /> // Vue页面组件路径<br /> const componentPath = resolve('../../src/views', inputName)<br /> // vue文件<br /> const vueFile = resolve(componentPath, 'main.vue')<br /> // 入口文件<br /> const entryFile = resolve(componentPath, 'entry.js')<br /> // 判断组件文件夹是否存在<br /> const hasComponentExists = fs.existsSync(componentPath)<br /> if (hasComponentExists) {<br /> errorLog(`${inputName}页面组件已存在,请重新输入`)<br /> return<br /> } else {<br /> log(`正在生成 component 目录 ${componentPath}`)<br /> await dotExistDirectoryCreate(componentPath)<br /> }<br /> try {<br /> // 获取组件名<br /> if (inputName.includes('/')) {<br /> const inputArr = inputName.split('/')<br /> componentName = inputArr[inputArr.length - 1]<br /> } else {<br /> componentName = inputName<br /> }<br /> log(`正在生成 vue 文件 ${vueFile}`)<br /> await generateFile(vueFile, vueTemplate(componentName))<br /> log(`正在生成 entry 文件 ${entryFile}`)<br /> await generateFile(entryFile, entryTemplate(componentName))<br /> successLog('生成成功')<br /> } catch (e) {<br /> errorLog(e.message)<br /> }</p> <p> process.stdin.emit('end')<br /> })<br /> process.stdin.on('end', () => {<br /> log('exit')<br /> process.exit()<br /> })</p> <p>function dotExistDirectoryCreate(directory) {<br /> return new Promise((resolve) => {<br /> mkdirs(directory, function() {<br /> resolve(true)<br /> })<br /> })<br /> }<br /> // 递归创建目录<br /> function mkdirs(directory, callback) {<br /> var exists = fs.existsSync(directory)<br /> if (exists) {<br /> callback()<br /> } else {<br /> mkdirs(path.dirname(directory), function() {<br /> fs.mkdirSync(directory)<br /> callback()<br /> })<br /> }<br /> }" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs typescript"><code><span class="hljs-comment">// index.js</span> <span class="hljs-keyword"><a href="http://www.js-code.com/tag/const" title="浏览关于“const”的文章" target="_blank" class="tag_link">const</a></span> chalk = <span class="hljs-built_in">require</span>(<span class="hljs-string">'chalk'</span>) <span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">'path'</span>) <span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>) <span class="hljs-keyword">const</span> resolve = <span class="hljs-function">(<span class="hljs-params">...file</span>) =&gt;</span> path.resolve(__dirname, ...file) <span class="hljs-keyword">const</span> log = <span class="hljs-function"><span class="hljs-params">message</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(chalk.green(<span class="hljs-string">`<span class="hljs-subst">${message}</span>`</span>)) <span class="hljs-keyword">const</span> successLog = <span class="hljs-function"><span class="hljs-params">message</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(chalk.blue(<span class="hljs-string">`<span class="hljs-subst">${message}</span>`</span>)) <span class="hljs-keyword">const</span> errorLog = <span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(chalk.red(<span class="hljs-string">`<span class="hljs-subst">${error}</span>`</span>)) <span class="hljs-comment">// 导入模板</span> <span class="hljs-keyword">const</span> { vue<a href="http://www.js-code.com/tag/template" title="浏览关于“Template”的文章" target="_blank" class="tag_link">Template</a>, entryTemplate } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./template'</span>) <span class="hljs-comment">// 生成文件</span> <span class="hljs-keyword">const</span> generateFile = <span class="hljs-function">(<span class="hljs-params">path, data</span>) =&gt;</span> { <span class="hljs-keyword">if</span> (fs.existsSync(path)) { errorLog(<span class="hljs-string">`<span class="hljs-subst">${path}</span>文件已存在`</span>) <span class="hljs-keyword">return</span> } <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in"><a href="http://www.js-code.com/tag/promise" title="浏览关于“Promise”的文章" target="_blank" class="tag_link">Promise</a></span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> { fs.writeFile(path, data, <span class="hljs-string">'utf8'</span>, <span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> { <span class="hljs-keyword">if</span> (err) { errorLog(err.message) reject(err) } <span class="hljs-keyword">else</span> { resolve(<span class="hljs-literal">true</span>) } }) }) } log(<span class="hljs-string">'请输入要生成的页面组件名称、会生成在 views/目录下'</span>) <span class="hljs-keyword"><a href="http://www.js-code.com/tag/let" title="浏览关于“let”的文章" target="_blank" class="tag_link">let</a></span> componentName = <span class="hljs-string">''</span> process.stdin.on(<span class="hljs-string">'data'</span>, <span class="hljs-keyword">async</span> chunk =&gt; { <span class="hljs-comment">// 组件名称</span> <span class="hljs-keyword">const</span> inputName = <span class="hljs-built_in">String</span>(chunk).trim().toString() <span class="hljs-comment">// <a href="http://www.js-code.com/tag/vue" title="浏览关于“Vue”的文章" target="_blank" class="tag_link">Vue</a>页面组件路径</span> <span class="hljs-keyword">const</span> componentPath = resolve(<span class="hljs-string">'../../src/views'</span>, inputName) <span class="hljs-comment">// vue文件</span> <span class="hljs-keyword">const</span> vueFile = resolve(componentPath, <span class="hljs-string">'main.vue'</span>) <span class="hljs-comment">// 入口文件</span> <span class="hljs-keyword">const</span> entryFile = resolve(componentPath, <span class="hljs-string">'entry.js'</span>) <span class="hljs-comment">// 判断组件文件夹是否存在</span> <span class="hljs-keyword">const</span> hasComponentExists = fs.existsSync(componentPath) <span class="hljs-keyword">if</span> (hasComponentExists) { errorLog(<span class="hljs-string">`<span class="hljs-subst">${inputName}</span>页面组件已存在,请重新输入`</span>) <span class="hljs-keyword">return</span> } <span class="hljs-keyword">else</span> { log(<span class="hljs-string">`正在生成 component 目录 <span class="hljs-subst">${componentPath}</span>`</span>) <span class="hljs-keyword">await</span> dotExistDirectoryCreate(componentPath) } <span class="hljs-keyword">try</span> { <span class="hljs-comment">// 获取组件名</span> <span class="hljs-keyword">if</span> (inputName.includes(<span class="hljs-string">'/'</span>)) { <span class="hljs-keyword">const</span> inputArr = inputName.split(<span class="hljs-string">'/'</span>) componentName = inputArr[inputArr.length - <span class="hljs-number">1</span>] } <span class="hljs-keyword">else</span> { componentName = inputName } log(<span class="hljs-string">`正在生成 vue 文件 <span class="hljs-subst">${vueFile}</span>`</span>) <span class="hljs-keyword">await</span> generateFile(vueFile, vueTemplate(componentName)) log(<span class="hljs-string">`正在生成 entry 文件 <span class="hljs-subst">${entryFile}</span>`</span>) <span class="hljs-keyword">await</span> generateFile(entryFile, entryTemplate(componentName)) successLog(<span class="hljs-string">'生成成功'</span>) } <span class="hljs-keyword">catch</span> (e) { errorLog(e.message) } process.stdin.emit(<span class="hljs-string">'end'</span>) }) process.stdin.on(<span class="hljs-string">'end'</span>, <span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> { log(<span class="hljs-string">'exit'</span>) process.exit() }) <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">dotExistDirectoryCreate</span>(<span class="hljs-params">directory</span>) </span>{ <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in"><a href="http://www.js-code.com/tag/promis" title="浏览关于“Promis”的文章" target="_blank" class="tag_link">Promis</a>e</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =&gt;</span> { mkdirs(directory, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{ resolve(<span class="hljs-literal">true</span>) }) }) } <span class="hljs-comment">// 递归创建目录</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">mkdirs</span>(<span class="hljs-params">directory, callback</span>) </span>{ <span class="hljs-keyword">var</span> exists = fs.existsSync(directory) <span class="hljs-keyword">if</span> (exists) { callback() } <span class="hljs-keyword">else</span> { mkdirs(path.dirname(directory), <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{ fs.mkdirSync(directory) callback() }) } }</code></pre> <h3 id="articleHeader4">template.js</h3> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="// template.js module.exports = { vueTemplate: compoenntName => {<br /> return `<template></p> <div class=&quot;${compoenntName}&quot;> ${compoenntName}组件 </div> <p></template><br /> <script> <a href="http://www.js-code.com/tag/export" title="export" target="_blank">export</a> default { name: '${compoenntName}' }; </script></p> <style lang=&quot;stylus&quot; scoped> .${compoenntName} { }; </style> <p>`<br /> },<br /> entryTemplate: compoenntName => {<br /> return `import ${compoenntName} from './main.vue'<br /> export default [{<br /> path: &quot;/${compoenntName}&quot;,<br /> name: &quot;${compoenntName}&quot;,<br /> component: ${compoenntName}<br /> }]`<br /> }<br /> }</p> <p>" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs typescript"><code><span class="hljs-comment">// template.js</span> <span class="hljs-built_in">module</span>.<a href="http://www.js-code.com/tag/export" title="浏览关于“export”的文章" target="_blank" class="tag_link">export</a>s = { vueTemplate: <span class="hljs-function"><span class="hljs-params">compoenntName</span> =&gt;</span> { <span class="hljs-keyword">return</span> <span class="hljs-string">`&lt;template&gt; &lt;<a href="http://www.js-code.com/tag/div" title="浏览关于“div”的文章" target="_blank" class="tag_link">div</a> class="<span class="hljs-subst">${compoenntName}</span>"&gt; <span class="hljs-subst">${compoenntName}</span>组件 &lt;/div&gt; &lt;/template&gt; &lt;script&gt; export default { name: '<span class="hljs-subst">${compoenntName}</span>' }; &lt;/script&gt; &lt;style lang="stylus" scoped&gt; .<span class="hljs-subst">${compoenntName}</span> { }; &lt;/style&gt;`</span> }, entryTemplate: <span class="hljs-function"><span class="hljs-params">compoenntName</span> =&gt;</span> { <span class="hljs-keyword">return</span> <span class="hljs-string">`import <span class="hljs-subst">${compoenntName}</span> from './main.vue' export default [{ path: "/<span class="hljs-subst">${compoenntName}</span>", name: "<span class="hljs-subst">${compoenntName}</span>", component: <span class="hljs-subst">${compoenntName}</span> }]`</span> } } </code></pre> <hr> <h2 id="articleHeader5">1.3 配置package.json</h2> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="&quot;new:view&quot;: &quot;node ./scripts/generateView/index&quot;" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs objectivec"><code style="word-break: break-word; white-space: initial;"><span class="hljs-string">"new:view"</span>: <span class="hljs-string">"<a href="http://www.js-code.com/tag/node" title="浏览关于“node”的文章" target="_blank" class="tag_link">node</a> ./scripts/generateView/index"</span></code></pre> <p>如果使用 <code>npm</code> 的话 就是 <code>npm run new:view</code><br />如果是 <code>yarn</code> 自行修改命令</p> <hr> <h2 id="articleHeader6">1.4 结果</h2> <p><span class="img-wrap"><img data-src="/img/bVbnVml?w=779&amp;h=218" src="https://static.segmentfault.com/v-5cc2cd8e/global/img/squares.svg" alt="clipboard.png" title="clipboard.png" style="cursor: pointer;"></span></p> <p><span class="img-wrap"><img data-src="/img/bVbnVm0?w=286&amp;h=330" src="https://static.segmentfault.com/v-5cc2cd8e/global/img/squares.svg" alt="clipboard.png" title="clipboard.png" style="cursor: pointer;"></span></p> <p><span class="img-wrap"><img data-src="/img/bVbnVnE?w=497&amp;h=224" src="https://static.segmentfault.com/v-5cc2cd8e/global/img/squares.svg" alt="clipboard.png" title="clipboard.png" style="cursor: pointer;"></span></p> <p><span class="img-wrap"><img data-src="/img/bVbnVnw?w=499&amp;h=411" src="https://static.segmentfault.com/v-5cc2cd8e/global/img/squares.svg" alt="clipboard.png" title="clipboard.png" style="cursor: pointer;"></span></p> <hr> <p>稍后再补上生成公用component的代码,基本差不多,改吧改吧就行了<br /><span class="img-wrap"><img data-src="/img/bVbnVoX?w=240&amp;h=240" src="https://static.segmentfault.com/v-5cc2cd8e/global/img/squares.svg" alt="clipboard.png" title="clipboard.png" style="cursor: pointer;"></span></p>

本文固定链接: http://www.js-code.com/vue-js/vue-js_16787.html