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?
基础教程推荐
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
