Webpack 模块构建失败意外令牌(rails react build)

Webpack module build failed unexpected token (rails react build)

本文关键字:rails react build 令牌 模块 构建 失败 意外 Webpack      更新时间:2023-09-26

我正在开发一个 react/rails 构建,并且第一次使用 webpack 和 babel。我正在使用两个文件并收到错误

./app/assets/frontend/main.jsx
中的错误 模块构建失败:
语法错误:/Users/cls/GitHub/rails_react/app/assets/frontend/main.jsx:意外令牌 (6:6)

第 6 行是:<Greet />

这是主.jsx文件

import Greet from './greet';
class Main extends React.Component {
    render() {
        return (
            <Greet />
        );
    }
}
let documentReady = () => {
    React.render(
        <Main />,
        document.getElementById('react')
    );
};
$(documentReady);

这是 greet.jsx 文件:

export default class Greet extends React.Component {
    render() {
        return <h2>Hello There</h2>
    }
}

这是我的webpack.config:

module.exports = {
  entry: "./app/assets/frontend/main.jsx",
  output: {
    path: __dirname + "/app/assets/javascripts",
    filename: "bundle.js"
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  module: {
    loaders: [
      { test: /'.jsx$/, loader: "babel-loader" }
    ]
  }
};

我没有 babelrc 文件?

首先,确保

使用
   npm install react --save 

然后在 Web 包配置文件中,请在query中包含类似于以下内容的presets

   module.exports = {
entry: 'main.jsx',
output: {
    // Output the bundled file.
    path: './src',
    // Use the name specified in the entry key as name for the bundle file.
    filename: 'bundle.js'
},
module: {
    loaders: [{
        test: /'.jsx?$/,
        exclude: /node_modules/,
        loader: 'babel',
        query: {
            presets: ['react']
        }
    }]
},
externals: {
    // Don't bundle the 'react' npm package with the component.
    'react': 'React'
},
resolve: {
    // Include empty string '' to resolve files by their explicit extension
    // (e.g. require('./somefile.ext')).
    // Include '.js', '.jsx' to resolve files by these implicit extensions
    // (e.g. require('underscore')).
    extensions: ['', '.js', '.jsx']
}
}; 

因此,通过给出的所有反馈,我能够弄清楚。 感谢所有回答的人。

这是我需要做的:

npm install babel-preset-es2015

npm install babel-preset-react

并创建一个 .babelrc 文件(感谢 azium 和 Kreozot

`{
  "presets": [
    "react",
    "es2015"
  ]
}`

我想我们正在观看Samer Buna的同一课程"React.js on Rails: Building a Full Stack Web App"

为了解决这个问题,我安装了以下模块:

npm install react --save

npm install babel-preset-es2015

npm install babel-preset-react

我正在使用此配置https://jsfiddle.net/daronwolff/11tgotvz/

感谢@milad-rezazadeh和@chrissavage