2016-08-13 102 views
6

我試圖加載我reactjs應用程序的狀態的JSON文件,但的WebPack不斷拋出此錯誤:的WebPack無法解析JSON即使JSON裝載機

ERROR in ./src/data/questions.json 
Module parse failed: C:\Users\[...]\myApp\src\data\questions.json 
Unexpected token (2:9) 
You may need an appropriate loader to handle this file type. 
SyntaxError: Unexpected token (2:9) 
... 

的JSON文件是有效的,並我爲webpack使用json-loader,所以我不確定是什麼問題。

這裏是我的webpack.config.json文件:

module.exports = { 
    entry: __dirname + '/src/index.js', 
    output: { 
    filename: 'bundle.js', 
    path: __dirname + '/dist/js' 
    }, 
    cache: true, 
    debug: true, 
    devtool: 'source-map', 
    module: { 
    loaders: [{ 
     test: /\.jsx?$/, 
     exclude: /(node_modules|\.c9)/, 
     loader: 'babel', 
     query: { 
     presets: ['react', 'es2015', 'stage-0'] 
     } 
    }, { 
     test: /\.json$/, 
     loader: 'json-loader' 
    }] 
    } 
}; 

這是我如何導入JSON文件:

const quizes = [ 
    require('./data/questions.json') 
]; 

如果我改變上述行來:

const quizes = [ 
    require('json!./data/questions.json') 
]; 

我收到了另一個錯誤:

ERROR in ./~/json-loader!./src/data/questions.json 
Module build failed: SyntaxError: Unexpected token m 
    at Object.parse (native) 
    at Object.module.exports (C:\Users\[...]\myApp\node_modules\json-loader\index.js:7:48) 

更奇怪的是,使用上述方法(json!前綴),錯誤立即拋出(在初始構建過程中)。但是,如果我只是將它放在webpack配置加載器中,則初始構建完成時不會出錯,但後續構建會引發錯誤。

儘管如此,我的應用程序仍然大多數時間工作。這裏發生了什麼?

回答

2

老問題,但您已經指定了兩次加載器:一次在webpack.config.js之後,再次加上require。使用一個或另一個,這應該刪除錯誤。