1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Jest】エラー「SyntaxError: Unexpected token import.meta」の原因と解決法

Posted at

はじめに

Viteで動いていたReactアプリをJestでテストしたところ、
次のようなエラーが出ました。

SyntaxError: Unexpected token import.meta

原因

Viteで使われている import.meta 構文をBabelが理解できないことが原因です。
Babelはデフォルトでは import.meta をサポートしていません。
Viteが内部で利用しているこの構文をそのままJestに渡すと構文エラーになります。

解決法

.babelrc にプラグインを追加して、Babelが import.meta を解釈できるようにします。

.babelrc
{
  "presets": [
    "@babel/preset-env",
    ["@babel/preset-react", { "runtime": "automatic" }]
  ],
  "plugins": [["transform-import-meta", { "module": "ES6" }]]
}

次に、依存関係を追加します。

$ npm install -D babel-plugin-transform-import-meta

これでimport.meta構文がBabelでも正しく変換されるようになります。

まとめ

エラーがきっかけでimport.metaがVite専用の構文であることを知ることができました。
同じようなエラーで困っている方の参考になれば幸いです。

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?