将单文件.vue组件转换为JavaScript?

sam*_*ime 11 javascript babel vue.js

有没有可以采用这样的.vue模板的工具:

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

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

<style>
  div { background: red; }
</style>
Run Code Online (Sandbox Code Playgroud)

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

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

(不确定它对CSS有什么魔力,但它会做点什么.)

我正在尝试使用本机浏览器模块,它运行良好,但我想使用.vue文件语法,因为它提供了一些不错的东西.我想避免使用像Webpack或Browserify这样的捆绑器.

我正在使用巴别塔.我有transform-vue-jsx插件,但无法处理.vue格式,只能转换JSX.

Dec*_*oon 6

您可以使用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 ?\{/, `$&\n\ttemplate: \`\n${templateEscaped}\`,`)
        : `${script}\n export default {\n\ttemplate: \`\n${templateEscaped}\`};`;

    process.stdout.write(scriptWithTemplate);
});
Run Code Online (Sandbox Code Playgroud)

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

find . -name '*.vue' -exec bash -c 'node convert.js < "{}" > "{}.js"' \;
Run Code Online (Sandbox Code Playgroud)

这将导致以下转换:

foo.vue

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

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

<style>
    /* Won't be extracted */
</style>
Run Code Online (Sandbox Code Playgroud)

foo.vue.js(生成)

export default {
    template: `
        <div>a</div>
    `,
    name: 'foo',
};
Run Code Online (Sandbox Code Playgroud)

你可能想要调整脚本,以便它处理提取样式(但是你想要处理它)并修复空白和类似的东西.