问题描述
我一直在尝试加载 ace 编辑器 (https://ace.c9.io/)进入我的 Sapper 应用程序.当我在 Sapper 路由中加载它时,我在脚本标签中成功加载了它,但是当我尝试在 Svelte 组件中执行相同的操作时,该组件再次由路由呈现,我收到错误:
ace 未定义
这是我的代码,如果它是 Sapper 路线,它工作正常:
定义主():返回总和(范围(1,100))
<script src="https://pagecdn.io/lib/ace/1.4.6/ace.js" type="text/javascript" charset="utf-8"></script><脚本>var editor = ace.edit("editor");editor.setTheme("ace/theme/monokai");editor.session.setMode("ace/mode/python");editor.resize()
当我第一次开始使用 Svelte2 时,我编写了一个组件来加载外部遗留 JS 库,然后将其重构为 Svelte 3.
//LibLoader.svelte<苗条:头><脚本绑定:this={script} src={url}/></svelte:head><脚本>import { onMount, createEventDispatcher } from 'svelte';const dispatch = createEventDispatcher();导出让网址;让脚本;onMount(async () => {script.addEventListener('load', () => {dispatch('加载');})script.addEventListener('error', (event) => {console.error("出了点问题", event);调度('错误');});});
//MyComponent.svelte<LibLoader url="myExternalLib.js"on:loaded="{onLoaded}"/><脚本>从'./LibLoader.svelte'导入LibLoader;函数 onLoaded() {myExternalLib.doStuff();}
这没有经过彻底的测试,一次性使用可能不保证单独的组件;但基本上这种方法解决了 Rich Harris 提到的时间问题.现在import
显然是更好的选择,如果有的话.
I have been trying to load the ace editor (https://ace.c9.io/) into my Sapper application. I had success loading it in the script tag when I loaded it in a Sapper route, but when I am trying to do the same in a Svelte component which is again rendered by a route I get the error:
ace is not defined
This is the code I have, which is working fine if it is a Sapper route:
<div id="editor"> def main():
return sum(range(1,100))
</div>
<script src="https://pagecdn.io/lib/ace/1.4.6/ace.js" type="text/javascript" charset="utf-8"></script>
<script>
var editor = ace.edit("editor");
editor.setTheme("ace/theme/monokai");
editor.session.setMode("ace/mode/python");
editor.resize()
</script>
I hacked together a component to load external legacy JS libraries when I first started playing with Svelte2 and just refactored it to Svelte 3.
// LibLoader.svelte
<svelte:head>
<script bind:this={script} src={url} />
</svelte:head>
<script>
import { onMount, createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
export let url;
let script;
onMount(async () => {
script.addEventListener('load', () => {
dispatch('loaded');
})
script.addEventListener('error', (event) => {
console.error("something went wrong", event);
dispatch('error');
});
});
</script>
// MyComponent.svelte
<LibLoader url="myExternalLib.js"
on:loaded="{onLoaded}" />
<script>
import LibLoader from './LibLoader.svelte';
function onLoaded() {
myExternalLib.doStuff();
}
</script>
This is not thoroughly tested and for a one-off probably doesn't warrant a separate component; but basically the approach gets round the timing issue Rich Harris mentions. These days import
is obviously the better option if it is available.
这篇关于如何在 Svelte/Sapper 中加载外部 JS 库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!