导入元信息
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.
:
了解更多关于 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.client | boolean | 在客户端执行时为 True。 |
import.meta.browser | boolean | 在客户端执行时为 True。 |
import.meta.server | boolean | 在服务器端执行时为 True。 |
import.meta.nitro | boolean | 在服务器端执行时为 True。 |
import.meta.dev | boolean | 运行 Nuxt 开发服务器时为 True。 |
import.meta.test | boolean | 在测试环境中运行时为 True。 |
import.meta.prerender | boolean | 在构建的预渲染阶段,在服务器上渲染 HTML 时为 True。 |
Builder 属性
¥Builder Properties
这些值在模块和 nuxt.config
中均可用。
¥These values are available both in modules and in your nuxt.config
.
属性 | 类型 | 描述 |
---|---|---|
import.meta.env | object | 等于 process.env |
import.meta.url | string | 当前文件的可解析路径。 |
示例
¥Examples
import.meta.url
解析模块内的文件 使用
¥Using import.meta.url
to resolve files within modules
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')
})
}
})