Webpack error when importing a json file

Viewed 3682

Here is a simple test case that breaks:

First, save a json file from Node:

const fs = require('fs')

let test = {
  foo: [
    { 1: 'a'},
    { 2: 'b'}
  ]
};

fs.writeFileSync('./test.json', JSON.stringify(test), 'utf-8');

Then, try importing this json into a js file that is processed by Webpack (I am using the latest version of Webpack, 3.4.1):

import test from './test.json';

console.log(test);

This fails with the following error:

ERROR in ./test.json                                       
Module build failed: SyntaxError: Unexpected token, expected ; (1:6)

> 1 | {"foo":[{"1":"a"},{"2":"b"}]}

The offending character that the console output is pointing at is the colon after "foo".

My Webpack config was very simple, with only these module options:

  module: {
    rules: [
      {
        test: /\.js/,
        exclude: [ path.resolve(__dirname, 'node_modules') ],
        loader: 'babel-loader'
      },
      {
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
          fallback: "style-loader",
          use: "css-loader"
        })
      }
    ]
  },

Confused, I opened the JSON loader page, which informed me that:

Since webpack >= v2.0.0, importing of JSON files will work by default.

Since I was using Webpack v. 3.4.1, I assumed json-loader was unnecessary. Still, out of desperation, I added the following rule to the modules field of Webpack config:

  {
    test: /\.json/,
    loader: 'json-loader'
  }

This actually worked! The json file got loaded, and the error disappeared.

So my question is: was I doing something wrong with Webpack trying to import the json file, or is the newest Webpack somehow broken as regards to the importing of json files?

1 Answers
Related