我正在尝试建立一个新的react.js项目并出现编译错误

时间:2019-07-09 06:40:33

标签: reactjs webpack syntax-error babel

我正在设置新的react项目,并且尝试编译webpack并出现语法错误。我的猜测是由于package.json和webpack.config.js问题

这是我的pacakage.json代码

{
  "name": "blog_project",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "webpack": "webpack"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.5.0",
    "@babel/preset-env": "^7.5.2",
    "@babel/preset-react": "^7.0.0",
    "babel-loader": "^8.0.6",
    "babel-preset-env": "^1.7.0",
    "css-loader": "^3.0.0",
    "node-sass": "^4.12.0",
    "webpack": "^4.35.3",
    "webpack-cli": "^3.3.5"
  },
  "dependencies": {
    "babel-preset-react": "^6.24.1"
    "react": "^16.8.6",
    "react-dom": "^16.8.6"

  }
}

这是我的webpack.config.js代码

const path = require('path');

module.exports = {
    mode: 'none',
    entry: {
        app: './src/index.js'
    },
    watch: true,
    devtool: 'source-map',
    output: {
        filename: '[name].bundle.js',
        path: path.resolve(__dirname, 'dist')
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: ['babel-loader']
            }
        ]
    },
    resolve: {
        extensions: [
            '.js'
        ]
    }
}

和index.js代码我试图编译并在网络浏览器上显示一些div标签

import React from 'react'
import ReactDOM from 'react-dom'

class RootEl extends React.Component {

    render() {
        return <div><h1>This is JSX!</h1></div>;
    }

}

ReactDOM.render(<RootEl />, document.getElementById("root"))

当我尝试编译此代码,然后webpack向我显示错误消息

ERROR in ./src/index.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: C:\blog\blog\static\src\index.js: Unexpected token (7:15)

   5 |
   6 |     render() {
>  7 |         return <div>This is XML!</div>;
     |                ^
   8 |     }
   9 |
  10 | }

1 个答案:

答案 0 :(得分:1)

JSX(例如javascript中的<div>)不是有效的javascript语法。您需要babel才能将这些JSX转换为有效的javascript。为此,您需要告诉babel HOW移植它们。

您应该安装@babel/preset-react并设置babel,以便它将使用该预设。

module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: [
                  {
                    loader: 'babel-loader',
                    options: {
                      presets: [
                        ['@babel/preset-react'],
                      ],
                    },
                  },
                ]
            }
        ]
    },

预设基本上只是babel在尝试转译代码时可以参考的一组规则。