3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

みんな大好きJavaScriptのimport.metaにどんなプロパティがあるか調べてみた

Last updated at Posted at 2025-03-07

Node.jsで動くJavaScriptとか書いているとimport.meta.urlとか書きますよね?
最近のNode.jsだとimport.meta.dirnameも使えたりするわけですけど、ちょっと古い環境では動かなかったりで困ったりしていて、そういえばどの環境だとどのimport.metaが使えるかよくわからないな、と思ったのでざっと調べてまとめようと思いました。

調べたドキュメントは、この辺りです。

ちなみにMDNで書いてあるのは、import.meta.urlimport.meta.resolveだけです。
これは Living Standard のやつと一致しますね。

参考: MDN - import.meta

ご存知かと思いますが、ECMAScriptにはどのプロパティも書いてありません。

import.meta.url

そのスクリプトのURLが取れる。大体どこの環境でも使えると思う。
Living Standard にも書いてあるのでブラウザでも使えそう。

import.meta.resolve()

そのスクリプトからimport(specifier)した場合に取れるスクリプトのパスの文字列が取れるはずだけど、環境によってはPromiseを返すらしい。怖い。
あと第2引数を受け入れるかどうかはその環境次第だと思う。
動きは違うけど、大体どこの環境でも存在はすると思う。
Living Standard にも書いてあるのでブラウザでも使えそう。

import.meta.filenameimport.meta.dirname

そのスクリプトのパスやディレクトリパスが取れる。
Node.js v20.11以降で使える。あとDenoとBunも大丈夫(バージョンは調べてない)。

import.meta.main

そのファイルがエントリーポイントかどうかがわかる。
DenoとBunで使える。

import.meta.pathimport.meta.dirimport.meta.file

import.meta.pathimport.meta.filenameimport.meta.dirimport.meta.dirnameと同じ。
import.meta.fileはそのファイル名が取れる。
Bunで使える。

import.meta.env

環境変数が取れる。
Bunで使える。あとViteではバンドル時に解決してくれる。

import.meta.glob()

Viteで使える。globを使って一括importできる。
ドキュメントはこちら→ https://vite.dev/guide/features.html#glob-import

import.meta.hot

Viteで使える。HMRのあれこれをするためのプロパティ。
ドキュメントはこちら→ https://vite.dev/guide/api-hmr.html

import.meta.webpack

Webpackで使える。Webpackのバージョンが取れる。

import.meta.webpackHot

Webpackで使える。HMRのやつ(かな?)
ドキュメントはこちら→ https://webpack.js.org/api/module-variables/#importmetawebpackhot

import.meta.webpackContext()

Webpackで使える。何かのコンテキストが取れる。
ドキュメントはこちら→ https://webpack.js.org/api/module-variables/#importmetawebpackcontext

あとがき

まだあるかもしれませんが、どうやって調べればいいかわからないのでこの辺で終わります。

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?