LoginSignup
14
6

More than 5 years have passed since last update.

【webpack】json-loaderで『Module parse failed: Unexpected token m in JSON at position 0 while parsing near 'module.exports = [{"...'』の解決方法

Posted at

Module parse failed: Unexpected token m in JSON at position 0 while parsing near 'module.exports = [{"...'

エラーについて

webpack で json-loader を用いて JSON ファイルを読み込む際に、

const json = require("data.json");

以下のエラーが出ることがある。

ERROR in ./src/data.json
Module parse failed: Unexpected token m in JSON at position 0 while parsing near 'module.exports = [{"...'
You may need an appropriate loader to handle this file type.

解決方法

webpack.config.js の JSON ファイルに関する rules を、以下のように記述すると解消される。

module: {
  rules: [
    {
      test: /\.json$/,
      loader: "json-loader",
      type: "javascript/auto"
    }
  ]
}

type: "javascript/auto" の部分が必要だったようである。

補足: json-loader

require から JSON の読み込みを可能にする loader である。

  1. インストール方法

    # npm の場合
    npm install json-loader --save-dev
    
    # yarn の場合
    yarn add json-loader --dev
    
  2. webpackの記述方法

    module: {
      rules: [
        {
          test: /\.json$/,
          loader: "json-loader",
          type: "javascript/auto"
        }
      ]
    }
    
14
6
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
14
6