import.meta - JavaScript 编辑

The import.meta object exposes context-specific metadata to a JavaScript module. It contains information about the module, like the module's URL.

Syntax

import.meta

Description

The syntax consists of the keyword import, a dot, and the identifier meta. Normally the left-hand side of the dot is the object on which property access is performed, but here import is not really an object.

The import.meta object is created by the ECMAScript implementation, with a null prototype. The object is extensible, and its properties are writable, configurable, and enumerable.

Examples

Using import.meta

Given a module my-module.js

<script type="module" src="my-module.js"></script>

you can access meta information about the module using the import.meta object.

console.log(import.meta); // { url: "file:///home/user/my-module.js" }

It returns an object with a url property indicating the base URL of the module. This will either be the URL from which the script was obtained, for external scripts, or the document base URL of the containing document, for inline scripts.

Note that this will include query parameters and/or hash (i.e., following the ? or #).

For example, with the following HTML:

<script type="module">
import './index.mjs?someURLInfo=5';
</script>

..the following JavaScript file will log the `someURLInfo parameter:

// index.mjs
new URL(import.meta.url).searchParams.get('someURLInfo'); // 5

The same applies when a file imports another:

// index.mjs
import './index2.mjs?someURLInfo=5';

// index2.mjs
new URL(import.meta.url).searchParams.get('someURLInfo'); // 5

Note that while Node.js will pass on query parameters (or the hash) as in the latter example, as of Node 14.1.0, a URL with query parameters will err when loading in the form node --experimental-modules index.mjs?someURLInfo=5 (it is treated as a file rather than a URL in this context).

Such file-specific argument passing may be complementary to that used in the application-wide location.href (with query strings or hash added after the HTML file path) (or on Node.js, through process.argv).

Specifications

Specification
import.meta proposal
HTML Living Standard
The definition of 'import.meta' in that specification.

Browser compatibility

BCD tables only load in the browser

Implementation Progress

The following table provides a daily implementation status for this feature, because this feature has not yet reached cross-browser stability. The data is generated by running the relevant feature tests in Test262, the standard test suite of JavaScript, in the nightly build, or latest release of each browser's JavaScript engine.

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:64 次

字数:5097

最后编辑:7年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文