我正在尝试遵循 React 教程,我的 webpack.config.js 文件如下:
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' }
]
}
}
虽然我的代码文件如下:我在lib.js中制作了组件,并在index.js中完成渲染,最终在index.html中的HTML div中调用
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')
)
当我运行 webpack -w
命令时,遇到以下错误
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
我的JSON文件如下: 标题.json
{
"hello": "Bonjour!",
"goodbye": "Au Revoir"
}
我的模块版本如下: 网页包 4.1.1 json-loader 0.5.7
我已经使用 npm install 全局安装了 webpack 和 json-loader TIA
最佳答案
我注意到你正在使用 webpack 4。根据 json-loader README :
Since webpack >= v2.0.0, importing of JSON files will work by default
因此,如果您同时使用 webpack >= v2.0.0
和 json-loader
,文件将被转换两次,从而导致问题。解决方案只需删除 json-loader
规则即可。
关于javascript - webpack.config.js 中的 json-loader 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49358313/