如果你有一个现有的JS应用,没有使用ESM、CJS,而只是一堆vanilla JS,你如何导出Svelte组件,从应用中随机的地方使用?我理想中的香草JS文件是这样的。
import AddressComponent from './AddressComponent.svelte';
import DifferentComponent from './DifferentComponent.svelte';
// ... my js app code
const address = new AddressComponent({target: ...});
// ... more vanilla JS code
const address = new DifferentComponent({target: ...});
// ... more vanilla JS code
或者即使没有导入,我也可以在其他地方将其作为一个列表来管理,以便在必要时单独生成Svelte组件。
使用rollup,似乎唯一的工作方式是指定'iife'。然而,这将我的整个应用程序捆绑为一个IIFE,并打破了许多代码重命名的东西,等等。似乎没有办法解决这个问题。
我使用这个方法得到了很好的编译组件 从Svelte Components中导出单独的自定义元素。然而,生成esm或cjs svelte组件。可能有一个工具可以轻松地将这种格式转换为vanilla JS?我已经搜索过了,没有找到
我用过很多组合设置,gulp和rollup一起用,都没有成功。
在 bundle.js
由svelte创建的自动导出 app
浏览器的根组件(除非您更改其名称)。
你可以写在你的 bundle.js
前面 return app;
语句的下面一行。
app.Child = Child // or whatever your component is called
然后在你的javascript中
var child = new app.Child({ target: document.body });
使用你想要的道具。
你的HTML页面最终应该是这样的。
<script src="public/build/bundle.js"></script>
<link href="public/build/bundle.css" rel='stylesheet'></link>
<script>
var child = new app.Child({ target: document.body });
</script>