英文:
Cannot import $lib/server/db.ts into client-side code
问题
我使用npm create svelte@latest my-app
进行了全新安装SvelteKit,
然后进行npm install
,我添加了npm install pg
来使PostgreSQL工作。我创建了一个名为todos
的数据库和一个名为items
的表;
在svelte
代码库中的src
目录下:
routes/+page.ts
:
import { getList } from "$lib/server/db";
export async function load() {
const list = await getList()
return {
test: JSON.stringify(list)
};
}
routes/+page.svelte
:
<script lang="ts">
export let data: { test: string };
</script>
{data.test}
lib/server/db.ts
:
import { Client } from 'pg';
const client = new Client({ 'database': 'todos' })
await client.connect()
export async function getList() {
return await client.query('select * from items')
}
当我尝试加载页面时,终端和浏览器中都出现以下错误:
[vite] Internal server error: Cannot import $lib/server/db.ts into client-side code
在浏览器中,我可以单击消息外部以将其关闭,然后得到预期的输出。
我在设置中做错了吗?
英文:
I have a fresh install of sveltekit using npm create svelte@latest my-app
and after doing npm install, I added npm install pg
to get postgres working. I created a database called todos
and a table called items
;
In the svelte codebase under src
:
routes/+page.ts
:
import { getList } from "$lib/server/db";
export async function load() {
const list = await getList()
return {
test: JSON.stringify(list)
};
}
routes/+page.svelte
:
<script lang="ts">
export let data: { test: string };
</script>
{data.test}
lib/server/db.ts
:
import { Client } from 'pg';
const client = new Client({ 'database': 'todos' })
await client.connect()
export async function getList() {
return await client.query('select * from items')
}
When I try to load the page I get this error in the terminal and the browser:
[vite] Internal server error: Cannot import $lib/server/db.ts into client-side code
On the browser I can click outside of the message to dismiss it, and I end up getting the output to print as expected.
Am I doing something wrong with my setup?
答案1
得分: 1
只需将您的 +page.ts
重命名为 +page.server.ts
,就可以确保此代码仅在后端运行。
请参考它们文档中的 Universal vs server 部分。
只需重命名 TypeScript 文件即可,不需要更改 Svelte 文件。
如果您实际上想要从前端连接到数据库,那么您需要通过 API 调用来连接。
--- 更新 ---
此外,我认为您可能遇到了 server modules protection。基本上,SvelteKit 理解您放在 $lib/server
下的任何内容都仅用于服务器端,因此会自动阻止在客户端代码中的任何使用。
英文:
I suspect you want this code to be run on the backend side only. For this, you just need to rename your +page.ts
into +page.server.ts
.
Take a look at the Universal vs server section in their documentation.
Just renaming the typescript file should be enough to get it working. You don't need to change the svelte file.
If you actually want to connect to the DB from the frontend, then you will need to connect via API calls.
--- Update ---
In addition to this, I think you stumbled into the server modules protection. Basically, SvelteKit understands that anything you place under $lib/server
is meant to be used on the server side only so it will automatically prevent any usage on client code.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论