Skip to main content

常见问题

其他资源(Other resources)

¥Other resources

请参阅 Svelte 常见问题解答vite-plugin-svelte FAQ,了解来自这些库的问题的答案。

¥Please see the Svelte FAQ and vite-plugin-svelte FAQ as well for the answers to questions deriving from those libraries.

我可以用 SvelteKit 做什么?(What can I make with SvelteKit?)

¥What can I make with SvelteKit?

有关更多详细信息,请参阅 有关项目类型的文档

¥See the documentation regarding project types for more details.

如何在我的应用中包含 package.json 中的详细信息?(How do I include details from package.json in my application?)

¥How do I include details from package.json in my application?

你不能直接需要 JSON 文件,因为 SvelteKit 要求 svelte.config.js 是 ES 模块。如果你想在应用中包含应用的版本号或来自 package.json 的其他信息,可以像这样加载 JSON:

¥You cannot directly require JSON files, since SvelteKit expects svelte.config.js to be an ES module. If you’d like to include your application’s version number or other information from package.json in your application, you can load JSON like so:

svelte.config
import { 
function readFileSync(path: PathOrFileDescriptor, options?: {
    encoding?: null | undefined;
    flag?: string | undefined;
} | null): Buffer (+2 overloads)

Returns the contents of the path.

For detailed information, see the documentation of the asynchronous version of this API: {@link readFile } .

If the encoding option is specified then this function returns a string. Otherwise it returns a buffer.

Similar to {@link readFile } , when the path is a directory, the behavior of fs.readFileSync() is platform-specific.

import { readFileSync } from 'node:fs';

// macOS, Linux, and Windows
readFileSync('<directory>');
// => [Error: EISDIR: illegal operation on a directory, read <directory>]

//  FreeBSD
readFileSync('<directory>'); // => <data>
@sincev0.1.8
@parampath filename or file descriptor
readFileSync
} from 'node:fs';
import { function fileURLToPath(url: string | URL, options?: FileUrlToPathOptions): string

This function ensures the correct decodings of percent-encoded characters as well as ensuring a cross-platform valid absolute path string.

import { fileURLToPath } from 'node:url';

const __filename = fileURLToPath(import.meta.url);

new URL('file:///C:/path/').pathname;      // Incorrect: /C:/path/
fileURLToPath('file:///C:/path/');// Correct:   C:\path\ (Windows)

new URL('file://nas/foo.txt').pathname;    // Incorrect: /foo.txt
fileURLToPath('file://nas/foo.txt');       // Correct:   \\nas\foo.txt (Windows)

new URL('file:///你好.txt').pathname;      // Incorrect: /%E4%BD%A0%E5%A5%BD.txt
fileURLToPath('file:///你好.txt');// Correct:   /你好.txt (POSIX)

new URL('file:///hello world').pathname;   // Incorrect: /hello%20world
fileURLToPath('file:///hello world');      // Correct:   /hello world (POSIX)
@sincev10.12.0
@paramurl The file URL string or URL object to convert to a path.
@returnThe fully-resolved platform-specific Node.js file path.
fileURLToPath
} from 'node:url';
const const path: stringpath = function fileURLToPath(url: string | URL, options?: FileUrlToPathOptions): string

This function ensures the correct decodings of percent-encoded characters as well as ensuring a cross-platform valid absolute path string.

import { fileURLToPath } from 'node:url';

const __filename = fileURLToPath(import.meta.url);

new URL('file:///C:/path/').pathname;      // Incorrect: /C:/path/
fileURLToPath('file:///C:/path/');// Correct:   C:\path\ (Windows)

new URL('file://nas/foo.txt').pathname;    // Incorrect: /foo.txt
fileURLToPath('file://nas/foo.txt');       // Correct:   \\nas\foo.txt (Windows)

new URL('file:///你好.txt').pathname;      // Incorrect: /%E4%BD%A0%E5%A5%BD.txt
fileURLToPath('file:///你好.txt');// Correct:   /你好.txt (POSIX)

new URL('file:///hello world').pathname;   // Incorrect: /hello%20world
fileURLToPath('file:///hello world');      // Correct:   /hello world (POSIX)
@sincev10.12.0
@paramurl The file URL string or URL object to convert to a path.
@returnThe fully-resolved platform-specific Node.js file path.
fileURLToPath
(new
new URL(input: string | {
    toString: () => string;
}, base?: string | URL): URL

Browser-compatible URL class, implemented by following the WHATWG URL Standard. Examples of parsed URLs may be found in the Standard itself. The URL class is also available on the global object.

In accordance with browser conventions, all properties of URL objects are implemented as getters and setters on the class prototype, rather than as data properties on the object itself. Thus, unlike legacy urlObjects, using the delete keyword on any properties of URL objects (e.g. delete myURL.protocol, delete myURL.pathname, etc) has no effect but will still return true.

@sincev7.0.0, v6.13.0
URL
('package.json', import.meta.ImportMeta.url: string

The absolute file: URL of the module.

url
));
const const pkg: anypkg = var JSON: JSON

An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.

JSON
.JSON.parse(text: string, reviver?: (this: any, key: string, value: any) => any): any

Converts a JavaScript Object Notation (JSON) string into an object.

@paramtext A valid JSON string.
@paramreviver A function that transforms the results. This function is called for each member of the object. If a member contains nested objects, the nested objects are transformed before the parent object is.
parse
(
function readFileSync(path: PathOrFileDescriptor, options: {
    encoding: BufferEncoding;
    flag?: string | undefined;
} | BufferEncoding): string (+2 overloads)

Synchronously reads the entire contents of a file.

@parampath A path to a file. If a URL is provided, it must use the file: protocol. If a file descriptor is provided, the underlying file will not be closed automatically.
@paramoptions Either the encoding for the result, or an object that contains the encoding and an optional flag. If a flag is not provided, it defaults to 'r'.
readFileSync
(const path: stringpath, 'utf8'));

如何修复尝试包含包时出现的错误?(How do I fix the error I’m getting trying to include a package?)

¥How do I fix the error I’m getting trying to include a package?

大多数与包含库相关的问题都是由于打包不正确造成的。你可以通过将库的打包输入 publint 网站 来检查它是否与 Node.js 兼容。

¥Most issues related to including a library are due to incorrect packaging. You can check if a library’s packaging is compatible with Node.js by entering it into the publint website.

检查库是否正确打包时,请记住以下几点:

¥Here are a few things to keep in mind when checking if a library is packaged correctly:

  • exports 优先于其他入口点字段,例如 mainmodule。添加 exports 字段可能不向后兼容,因为它会阻止深度导入。

    ¥exports takes precedence over the other entry point fields such as main and module. Adding an exports field may not be backwards-compatible as it prevents deep imports.

  • ESM 文件应以 .mjs 结尾,除非设置了 "type": "module",在这种情况下,CommonJS 文件应以 .cjs 结尾。

    ¥ESM files should end with .mjs unless "type": "module" is set in which any case CommonJS files should end with .cjs.

  • 如果 exports 没有定义,则应该定义 main。它应该是 CommonJS 或 ESM 文件,并遵守上一个项目符号。如果定义了 module 字段,则它应该引用 ESM 文件。

    ¥main should be defined if exports is not. It should be either a CommonJS or ESM file and adhere to the previous bullet. If a module field is defined, it should refer to an ESM file.

  • Svelte 组件应作为未编译的 .svelte 文件分发,包中的任何 JS 都仅以 ESM 形式编写。自定义脚本和样式语言(如 TypeScript 和 SCSS)应分别预处理为原始 JS 和 CSS。我们建议使用 svelte-package 来打包 Svelte 库,它会为你完成此操作。

    ¥Svelte components should be distributed as uncompiled .svelte files with any JS in the package written as ESM only. Custom script and style languages, like TypeScript and SCSS, should be preprocessed as vanilla JS and CSS respectively. We recommend using svelte-package for packaging Svelte libraries, which will do this for you.

当库分发 ESM 版本时,它们在浏览器中与 Vite 配合使用效果最佳,尤其是当它们是 Svelte 组件库的依赖时。你可能希望建议库作者提供 ESM 版本。但是,CommonJS (CJS) 依赖也应该可以工作,因为默认情况下,vite-plugin-svelte 将要求 Vite 预先打包它们 使用 esbuild 将它们转换为 ESM。

¥Libraries work best in the browser with Vite when they distribute an ESM version, especially if they are dependencies of a Svelte component library. You may wish to suggest to library authors that they provide an ESM version. However, CommonJS (CJS) dependencies should work as well since, by default, vite-plugin-svelte will ask Vite to pre-bundle them using esbuild to convert them to ESM.

如果你仍然遇到问题,我们建议你同时搜索 Vite 问题跟踪器 和相关库的问题跟踪器。有时可以通过摆弄 optimizeDepsssr 配置值来解决问题,但我们建议这只是一个短期解决方法,以修复有问题的库。

¥If you are still encountering issues we recommend searching both the Vite issue tracker and the issue tracker of the library in question. Sometimes issues can be worked around by fiddling with the optimizeDeps or ssr config values though we recommend this as only a short-term workaround in favor of fixing the library in question.

如何使用视图转换 API?(How do I use the view transitions API?)

¥How do I use the view transitions API?

虽然 SvelteKit 与 查看转换 没有任何特定的集成,但你可以在 onNavigate 中调用 document.startViewTransition 以在每个客户端导航上触发视图转换。

¥While SvelteKit does not have any specific integration with view transitions, you can call document.startViewTransition in onNavigate to trigger a view transition on every client-side navigation.

import { function onNavigate(callback: (navigation: import("@sveltejs/kit").OnNavigate) => MaybePromise<void | (() => void)>): void

A lifecycle function that runs the supplied callback immediately before we navigate to a new URL except during full-page navigations.

If you return a Promise, SvelteKit will wait for it to resolve before completing the navigation. This allows you to — for example — use document.startViewTransition. Avoid promises that are slow to resolve, since navigation will appear stalled to the user.

If a function (or a Promise that resolves to a function) is returned from the callback, it will be called once the DOM has updated.

onNavigate must be called during a component initialization. It remains active as long as the component is mounted.

onNavigate
} from '$app/navigation';
function onNavigate(callback: (navigation: import("@sveltejs/kit").OnNavigate) => MaybePromise<void | (() => void)>): void

A lifecycle function that runs the supplied callback immediately before we navigate to a new URL except during full-page navigations.

If you return a Promise, SvelteKit will wait for it to resolve before completing the navigation. This allows you to — for example — use document.startViewTransition. Avoid promises that are slow to resolve, since navigation will appear stalled to the user.

If a function (or a Promise that resolves to a function) is returned from the callback, it will be called once the DOM has updated.

onNavigate must be called during a component initialization. It remains active as long as the component is mounted.

onNavigate
((navigation: OnNavigatenavigation) => {
if (!var document: Documentdocument.startViewTransition) return; return new
var Promise: PromiseConstructor
new <void | (() => void)>(executor: (resolve: (value: void | (() => void) | PromiseLike<void | (() => void)>) => void, reject: (reason?: any) => void) => void) => Promise<void | (() => void)>

Creates a new Promise.

@paramexecutor A callback used to initialize the promise. This callback is passed two arguments: a resolve callback used to resolve the promise with a value or the result of another promise, and a reject callback used to reject the promise with a provided reason or error.
Promise
((resolve: (value: void | (() => void) | PromiseLike<void | (() => void)>) => voidresolve) => {
var document: Documentdocument.startViewTransition(async () => { resolve: (value: void | (() => void) | PromiseLike<void | (() => void)>) => voidresolve(); await navigation: OnNavigatenavigation.Navigation.complete: Promise<void>

A promise that resolves once the navigation is complete, and rejects if the navigation fails or is aborted. In the case of a willUnload navigation, the promise will never resolve

complete
;
}); }); });

有关更多信息,请参阅 Svelte 博客上的 “解锁视图转换”

¥For more, see “Unlocking view transitions” on the Svelte blog.

如何设置数据库?(How do I set up a database?)

¥How do I set up a database?

将查询数据库的代码放在 服务器路由 中 - 不要在 .svelte 文件中查询数据库。你可以创建一个 db.js 或类似的东西,立即建立连接并使客户端可以作为单例在整个应用中访问。你可以在 hooks.server.js 中执行任何一次性设置代码,并将数据库助手导入任何需要它们的端点。

¥Put the code to query your database in a server route - don’t query the database in .svelte files. You can create a db.js or similar that sets up a connection immediately and makes the client accessible throughout the app as a singleton. You can execute any one-time setup code in hooks.server.js and import your database helpers into any endpoint that needs them.

你可以使用 Svelte CLI 自动设置数据库集成。

¥You can use the Svelte CLI to automatically set up database integrations.

如何使用访问 document 或 window 的客户端库?(How do I use a client-side library accessing document or window?)

¥How do I use a client-side library accessing document or window?

如果你需要访问 documentwindow 变量,或者需要仅在客户端运行代码,则可以将其封装在 browser 检查中:

¥If you need access to the document or window variables or otherwise need code to run only on the client-side you can wrap it in a browser check:

import { const browser: boolean

true if the app is running in the browser.

browser
} from '$app/environment';
if (const browser: boolean

true if the app is running in the browser.

browser
) {
// client-only code here }

如果你想在组件首次渲染到 DOM 后运行代码,也可以在 onMount 中运行代码:

¥You can also run code in onMount if you’d like to run it after the component has been first rendered to the DOM:

import { function onMount<T>(fn: () => NotFunction<T> | Promise<NotFunction<T>> | (() => any)): void

The onMount function schedules a callback to run as soon as the component has been mounted to the DOM. It must be called during the component’s initialisation (but doesn’t need to live inside the component; it can be called from an external module).

If a function is returned synchronously from onMount, it will be called when the component is unmounted.

onMount does not run inside server-side components.

onMount
} from 'svelte';
onMount<void>(fn: () => void | (() => any) | Promise<void>): void

The onMount function schedules a callback to run as soon as the component has been mounted to the DOM. It must be called during the component’s initialisation (but doesn’t need to live inside the component; it can be called from an external module).

If a function is returned synchronously from onMount, it will be called when the component is unmounted.

onMount does not run inside server-side components.

onMount
(async () => {
const { const method: anymethod } = await import('some-browser-only-library'); const method: anymethod('hello world'); });

如果你想要使用的库没有副作用,你也可以静态导入它,它将在服务器端构建中被 tree-shaking 掉,其中 onMount 将自动替换为无操作:

¥If the library you’d like to use is side-effect free you can also statically import it and it will be tree-shaken out in the server-side build where onMount will be automatically replaced with a no-op:

import { function onMount<T>(fn: () => NotFunction<T> | Promise<NotFunction<T>> | (() => any)): void

The onMount function schedules a callback to run as soon as the component has been mounted to the DOM. It must be called during the component’s initialisation (but doesn’t need to live inside the component; it can be called from an external module).

If a function is returned synchronously from onMount, it will be called when the component is unmounted.

onMount does not run inside server-side components.

onMount
} from 'svelte';
import { module "some-browser-only-library"method } from 'some-browser-only-library'; onMount<void>(fn: () => void | (() => any) | Promise<void>): void

The onMount function schedules a callback to run as soon as the component has been mounted to the DOM. It must be called during the component’s initialisation (but doesn’t need to live inside the component; it can be called from an external module).

If a function is returned synchronously from onMount, it will be called when the component is unmounted.

onMount does not run inside server-side components.

onMount
(() => {
module "some-browser-only-library"method('hello world'); });

最后,你也可以考虑使用 {#await} 块:

¥Finally, you may also consider using an {#await} block:

index
<script>
	import { browser } from '$app/environment';

	const ComponentConstructor = browser ?
		import('some-browser-only-library').then((module) => module.Component) :
		new Promise(() => {});
</script>

{#await ComponentConstructor}
	<p>Loading...</p>
{:then component}
	<svelte:component this={component} />
{:catch error}
	<p>Something went wrong: {error.message}</p>
{/await}
<script lang="ts">
	import { browser } from '$app/environment';

	const ComponentConstructor = browser ?
		import('some-browser-only-library').then((module) => module.Component) :
		new Promise(() => {});
</script>

{#await ComponentConstructor}
	<p>Loading...</p>
{:then component}
	<svelte:component this={component} />
{:catch error}
	<p>Something went wrong: {error.message}</p>
{/await}

如何使用不同的后端 API 服务器?(How do I use a different backend API server?)

¥How do I use a different backend API server?

你可以使用 event.fetch 从外部 API 服务器请求数据,但请注意,你需要处理 CORS,这会导致一些复杂情况,例如通常需要对请求进行预检,从而导致更高的延迟。由于额外的 DNS 查找、TLS 设置等,对单独子域的请求也可能会增加延迟。如果你希望使用此方法,你可能会发现 handleFetch 很有帮助。

¥You can use event.fetch to request data from an external API server, but be aware that you would need to deal with CORS, which will result in complications such as generally requiring requests to be preflighted resulting in higher latency. Requests to a separate subdomain may also increase latency due to an additional DNS lookup, TLS setup, etc. If you wish to use this method, you may find handleFetch helpful.

动画可以使用提供 、 对象和任何 作为参数的自定义函数。在生产中,你需要将路径(如 /api)重写到 API 服务器;对于本地开发,请使用 Vite 的 server.proxy 选项。

¥Another approach is to set up a proxy to bypass CORS headaches. In production, you would rewrite a path like /api to the API server; for local development, use Vite’s server.proxy option.

如何在生产中设置重写将取决于你的部署平台。如果重写不是一种选择,你可以选择添加 API 路由

¥How to setup rewrites in production will depend on your deployment platform. If rewrites aren’t an option, you could alternatively add an API route:

src/routes/api/[...path]/+server
/** @type {import('./$types').RequestHandler} */
export function 
function GET({ params, url }: {
    params: any;
    url: any;
}): Promise<Response>
@type{import('./$types').RequestHandler}
GET
({ params: anyparams, url: anyurl }) {
return function fetch(input: string | URL | globalThis.Request, init?: RequestInit): Promise<Response> (+1 overload)fetch(`https://my-api-server.com/${params: anyparams.path + url: anyurl.search}`); }
import type { 
type RequestHandler = (event: Kit.RequestEvent<Record<string, any>, string | null>) => MaybePromise<Response>
type RequestHandler = (event: Kit.RequestEvent<Record<string, any>, string | null>) => MaybePromise<Response>
RequestHandler
} from './$types';
export const const GET: RequestHandlerGET:
type RequestHandler = (event: Kit.RequestEvent<Record<string, any>, string | null>) => MaybePromise<Response>
type RequestHandler = (event: Kit.RequestEvent<Record<string, any>, string | null>) => MaybePromise<Response>
RequestHandler
= ({ params: Record<string, any>

The parameters of the current route - e.g. for a route like /blog/[slug], a { slug: string } object

params
, url: URL

The requested URL.

url
}) => {
return function fetch(input: string | URL | globalThis.Request, init?: RequestInit): Promise<Response> (+1 overload)fetch(`https://my-api-server.com/${params: Record<string, any>

The parameters of the current route - e.g. for a route like /blog/[slug], a { slug: string } object

params
.path + url: URL

The requested URL.

url
.URL.search: stringsearch}`);
};

(请注意,你可能还需要代理 POST / PATCH 等请求,并转发 request.headers,具体取决于你的需要。)

¥(Note that you may also need to proxy POST / PATCH etc requests, and forward request.headers, depending on your needs.)

如何使用中间件?(How do I use middleware?)

¥How do I use middleware?

adapter-node 构建了一个中间件,你可以在自己的服务器上将其用于生产模式。在开发中,你可以使用 Vite 插件向 Vite 添加中间件。例如:

¥adapter-node builds a middleware that you can use with your own server for production mode. In dev, you can add middleware to Vite by using a Vite plugin. For example:

import { module "@sveltejs/kit/vite"sveltekit } from '@sveltejs/kit/vite';

/** @type {import('vite').Plugin} */
const const myPlugin: Plugin<any>
@type{import('vite').Plugin}
myPlugin
= {
OutputPlugin.name: stringname: 'log-request-middleware', Plugin<any>.configureServer?: ObjectHook<ServerHook> | undefined

Configure the vite server. The hook receives the {@link ViteDevServer }

instance. This can also be used to store a reference to the server for use in other hooks.

The hooks will be called before internal middlewares are applied. A hook can return a post hook that will be called after internal middlewares are applied. Hook can be async functions and will be called in series.

configureServer
(server: ViteDevServerserver) {
server: ViteDevServerserver.ViteDevServer.middlewares: Connect.Server

A connect app instance.

  • Can be used to attach custom middlewares to the dev server.
  • Can also be used as the handler function of a custom http server or as a middleware in any connect-style Node.js frameworks

https://github.com/senchalabs/connect#use-middleware

middlewares
.Connect.Server.use(fn: Connect.NextHandleFunction): Connect.Server (+3 overloads)

Utilize the given middleware handle to the given route, defaulting to /. This “route” is the mount-point for the middleware, when given a value other than / the middleware is only effective when that segment is present in the request’s pathname.

For example if we were to mount a function at /admin, it would be invoked on /admin, and /admin/settings, however it would not be invoked for /, or /posts.

use
((req: Connect.IncomingMessagereq, res: ServerResponse<IncomingMessage>res, next: Connect.NextFunctionnext) => {
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without calling require('console').

Warning: The global console object’s methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
//   Error: Whoops, something bad happened
//     at [eval]:5:15
//     at Script.runInThisContext (node:vm:132:18)
//     at Object.runInThisContext (node:vm:309:38)
//     at node:internal/process/execution:77:19
//     at [eval]-wrapper:6:22
//     at evalScript (node:internal/process/execution:76:60)
//     at node:internal/main/eval_string:23:3

const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);

myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err

const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
@seesource
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100
log
(`Got request ${req: Connect.IncomingMessagereq.IncomingMessage.url?: string | undefined

Only valid for request obtained from {@link Server } .

Request URL string. This contains only the URL that is present in the actual HTTP request. Take the following request:

GET /status?name=ryan HTTP/1.1
Accept: text/plain

To parse the URL into its parts:

new URL(`http://${process.env.HOST ?? 'localhost'}${request.url}`);

When request.url is '/status?name=ryan' and process.env.HOST is undefined:

$ node
> new URL(`http://${process.env.HOST ?? 'localhost'}${request.url}`);
URL {
  href: 'http://localhost/status?name=ryan',
  origin: 'http://localhost',
  protocol: 'http:',
  username: '',
  password: '',
  host: 'localhost',
  hostname: 'localhost',
  port: '',
  pathname: '/status',
  search: '?name=ryan',
  searchParams: URLSearchParams { 'name' => 'ryan' },
  hash: ''
}

Ensure that you set process.env.HOST to the server’s host name, or consider replacing this part entirely. If using req.headers.host, ensure proper validation is used, as clients may specify a custom Host header.

@sincev0.1.90
url
}`);
next: (err?: any) => voidnext(); }); } }; /** @type {import('vite').UserConfig} */ const const config: UserConfig
@type{import('vite').UserConfig}
config
= {
UserConfig.plugins?: PluginOption[] | undefined

Array of vite plugins to use.

plugins
: [const myPlugin: Plugin<any>
@type{import('vite').Plugin}
myPlugin
, module "@sveltejs/kit/vite"sveltekit()]
}; export default const config: UserConfig
@type{import('vite').UserConfig}
config
;

有关更多详细信息,包括如何控制排序,请参阅 Vite 的 configureServer 文档

¥See Vite’s configureServer docs for more details including how to control ordering.

如何使用 Yarn?(How do I use Yarn?)

¥How do I use Yarn?

它能与 Yarn 2 配合使用吗?(Does it work with Yarn 2?)

¥Does it work with Yarn 2?

有点。Plug’n'Play 功能(又名 ‘pnp’)已损坏(它偏离了 Node 模块解析算法和 SvelteKit(以及 增加软件包数量)使用的 尚无法与原生 JavaScript 模块一起使用)。你可以在 .yarnrc.yml 文件中使用 nodeLinker: 'node-modules' 来禁用 pnp,但使用 npm 或 pnpm 可能更容易,它们同样快速高效,但没有兼容性问题。

¥Sort of. The Plug’n'Play feature, aka ‘pnp’, is broken (it deviates from the Node module resolution algorithm, and doesn’t yet work with native JavaScript modules which SvelteKit — along with an increasing number of packages — uses). You can use nodeLinker: 'node-modules' in your .yarnrc.yml file to disable pnp, but it’s probably easier to just use npm or pnpm, which is similarly fast and efficient but without the compatibility headaches.

如何与 Yarn 3 结合使用?(How do I use with Yarn 3?)

¥How do I use with Yarn 3?

目前,最新 Yarn(版本 3)中的 ESM 支持被视为 experimental

¥Currently ESM Support within the latest Yarn (version 3) is considered experimental.

下面的方法似乎有效,但你的结果可能会有所不同。

¥The below seems to work although your results may vary.

首先创建一个新的应用:

¥First create a new application:

yarn create svelte myapp
cd myapp

并启用 Yarn Berry:

¥And enable Yarn Berry:

yarn set version berry
yarn install

Yarn 3 全局缓存(Yarn 3 global cache)

¥Yarn 3 global cache

Yarn Berry 更有趣的功能之一是能够为包提供单个全局缓存,而不是在磁盘上为每个项目提供多个副本。但是,将 enableGlobalCache 设置为 true 会导致构建失败,因此建议将以下内容添加到 .yarnrc.yml 文件中:

¥One of the more interesting features of Yarn Berry is the ability to have a single global cache for packages, instead of having multiple copies for each project on the disk. However, setting enableGlobalCache to true causes building to fail, so it is recommended to add the following to the .yarnrc.yml file:

nodeLinker: node-modules

这将导致将包下载到本地 node_modules 目录中,但避免了上述问题,并且是目前使用 Yarn 版本 3 的最佳选择。

¥This will cause packages to be downloaded into a local node_modules directory but avoids the above problem and is your best bet for using version 3 of Yarn at this point in time.

上一页 下一页