是否将单文件.VUE组件转换为JavaScript? [英] Convert single-file .vue components to JavaScript?

查看:112
本文介绍了是否将单文件.VUE组件转换为JavaScript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有可以接受这样的.vue模板的工具:

<template>
  <div>Hello, {{ thing }}</div>
</template>

<script>
  export default {
    data() { return { thing: 'World' }; }
  }
</script>

<style>
  div { background: red; }
</style>

并将其转换为.js文件,如下所示:

export default {
  template: `
    <div>Hello {{ thing }}</div>
  `,
  data() {
    return {
      thing: 'World'
    }
  }
}

(不确定它对CSS有什么魔力,但它会做一些事情。)

我正在尝试使用本机浏览器模块,它们工作得很好,但是我想使用.vue文件语法,因为它提供了一些不错的功能。我希望避免使用webpack或Browserify这样的捆绑包。

我在用巴别塔。我有transform-vue-jsx插件,但它不能处理.vue格式,只能转换JSX。

推荐答案

您可以使用vue-template-compiler解析*.VUE文件并提取相关节。

我已经编写了一个节点脚本,它应该可以完成这项工作:

Convert.js

const compiler = require('vue-template-compiler');

let content = '';

process.stdin.resume();

process.stdin.on('data', buf => {
    content += buf.toString();
});

process.stdin.on('end', () => {
    const parsed = compiler.parseComponent(content);
    const template = parsed.template ? parsed.template.content : '';
    const script = parsed.script ? parsed.script.content : '';

    const templateEscaped = template.trim().replace(/`/g, '\`');
    const scriptWithTemplate = script.match(/export default ?{/)
        ? script.replace(/export default ?{/, `$&
	template: `
${templateEscaped}`,`)
        : `${script}
 export default {
	template: `
${templateEscaped}`};`;

    process.stdout.write(scriptWithTemplate);
});

要将所有*.VUE文件转换为*.vue.js,请在包含*.VUE文件的目录中运行以下bash命令(假设您使用的是Linux或MacOS):

find . -name '*.vue' -exec bash -c 'node convert.js < "{}" > "{}.js"' ;

这将导致以下转换:

foo.vue

<template>
    <div>a</div>
</template>

<script>
    export default {
        name: 'foo',
    };
</script>

<style>
    /* Won't be extracted */
</style>

foo.vue.js(生成)

export default {
    template: `
        <div>a</div>
    `,
    name: 'foo',
};

您可能希望调整脚本,使其处理提取样式(无论您希望如何处理)和修复空格等问题。

这篇关于是否将单文件.VUE组件转换为JavaScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆