json-loader in webpack.config.js not working

久未见 提交于 2021-02-18 01:39:27

问题


I'm trying to follow a react tutorial, My webpack.config.js file is as follows:

var webpack = require("webpack");
var pth = require("path");

module.exports = {
entry: "./src/index.js",
output: {
    path: __dirname + "/dist",
    filename: "bundle.js"
},
devServer: {
    inline: true,
    contentBase: './dist',
    port: 3000
},
module: {
    rules: [
      { test: /\.js$/, exclude: /(node_modules)/, use: 'babel-loader' },
      { test: /\.json$/, exclude: /(node_modules)/, use: 'json-loader' }
    ]
  }
} 

While my Code files are as follows: I have made components here in lib.js and rendering is being done in index.js which ultimately is called in a HTML div in index.html

lib.js

import React from 'react'
import text from './titles.json'

export const hello = (
<h1 id='title'
    className='header'
    style={{backgroundColor: 'purple', color: 'yellow'}}>
    {text.hello}    
</h1>
)


export const goodbye = (
<h1 id='title'
    className='header'
    style={{backgroundColor: 'white', color: 'red'}}>
    {text.goodbye}    
</h1>
)

index.js

import React from 'react'
import {render} from 'react-dom'
import {hello, goodbye} from './lib'


const design = {
backgroundColor: 'red',
color: 'white',
fontFamily:'verdana'
}


render(
<div>
    {hello}
    {goodbye}
</div>,    
document.getElementById('react-container')
)

When I run webpack -w command, I experience the following error

ERROR in ./src/titles.json
Module parse failed: Unexpected token m in JSON at position 0
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token m in JSON at position 0
at Object.parse (native)
at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:447:3)
@ ./src/lib.js 12:14-38
@ ./src/index.js

ERROR in chunk main [entry]
bundle.js
Cannot read property 'replace' of undefined

My JSON file is as follows: titles.json

{
    "hello": "Bonjour!",
    "goodbye": "Au Revoir"

}

My Module verions are as follows: webpack 4.1.1 json-loader 0.5.7

I have installed webpack and json-loader globally using npm install TIA


回答1:


I notice you are using webpack 4. According to json-loader README:

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

So if you are using webpack >= v2.0.0 and json-loader together, the file will be transformed twice which caused the issue. The solution is simply delete the json-loader rule.




回答2:


I was importing the titles.json the wrong way in lib.js

We can do it as follows: In lib.js

var greetings = require('./titles.json')

And it will be utilized as follows:

{greetings.hello}


来源:https://stackoverflow.com/questions/49358313/json-loader-in-webpack-config-js-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!