我希望我的应用程序中的路线之一不要在服务器端渲染。
这样做的方法是export const ssr = false
在模块脚本或设置中ssr: false
in svelte.config.js
如中提到的精简文档 https://kit.svelte.dev/docs#ssr-and-javascript-ssr
但即使以两种方式禁用 ssr 后,我仍然在终端中收到错误,例如localStorage is not defined
禁用 ssr 后不应该出现该情况。
虽然应用程序仍然可以找到。但是每当我在浏览器中重新加载页面时,终端上就会出现此错误
[vite] Error when evaluating SSR module /src/routes/index.svelte:
ReferenceError: localStorage is not defined
svelte.config.js
import preprocess from 'svelte-preprocess';
import adapter from '@sveltejs/adapter-static';
/** @type {import('@sveltejs/kit').Config} */
const config = {
// Consult https://github.com/sveltejs/svelte-preprocess
// for more information about preprocessors
preprocess: preprocess(),
kit: {
ssr: false,
adapter: adapter({
fallback: '200.html'
}),
prerender: {
enabled: false
},
}
};
export default config;
索引.svelte
<script context="module" lang="ts">
export const ssr = false
</script>
<script lang="ts">
import Yrtc from "./../helpers/Yrtc";
import { onMount } from "svelte";
onMount(() => {
const yrtc = new Yrtc({
roomId: 'tet-riieiiasds-di'
})
console.log({yrtc})
})
</script>
test
变量如localStorage
, document
and self
未在服务器上定义。在里面使用这些变量onMount https://svelte.dev/docs/svelte#onmount仅当组件渲染后才在浏览器中运行的函数:
<script>
import { onMount } from 'svelte';
onMount(() => {
document.createElement(...);
// ...
});
</script>
Source: https://stackoverflow.com/a/56184892/9157799 https://stackoverflow.com/a/56184892/9157799
如果您要导入外部模块这取决于这些变量,使用import() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import在运行时加载模块的函数:
<script>
import { onMount } from 'svelte'
onMount(async () => {
const Plotly = await import('plotly.js-dist-min')
// ...
})
</script>
Source: https://stackoverflow.com/a/65452698/9157799 https://stackoverflow.com/a/65452698/9157799
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)