Webpack无法编译

时间:2017-06-24 13:22:16

标签: reactjs webpack webpack-dev-server react-hot-loader babel-loader

我刚刚开始学习React,并且我正在使用Webpack实现它。

以下是我devDependencies的{​​{1}}:

package.json

这是我的"devDependencies": { "babel-core": "^6.25.0", "babel-loader": "^7.1.0", "babel-preset-es2015": "^6.24.1", "babel-preset-react": "^6.24.1", "react-hot-loader": "^1.3.1", "react-scripts": "1.0.7", "serve": "^5.2.4", "webpack": "^3.0.0", "webpack-dev-server": "^2.5.0" },

webpack.config.js

以下是module.exports = { context: __dirname + "/src", entry: './index.js', output: { filename: "index.js", path: __dirname + '/dist' }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loaders: ["react-hot-loader", "babel-loader"], } ], }, }

.babelrc

现在,当我运行{ "presets": [ "es2015", "react" ] } 时,它会引发此错误

npm start

请帮我解决这个问题。

修改1:

ERROR in ./src/index.css Module parse failed: /home/tps/ReactApps/login-app/src/index.css Unexpected token (1:5) You may need an appropriate loader to handle this file type. | body { | margin: 0; | padding: 0; @ ./src/index.js 21:0-22 @ multi ./node_modules/webpack-dev-server/client?http://localhost:8081 webpack/hot/dev-server ./index.js ERROR in ./src/App.js Module not found: Error: Can't resolve './notFound' in '/home/tps/ReactApps/login-app/src' @ ./src/App.js 33:16-37 @ ./src/index.js @ multi ./node_modules/webpack-dev-server/client?http://localhost:8081 webpack/hot/dev-server ./index.js ERROR in ./src/App.css Module parse failed: /home/tps/ReactApps/login-app/src/App.css Unexpected token (1:0) You may need an appropriate loader to handle this file type. | .App { | text-align: center; | } @ ./src/App.js 19:0-20 @ ./src/index.js @ multi ./node_modules/webpack-dev-server/client?http://localhost:8081 webpack/hot/dev-server ./index.js

webpack.config.js

module.exports = { context: __dirname + "/src", entry: './index.js', output: { filename: "index.js", path: __dirname + '/dist' }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loaders: ["react-hot-loader", "babel-loader"], } ], rules: [ { test: /\.css$/, use: [ 'style-loader', 'css-loader' ] } ] }, }

package.json

1 个答案:

答案 0 :(得分:2)

您需要在webpack配置中添加一个css-loader才能导入css文件。

npm install --save-dev css-loader style-loader

并将以下内容添加到webpack配置中的loaders数组中:

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

检查以获取更多信息:https://github.com/webpack-contrib/css-loader

编辑:您正在使用加载器和规则。它们基本上是一回事。 请查看此信息以获取更多信息:https://webpack.js.org/guides/migrating/#module-loaders-is-now-module-rules

试试这个webpack配置:

module.exports = {
  context: __dirname + "/src",
  entry: './index.js',

  output: {
    filename: "index.js",
    path: __dirname + '/dist'
  },

  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loaders: ["react-hot-loader", "babel-loader"],
      },       
      {
        test: /\.css$/,
        use: [ 'style-loader', 'css-loader' ]
      }
    ]
  },
}