Convert single-file .vue components to JavaScript?(是否将单文件.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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是否将单文件.VUE组件转换为JavaScript?


- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01