如何运行一个vue文件进行预览

如何预览一个.vue文件进行预览呢?

每天写个页面,都要配置脚手架,能不能像以前开发前端页面一样,写一个index.html,然后编写js,css,就可以在浏览器上运行了呢?可是我又不想舍弃vue,那么能不能全局搭建一个脚手架,供我来使用呢?

今天翻阅文档,发现了官方文档给出了一个方案

安装

npm install -g @vue/cli @vue/cli-service-global
# or
yarn global add @vue/cli @vue/cli-service-global  

运行

vue serve MyComponent.vue  

是不是很方便~

看了下实现思路

1、自己编写了vue工程的模版

2、内置了一套默认的vue的配置

3、使用node执行命令

 

下面就开始自己撸代码,写了一个简版的:

首先我想要像node运行js文件一样,直接

pv run index.vue

读取文件内容 写入到APP.vue,添加到默认脚手架中,展示UI

program.command('run')
    .description('run a project')
    .action(async (name,router) => {
        // console.log(typeof router);
        if(typeof router === 'object'){
            sigleVue(name)
        }
    }) 

  

那么重点就是实现sigleVue.js

const filePath = path.join(process.env.PWD, name)
    const templateDir = path.join(__dirname, '../template')
    const templatePath = path.join(templateDir, 'src/App.vue')
    try {
        //热更新
        const content =
            `
                <template>
                    <div>
                        <Test></Test>
                    </div>
                </template>
                <script>
                import Test from '${filePath}'
                export default {
                    components:{
                        Test
                    }
                }
                </script>
                `
        await fs.writeFileSync(templatePath, content)
        //执行npm run dev 命令
        cd(templateDir)
        if (exec('npm run dev').code !== 0) {
            exit(1);
        }
    } catch (error) {
        console.error(error)
    }

 这样,我就可以像预览js文件一样预览vue文件了。

 

//代码放桌面
node ~/desktop/pv-cli/bin/index run index.vue  

是不是很简单。

ps:.vue文件下需要vue的npm包依赖

 

代码地址:

https://github.com/yiyibao/pv-cli

如果觉得文章不错,可以给小编发个红包给予鼓励.

posted @ 2020-01-31 19:25  地铁程序员  阅读(10930)  评论(0编辑  收藏  举报