Babel和Webpack es6错误,尝试了此处找到的众多修复程序,但无法使其正常运行

时间:2018-12-31 01:45:01

标签: javascript reactjs webpack babel babel-loader

尝试在我的烧瓶网站上使用react时,我一直收到错误消息。我已经尝试了很多在这里找到的修复程序,但是只要我经过一个修复程序,就会弹出另一个修复程序。

最近的错误是:

Module parse failed: Unexpected Token (3:0)
You may need an appropriate loader to handle this file type.
| /* DayPicker styles */
| 
> .DayPicker {
|   display: inline-block;
|   font-size: 1rem;
 @ ./js/daypicker.js 17:0-41
 @ ./js/index.js

我尝试添加CSS和样式加载器,如下所示,但是我无法使其正常运行。我的代码可能很乱,但这是因为我一直在尝试许多不同的修复程序,其中一些已被其他覆盖。

这是我的webpack.config.js文件

const path = require('path');
const webpack = require('webpack');

module.exports = {
  mode: 'development',

  entry: {
    index: './js/index.js'
  },
  output: {
    path: path.resolve(__dirname, 'static/lib'),
    filename: '[name].js',
    publicPath: '/static/lib'
  },
  devtool: 'source-map',
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: 'style-loader',
          loader: 'css-loader',
          loader: 'babel-loader',
          query: {
            cacheDirectory: true,
            presets: ['es2015', 'react', 'stage-0', 'env'],
          }
        }
      },

    ]
  }
};

我什至尝试添加babel.rc文件(如在此处找到的一些修复建议的那样):

{
  test: /\.js$/,
  exclude: /node_modules/,
  loader: 'babel-loader?cacheDirectory=true'
}

但是似乎没有任何作用

不确定这是否相关,但这是我的package.json文件:

{
  "name": "shopping-cart",
  "version": "1.0.0",
  "description": "run `npm install`. and then `npx webpack`",
  "scripts": {
    "build": "webpack -w",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/pambalos/shopping-cart.git"
  },
  "author": "Bradley J <bradleyjusticeca@gmail.com>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/pambalos/shopping-cart/issues"
  },
  "homepage": "https://github.com/pambalos/shopping-cart#readme",
  "main": "index.js",
  "dependencies": {
    "babel-cli": "^6.26.0",
    "babel-preset-env": "^1.7.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "babel-preset-stage-0": "^6.24.1",
    "date-fns": "next",
    "moment": "latest",
    "react": "latest",
    "react-day-picker": "^7.2.4",
    "react-dom": "latest",
    "react-helmet": "latest",
    "webpack": "^4.28.2"
  },
  "devDependencies": {
    "babel-core": "^6.26.3",
    "babel-loader": "^7.1.5",
    "css-loader": "^2.1.0",
    "style-loader": "^0.23.1",
    "styled-components": "^3.4.6",
    "webpack-cli": "^3.1.2"
  }
}

1 个答案:

答案 0 :(得分:1)

要解决此问题,我们可以在webpack.config.js中使用style-loader and css-loader,如下所示:

{ 
  test: /\.css$/, 
  include: /node_modules/, 
  loaders: ['style-loader', 'css-loader'] 
}

css-loader以字符串形式读取css文件。由于它只读取文件内容,而没有其他任何内容,因此除非您将其与另一个加载程序链接在一起,否则它基本上是没有用的。

style-loader采用这些样式,并在包含这些样式的页面元素中创建一个标签。

希望它会有所帮助:)