创建 Nuxt 层

Nuxt 提供了一个强大的系统,允许你扩展默认文件、配置等等。

Nuxt 层是一项强大的功能,可用于在单一仓库、git 仓库或 npm 包中共享和重用部分 Nuxt 应用。图层结构几乎与标准 Nuxt 应用相同,这使得它们易于编写和维护。

¥Nuxt layers are a powerful feature that you can use to share and reuse partial Nuxt applications within a monorepo, or from a git repository or npm package. The layers structure is almost identical to a standard Nuxt application, which makes them easy to author and maintain.

Read more in Docs > Getting Started > Layers.

一个最小的 Nuxt 层目录应该包含一个 nuxt.config.ts 文件,以表明它是一个层。

¥A minimal Nuxt layer directory should contain a nuxt.config.ts file to indicate it is a layer.

base/nuxt.config.ts
export default defineNuxtConfig({})

此外,Nuxt 将自动扫描层目录中的某些其他文件,并将其用于扩展此层的项目。

¥Additionally, certain other files in the layer directory will be auto-scanned and used by Nuxt for the project extending this layer.

基本示例

¥Basic Example

export default defineNuxtConfig({
  extends: [
    './base'
  ]
})

入门模板

¥Starter Template

首先,你可以使用 nuxt/starter/layer 模板 初始化一个层。这将创建一个你可以在此基础上进行构建的基本结构。在终端中执行此命令即可开始使用:

¥To get started you can initialize a layer with the nuxt/starter/layer template. This will create a basic structure you can build upon. Execute this command within the terminal to get started:

Terminal
npm create nuxt -- --template layer nuxt-layer

请按照 README 文件中的说明进行后续步骤。

¥Follow up on the README instructions for the next steps.

发布层

¥Publishing Layers

你可以使用远程源或 npm 包来发布和共享层。

¥You can publish and share layers by either using a remote source or an npm package.

Git 仓库

¥Git Repository

你可以使用 git 代码库共享你的 Nuxt 层。一些示例:

¥You can use a git repository to share your Nuxt layer. Some examples:

nuxt.config.ts
export default defineNuxtConfig({
  extends: [
    'github:username/repoName',        // GitHub Remote Source
    'github:username/repoName/base',   // GitHub Remote Source within /base directory
    'github:username/repoName#dev',    // GitHub Remote Source from dev branch
    'github:username/repoName#v1.0.0', // GitHub Remote Source from v1.0.0 tag
    'gitlab:username/repoName',        // GitLab Remote Source example
    'bitbucket:username/repoName',     // Bitbucket Remote Source example
  ]
})
如果你想扩展私有远程源,则需要添加环境变量 GIGET_AUTH=<token> 来提供令牌。
如果你想从自托管的 GitHub 或 GitLab 实例扩展远程源,则需要使用 GIGET_GITHUB_URL=<url>GIGET_GITLAB_URL=<url> 环境变量提供其 URL - 或者直接在 nuxt.config 中使用 the auth option 配置它。
请记住,如果你将远程源扩展为层,你将无法在 Nuxt 之外访问其依赖。例如,如果远程层依赖于 eslint 插件,则这将无法在你的 eslint 配置中使用。这是因为这些依赖将位于你的包管理器无法访问的特殊位置 (node_modules/.c12/layer_name/node_modules/)。¥Bear in mind that if you are extending a remote source as a layer, you will not be able to access its dependencies outside of Nuxt. For example, if the remote layer depends on an eslint plugin, this will not be usable in your eslint config. That is because these dependencies will be located in a special location (node_modules/.c12/layer_name/node_modules/) that is not accessible to your package manager.
使用 git 远程源时,如果某个层包含 npm 依赖并且你希望安装它们,则可以通过在层选项中指定 install: true 来实现。```ts nuxt.config.ts export default defineNuxtConfig({ extends: 'github:username/repoName', { install: true } })
::

<a id="npm-package"></a>

### npm 软件包

¥npm Package

你可以将 Nuxt 层发布为包含要扩展的文件和依赖的 npm 包。这允许你与他人共享你的配置,在多个项目中使用或私下使用。

¥You can publish Nuxt layers as an npm package that contains the files and dependencies you want to extend. This allows you to share your config with others, use it in multiple projects or use it privately.

要从 npm 包扩展,你需要确保模块已发布到 npm 并作为 devDependency 安装在用户的项目中。然后,你可以使用模块名称来扩展当前的 Nuxt 配置:

¥To extend from an npm package, you need to make sure that the module is published to npm and installed in the user's project as a devDependency. Then you can use the module name to extend the current nuxt config:

```ts [nuxt.config.ts]
export default defineNuxtConfig({
  extends: [
    // Node Module with scope
    '@scope/moduleName',
    // or just the module name
    'moduleName'
  ]
})
要将层目录发布为 npm 包,你需要确保 package.json 已填写正确的属性。这将确保在发布包时包含这些文件。¥To publish a layer directory as an npm package, you want to make sure that the package.json has the correct properties filled out. This will make sure that the files are included when the package is published.
package.json
{
  "name": "my-theme",
  "version": "1.0.0",
  "type": "module",
  "main": "./nuxt.config.ts",
  "dependencies": {},
  "devDependencies": {
    "nuxt": "^3.0.0"
  }
}
确保层中导入的任何依赖都是 explicitly addeddependenciesnuxt 依赖以及任何仅用于在发布前测试层的内容应保留在 devDependencies 字段中。
现在你可以继续将模块发布到 npm,无论是公开还是私有。¥Now you can proceed to publish the module to npm, either publicly or privately.
将层发布为私有 npm 包时,你需要确保登录,并通过 npm 进行身份验证以下载 Node 模块。

提示

¥Tips

命名层别名

¥Named Layer Aliases自动扫描的层(来自你的 ~~/layers 目录)会自动创建别名。例如,你可以通过 #layers/test 访问你的 ~~/layers/test 层。¥Auto-scanned layers (from your ~~/layers directory) automatically create aliases. For example, you can access your ~~/layers/test layer via #layers/test.如果你想为其他图层创建命名图层别名,你可以在图层的配置中指定一个名称。¥If you want to create named layer aliases for other layers, you can specify a name in the configuration of the layer.
nuxt.config.ts
export default defineNuxtConfig({
  $meta: {
    name: 'example',
  },
})
这将生成一个指向你的层的 #layers/example 别名。¥This will produce an alias of #layers/example which points to your layer.

相对路径和别名

¥Relative Paths and Aliases在层组件和可组合项中使用全局别名(例如 ~/@/)导入时,请注意这些别名是相对于用户的项目路径解析的。作为一种解决方法,你可以使用相对路径导入它们,或使用命名层别名。¥When importing using global aliases (such as ~/ and @/) in a layer components and composables, note that these aliases are resolved relative to the user's project paths. As a workaround, you can use relative paths to import them, or use named layer aliases.此外,在层的 nuxt.config 文件中使用相对路径时(嵌套的 extends 除外),它们是相对于用户的项目而不是层进行解析的。作为一种解决方法,请在 nuxt.config 中使用完整解析路径:¥Also when using relative paths in nuxt.config file of a layer, (with exception of nested extends) they are resolved relative to user's project instead of the layer. As a workaround, use full resolved paths in nuxt.config:
nuxt.config.ts
import { fileURLToPath } from 'url'
import { dirname, join } from 'path'

const currentDir = dirname(fileURLToPath(import.meta.url))

export default defineNuxtConfig({
  css: [
    join(currentDir, './assets/main.css')
  ]
})

Nuxt 模块的多层支持

¥Multi-Layer Support for Nuxt Modules你可以使用内部数组 nuxt.options._layers 支持模块的自定义多层处理。¥You can use the internal array nuxt.options._layers to support custom multi-layer handling for your modules.
modules/my-module.ts
export default defineNuxtModule({
  setup(_options, nuxt) {
    for (const layer of nuxt.options._layers) {
      // You can check for a custom directory existence to extend for each layer
      console.log('Custom extension for', layer.cwd, layer.config)
    }
  }
})
备注:¥Notes:
  • _layers 数组中靠前的项目优先级更高,会覆盖靠后的项目。
  • 用户的项目是 _layers 数组中的第一个项目。

深入了解

¥Going Deeper配置加载和扩展支持由 unjs/c12 处理,使用 unjs/defu 进行合并,使用 unjs/giget 支持远程 git 源。查看文档和源代码以了解更多信息。¥Configuration loading and extends support is handled by unjs/c12, merged using unjs/defu and remote git sources are supported using unjs/giget. Check the docs and source code to learn more.:
Read more in https://github.com/nuxt/nuxt/issues/13367.
查看我们正在进行的开发,以在 GitHub 上为图层支持带来更多改进。¥Checkout our ongoing development to bring more improvements for layers support on GitHub.::