2016-11-10 37 views
1

我使用這裏的教程作爲基礎,但我沒有任何有關如何將css文件導入到應用程序的示例。我發現了點點滴滴,但還不足以知道如何去做。我添加了「./styles/main.css」的導入樣式;「到App.jsx和我的webpack配置如下。將CSS添加到ReactJS項目

var css = require("css!./main.css"); 

var config = { 
    entry: './main.js', 

    output: { 
     path:'./', 
     filename: 'index.js', 
    }, 

    devServer: { 
     inline: true, 
     port: 8080 
    }, 

    module: { 
     loaders: [ 
      { 
       test: /\.jsx?$/, 
       exclude: /node_modules/, 
       loader: 'babel', 

       query: { 
        presets: ['es2015', 'react'] 
       } 
      }, 
      { 
       test: /\.css$/, 
       loader: "style!css!" 
      } 
     ] 
    } 
} 

module.exports = config;` 

我得到的錯誤:

./styles/main.css
Module parse failed: C:\Projects\reactApp\styles\main.css Unexpected token (1:5)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (1:5)

該文件只有div {}現在。

回答

0

在你的WebPack配置,你只需要添加style-loadercss-loader(你需要npm install它在前):

{ test: /\.css$/, loader: 'style-loader!css-loader' }, 

然後你就可以要求CSS在你的.js文件(組件):

require('./styles/main.css'); 
+0

現在我無法啓動服務器。這是我的包json:{ 「name」:「reactapp」, 「version」:「1.0.0」, 「description」:「帶有YouTube播放列表顯示的網站」, 「main」:「index.js」 , 「腳本」:{ 「開始」: 「的WebPack-DEV-服務器--hot」 }, 「關鍵字」:[ 「反應」, 「YouTube」 的, 「播放列表」 ], 「作者「:」Troy Taylor「, 」license「:」ISC「, 」dependencies「:{ 」react「:」^ 15.3.2「, 」react-dom「:」^ 15.3.2「, 「webpack」:「^ 1.13.3」, 「webpack-dev-serv ER「: 」^ 1.16.2「 }, 」devDependencies「:{ 」CSS加載器「: 」^ 0.25.0「, \t 」式裝載機「: 」^ 0.13.0「 }} –

+0

控制檯中的錯誤是什麼? –

+0

npm ERR! Windows_NT 10.0.14393 npm ERR! argv「C:\\ Program Files \\ nodejs \\ node.exe」「C:\\ Program Files \\ nodejs \\ node_modules \\ npm \\ bin \\ npm-cli.js」「start」 npm ERR !節點v6.3.1 npm ERR! npm v3.10.3 npm ERR!代碼ELIFECYCLE npm ERR! [email protected] start:'webpack-dev-server --hot' npm ERR!退出狀態1 –