【问题标题】:json-loader in webpack.config.js not workingwebpack.config.js 中的 json-loader 不工作
【发布时间】:2018-03-19 08:11:11
【问题描述】:

我正在尝试遵循一个反应教程,我的 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

【问题讨论】:

    标签: javascript reactjs webpack


    【解决方案1】:

    我注意到你正在使用 webpack 4。根据json-loader README

    由于 webpack >= v2.0.0,默认情况下可以导入 JSON 文件

    因此,如果您同时使用webpack &gt;= v2.0.0json-loader,文件将被转换两次,从而导致问题。解决方法就是删除json-loader规则。

    【讨论】:

      【解决方案2】:

      我在 lib.js 中以错误的方式导入了titles.json

      我们可以这样做: 在 lib.js 中

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

      它的用途如下:

      {greetings.hello}
      

      【讨论】:

        猜你喜欢
        • 2017-11-24
        • 2017-07-15
        • 2017-12-29
        • 2019-03-09
        • 2016-02-28
        • 2018-02-11
        • 1970-01-01
        • 1970-01-01
        • 2022-07-03
        相关资源
        最近更新 更多