GAG*_*NGH 7 javascript server-side-rendering svelte sveltekit
我希望我的应用程序中的路线之一不要在服务器端渲染。执行此操作的方法将export const ssr = false在模块脚本中执行或ssr: false按照svelte 文档svelte.config.js中提到的设置进行设置
但即使以两种方式禁用 ssr 后,我仍然在终端中收到错误,例如localStorage is not defined禁用 ssr 时不应出现的错误。
虽然应用程序仍然可以找到。但是每当我在浏览器中重新加载页面时,终端上就会出现此错误
[vite] Error when evaluating SSR module /src/routes/index.svelte:
ReferenceError: localStorage is not defined
Run Code Online (Sandbox Code Playgroud)
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;
Run Code Online (Sandbox Code Playgroud)
索引.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
Run Code Online (Sandbox Code Playgroud)
M I*_*ama -1
localStorage、和document等变量self未在服务器上定义。onMount在渲染组件时仅在浏览器中运行的函数中使用这些变量:
<script>
import { onMount } from 'svelte';
onMount(() => {
document.createElement(...);
// ...
});
</script>
Run Code Online (Sandbox Code Playgroud)
来源:https ://stackoverflow.com/a/56184892/9157799
如果您要导入依赖于这些变量的外部模块import(),请使用该函数在运行时加载模块:
<script>
import { onMount } from 'svelte'
onMount(async () => {
const Plotly = await import('plotly.js-dist-min')
// ...
})
</script>
Run Code Online (Sandbox Code Playgroud)
来源:https ://stackoverflow.com/a/65452698/9157799