导入元信息

使用 `import.meta` 了解代码的运行位置。

import.meta 对象

¥The import.meta object

使用 ES 模块,你可以从导入或编译 ES 模块的代码中获取一些元数据。这是通过 import.meta 完成的,它是一个为你的代码提供此信息的对象。在整个 Nuxt 文档中,你可能会看到一些代码片段已经使用它来确定代码当前是在客户端还是服务器端运行。

¥With ES modules you can obtain some metadata from the code that imports or compiles your ES-module. This is done through import.meta, which is an object that provides your code with this information. Throughout the Nuxt documentation you may see snippets that use this already to figure out whether the code is currently running on the client or server side.

:

Read more in https://web.nodejs.cn/en-US/docs/Web/JavaScript/Reference/Operators/import.meta.

了解更多关于 import.meta 的信息。

¥Read more about import.meta.

::

运行时(应用)属性

¥Runtime (App) Properties

这些值是静态注入的,可用于对运行时代码进行摇树优化。

¥These values are statically injected and can be used for tree-shaking your runtime code.

属性类型描述
import.meta.clientboolean在客户端执行时为 True。
import.meta.browserboolean在客户端执行时为 True。
import.meta.serverboolean在服务器端执行时为 True。
import.meta.nitroboolean在服务器端执行时为 True。
import.meta.devboolean运行 Nuxt 开发服务器时为 True。
import.meta.testboolean在测试环境中运行时为 True。
import.meta.prerenderboolean在构建的预渲染阶段,在服务器上渲染 HTML 时为 True。

Builder 属性

¥Builder Properties

这些值在模块和 nuxt.config 中均可用。

¥These values are available both in modules and in your nuxt.config.

属性类型描述
import.meta.envobject等于 process.env
import.meta.urlstring当前文件的可解析路径。

示例

¥Examples

使用 import.meta.url 解析模块内的文件

¥Using import.meta.url to resolve files within modules

modules/my-module/index.ts
import { createResolver } from 'nuxt/kit'

// Resolve relative from the current file
const resolver = createResolver(import.meta.url)

export default defineNuxtModule({
  meta: { name: 'myModule' },
  setup() {
    addComponent({
      name: 'MyModuleComponent',
      // Resolves to '/modules/my-module/components/MyModuleComponent.vue'
      filePath: resolver.resolve('./components/MyModuleComponent.vue')
    })
  }
})