试图让CSS在我的项目中工作 - 尝试排除故障

时间:2018-02-15 18:10:09

标签: javascript reactjs webpack

我试图让css文件在我的反应项目中工作。我总是在个人项目中使用create-react-app,但是这个项目是从webpack创建的,所以我必须配置加载器等等,我的理解是有限的。更糟糕的是,我继承了项目,所有样式都应用于每个组件上的样式对象,因此这里存在多种复杂性。但是anywhozzle,css文件与组件的JS文件位于完全相同的文件夹中。我试图将css样式表导入我的Home组件中的文件,如下所示:

import from './home.css'

我得到的错误是......

Module build failed: SyntaxError: Unexpected token (10:12)
import from './home.css'

......并且有一个红色箭头指向'就在./home.css之前。

我的webpack配置文件的loader部分如下所示:

module : {
  loaders : [
    {
      test : /\.jsx?/,
      include : APP_DIR,
      loader : 'babel-loader'
    },
    {
      test: /\.css$/,
      use: [ 'style-loader', 'css-loader' ]
    },
    {
      test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2|otf)$/,
      loader: 'url-loader',
      options: {
        limit: 10000
      }
    }
  ]
},

并且,为了更好的衡量,这是我的package.json ...

{
  "name": "react-cbd",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "devNoServer": "webpack --d --watch",
    "dev": "webpack-dev-server --watch --progress --colors",
    "build": "webpack -p",
    "build-css": "node-sass-chokidar src/ -o src/",
    "watch-css": "npm run build-css && node-sass-chokidar src/ -o src/ --watch --recursive"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-plugin-transform-object-rest-spread": "^6.26.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "copy-webpack-plugin": "^4.2.3",
    "css-loader": "^0.28.9",
    "font-loader": "^0.1.2",
    "jquery": "^3.2.1",
    "lodash": "^4.17.4",
    "moment": "^2.20.1",
    "node-sass-chokidar": "0.0.3",
    "react": "^16.0.0",
    "react-bootstrap-carousel": "^2.2.1",
    "react-datetime": "^2.11.1",
    "react-dom": "^16.0.0",
    "react-fontawesome": "^1.6.1",
    "react-motion": "^0.5.2",
    "react-redux": "^5.0.6",
    "react-router-dom": "^4.2.2",
    "react-scrollbars": "0.0.5",
    "redux": "^3.7.2",
    "style-loader": "^0.19.1",
    "webpack": "^3.8.1",
    "webpack-dev-server": "^2.9.5"
  },
  "devDependencies": {
    "babel-plugin-transform-decorators-legacy": "^1.3.4",
    "babel-preset-stage-2": "^6.24.1",
    "css-loader": "^0.28.8",
    "file-loader": "^1.1.5",
    "url-loader": "^0.6.2"
  }
}

2 个答案:

答案 0 :(得分:0)

您需要使用组件名称引用导入。

import ComponentName from './home.css'

答案 1 :(得分:0)

通常情况下,对于css in react,只需导入css模块而不使用关键字:

import './home.css'

如果您想深入挖掘,可以在Javascript中查看有关导入的MDN docs