webpack: Webpack fails to parse modules that use a json file as the index

Hi there!

When I require the module https://github.com/dfcreative/color-name, Webpack fails with the following error:

ERROR in ./~/color-name/index.json
Module parse failed: [redacted]/node_modules/color-name/index.json Line 2: Unexpected token :
You may need an appropriate loader to handle this file type.
| {
|   "aliceblue": [240, 248, 255],
|   "antiquewhite": [250, 235, 215],
|   "aqua": [0, 255, 255],
 @ ./app/client/index.jsx 17:8-29

And it’s because the color-name module specifies index.json as the module entrypoint in its package.json.

When I change the filename inside that module to index.js and modify it to use module.exports = ... everything works fine.

I tried addding json-loader to my webpack config, but it looks like webpack expects only to find .js files when requiring something from node_modules.

It’s strange that the color-name module uses a json file as its index, but Node supports it, so it seems like Webpack maybe should too?

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Comments: 18 (5 by maintainers)

Commits related to this issue

Most upvoted comments

I am so sorry.

This is very embarrassing. It does, in fact, work fine. I was editing the wrong webpack config.

shamecube

Remove the exclude from the json-loader.

module.exports = {
    module: {
        loaders: [
            { test: /\.json$/, loader: "json-loader" }
        ]
    }
}
webpack color-name bundle.js

works fine.

You need the json-loader

I had this problem because I was applying the babel-loader to json files. I did this:

{
  test: /\.js/,
  use: 'babel-loader'
}

I fixed it by doing this:

{
  test: /\.js$/,
  use: 'babel-loader'
}

Sorry I’ve taken so long to get back, here’s what my webpack config looks like:

var path = require('path')

module.exports = {
  entry: "./app/client/index.jsx",
  output: {
    path: path.join(__dirname, 'app', 'static', 'generated'),
    filename: 'bundle.js'
  },

  resolve: {
    extensions: ['', '.js', '.jsx', 'index.js', 'index.jsx', '.json', 'index.json']
  },

  module: {
    preLoaders: [
        { test: /\.json$/, exclude: /node_modules/, loader: 'json'},
    ],
    loaders: [
        { test: /\.js$/, exclude: /node_modules/, loader: 'babel'},
        { test: /\.jsx$/, exclude: /node_modules/, loader: 'babel'},
        { test: /\.css$/, exclude: /static/, loader: 'style!css'}
    ]
  },

  devtool: '#eval'
}

thanks for the fix 👍