我试图按照反应教程,我的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文件如下: titles.json
{
"hello": "Bonjour!",
"goodbye": "Au Revoir"
}
我的模块版本如下: webpack 4.1.1 json-loader 0.5.7
我使用npm install全局安装了webpack和json-loader TIA
答案 0 :(得分:8)
我注意到你正在使用webpack 4.根据json-loader README:
由于webpack&gt; = v2.0.0,默认情况下导入JSON文件
因此,如果您一起使用webpack >= v2.0.0
和json-loader
,该文件将被转换两次,从而导致问题。解决方案只是删除json-loader
规则。
答案 1 :(得分:0)
我在lib.js中以错误的方式导入titles.json
我们可以这样做: 在lib.js中
var greetings = require('./titles.json')
它将按如下方式使用:
{greetings.hello}