我目前正在为下一个项目使用Svelte 3探索Bucklescript / ReasonML。典型的Svelte组件是一个.svelte文件:
<script>
let name = 'world';
</script>
<h1>Hello world!</h1>
Run Code Online (Sandbox Code Playgroud)
取而代之的是,我可以script使用带有src或等效标记的代码将JS代码保存在单独的文件中吗?
<script src='./some-file.js'></script>
Run Code Online (Sandbox Code Playgroud)
通过将js代码移动到单独的文件中,可以将Bucklescript编译器的目标(是JS文件)用于该组件。
Vue.js的SFC .vue文件已支持此功能。
附带说明:我可以为此使用Vue.js,但是存在虚拟DOM对于遗留代码库是有问题的。而且,Svelte在运行时正在减少,因此非常可取。另外,
this在Vue中使用该功能会使Ocaml / Reason感到尴尬。
使用svelte.preprocess API 可以实现此功能,最常用的方法是通过preprocessrollup-plugin-svelte或svelte-loader中的选项来访问。这样的事情应该可以工作(尽管我还没有测试过):
plugins: [
svelte({
// ...
preprocess: {
script: ({ content, attributes, filename }) => {
if (attributes.src) {
const file = path.resolve(attributes.src, path.dirname(filename));
const code = fs.readFileSync(file, 'utf-8');
return { code };
}
}
}
})
]
Run Code Online (Sandbox Code Playgroud)