项目结构

一个典型的 Qwik 项目的结构如下所示:

qwik-app-demo
├── README.md
├── package.json
├── public
   └── favicon.svg
├── src
   ├── components
      └── router-head
          └── router-head.tsx
   ├── entry.ssr.tsx
   ├── global.css
   ├── root.tsx
   └── routes
       ├── flower
          ├── flower.css
          └── index.tsx
       ├── index.tsx
       ├── layout.tsx
       └── service-worker.ts
├── tsconfig.json
└── vite.config.ts

项目文件

src/routes/

src/routes/ 目录是 Qwik City 的特殊目录,因为它是 Qwik City 查找页面的目录。该目录中的文件和文件夹具有特殊含义,并将映射到应用的 URL。

  • src/routes/index.tsx 是应用的首页。
  • src/routes/layout.tsx 是应用的根布局,所有页面都将在此布局中呈现。

有关更多信息,请参阅路由部分。

src/components/

src/components/ 目录是按照约定的目录。所有的 Qwik 起始模板都会有这个目录,但你可以根据需要进行更改。这个目录是用来放置组件的,即可在多个地方重复使用的代码片段。它们不是路由或布局,但可以在它们内部使用。

例如,一个 Button 组件应该放在 src/components/button/button.tsx 中。

public/

public/ 目录包含静态资源,如图像、字体和图标。当构建应用时,这些文件将被复制到 dist/ 目录并在根目录下提供服务。

有关更多信息,请参阅Vite 配置

src/entry.ssr.tsx

SSR 入口点,在所有情况下,应用程序都在浏览器之外渲染,这个入口点将是通用的。

  • 服务器 (express, cloudflare...)
  • npm run start
  • npm run preview
  • npm run build

src/root.tsx

src/root.tsx 文件是应用程序树的入口点。它是将被渲染的第一个组件。它是树的根。

src/global.css

src/global.css 文件是一个全局的 CSS 文件,如果你需要定义一些在应用的多个地方使用的 CSS,可以在这里定义。

根组件 (src/root.tsx) 默认导入此文件。

tsconfig.json

tsconfig.json 文件包含 TypeScript 编译器的配置。对于任何 TypeScript 项目来说,这是标准的。

vite.config.ts

Qwik 使用 Vite 来构建项目。vite.config.ts 文件包含 Vite 的配置。对于任何 Vite 项目来说,这是标准的。请参阅Vite 文档获取更多信息。

实用工具

Qwik 有一个名为 new 的实用命令,允许开发者轻松创建新的组件和路由。

假设你想创建一个名为 Button 的新组件,你可以运行以下命令:

pnpm qwik new Button

也许你想为 /contact 页面创建一个新的路由。为了做到这一点,你可以使用以下命令:

pnpm qwik new /contact

这些命令与 Qwik 的目录文件结构保持一致,可以更快地生成组件的脚手架。

如果我们将页面顶部的 qwik-app-demo 与之前的对比,额外的更改将如下所示:

qwik-app-demo
├── README.md
├── package.json
├── public
   └── favicon.svg
├── src
   ├── components
      └── router-head
          └── router-head.tsx
          Button
          └── button.tsx
   ├── entry.ssr.tsx
   ├── global.css
   ├── root.tsx
   └── routes
       ├── flower
          ├── flower.css
          └── index.tsx
       ├── contact
          └── index.tsx
       ├── index.tsx
       ├── layout.tsx
       └── service-worker.ts
├── tsconfig.json
└── vite.config.ts

如果你更喜欢使用 Button/index.tsx 命名约定生成 Button 组件,你可以使用以下命令:

pnpm qwik new --barrel Button

在这种情况下,src/components 文件夹的结构将如下所示:

src
   ├── components
      └── router-head
          └── router-head.tsx
          Button
          └── index.tsx

此功能在 Qwik v1.2 中添加,使用较旧版本的用户将无法看到此功能。

Contributors

Thanks to all the contributors who have helped make this documentation better!

  • manucorporat
  • steve8708
  • mhevery