'import json file in react, webpack config error

I am trying to import a json file into my code. The js file for the same is

import React from 'react';
import ReactDom from 'react-dom' ;
import $ from 'jquery' ;
import data from './data.json';

class ExpenseApp extends React.Component{
  render(){
    return(
        <div>{data.Author}</div>
      )
  }
}


ReactDom.render(<ExpenseApp/>,document.getElementById('container'));

I already have json loader installed and webpack config file is like this--

var webpack = require('webpack');
var path = require('path');

var node_dir = __dirname + '/node_modules',
    lib_dir = __dirname + '/public/libraries';

var config = {
    // The resolve.alias object takes require expressions 
    // (require('react')) as keys and filepath to actual
    // module as values
    resolve: {
        alias: {
            react: lib_dir + '/react',
            "react-dom": lib_dir + '/react-dom',
            "jquery": lib_dir + '/jquery-3.2.1.js'
        },
        extensions:['','.js','.jsx','.json']
    },
    plugins: [

        new webpack.optimize.CommonsChunkPlugin({ // 
            name: 'vendors',
            filename: 'build/vendors.bundle.js',
            minChunks: 2,
        }),

        new webpack.HotModuleReplacementPlugin(),
        new webpack.NoEmitOnErrorsPlugin()
    ],

    entry: {
        musicApp: ['./public/js/expense-app.js', 'webpack/hot/only-dev-server'],
        vendors: ['react', 'react-dom', 'jquery', 'webpack/hot/only-dev-server']
    },

    output: {
        path: path.join(__dirname, "public"),
        filename: 'build/[name].bundle.js',
        libraryTarget: "umd"
    },

    module: {

        noParse: [
            new RegExp(lib_dir + './react.js'), 
            new RegExp(lib_dir + './react-dom.js')
        ],
        rules: [
             {
                test: /\.js?$/,

                loaders: ['react-hot-loader/webpack', 'babel-loader'],
                include: path.join(__dirname, 'public')

            }, 
            {
                loader: 'babel-loader',
                query: {
                    presets: ['react', 'es2015']
                },
                include: path.join(__dirname, 'public')
            }
        ]
    }
}

module.exports = config;

The data.json file is--

var data={
    "Author":"Dan Brown",
    "Book":"Inferno",
}
module.exports=data;

I was getting 'cannot resolve data.json' error at first so I added extensions in resolve of webpack. Now also,I am getting the same Error

Also, I tried adding json-loader in loaders[] inside modules, but then also I was getting errors. And the folder structure is like this Folder

How can I resolve this?



Solution 1:[1]

you can try following things

1) add "json-server": "^0.8.8", in your package.json 2)start the json server with below command

node ./node_modules/json-server/bin/index.js --watch ./data/data.json--port 3001

3) access your json file using any ajax call.

you can check my sample project as below where i implemented this code

https://github.com/johibkhan2/react-redux-singlePageApp

Solution 2:[2]

Webpack does not find your data.json because you have specified incorrect path. The import data from './data.json' will look for data.json from the same directory as the your ExpenseApp component, but based on your screenshot it's one level above. So the import statement should be import data from '../data.json'

Your data.json file also has problems which probably caused your other issues. JSON is not javascript, so it does not have var's or module exports etc...

{ "Author":"Dan Brown", "Book":"Inferno", }

Is the JSON, everything else there is extra and will likely make the JSON loader barf as it is expecting JSON, not javascript.

Solution 3:[3]

When importing JSON files as module, you should use the ES6 configuration which is :

import XXX from "./myJsonFile.json" assert { type: "json" };

also, you don't need to export the data in your JSON file just put it as an Object or Array without name like this:

[
    "SELECT",
    "UPDATE",
    "DELETE",
    "SELECT",
    "TRUNCATE",
    "CREATE DATABASE",
    "CREATE SCHEMA",
    "CREATE TABLE ",
    "CREATE VIEW ",
    "CREATE TRIGGER",
    "CREATE_FUNCTION",
    "CREATE INDEX",
    "DROP DATABASE",
    "DROP SCHEMA",
    "DROP TABLE",
    "DROP VIEW",
    "DROP TRIGGER",
    "DROP FUNCTION",
    "DROP INDEX",
    "ALTER DATABASE",
    "ALTER SCHEMA",
    "ALTER TABLE",
    "ALTER VIEW",
    "ALTER TRIGGER",
    "ALTER FUNCTION",
    "ALTER INDEX",
    "UNKNOWN"
]

also in your HTML file add (type="module") to the script tag for your js file.

this is probably not the best way for production but, is a trick.

I hope this helps.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Johib Khan
Solution 2 Matti
Solution 3 Hootan