Webpack模块构建失败的意外令牌(rails反应构建)

时间:2016-01-26 21:46:28

标签: javascript ruby-on-rails reactjs webpack babeljs

我正在进行react / rails构建,并首次使用webpack和babel。我使用了两个文件并获得错误

  

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

第6行是:<Greet />

这是main.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:

&#13;
&#13;
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" }
    ]
  }
};
&#13;
&#13;
&#13;

我没有babelrc文件?

3 个答案:

答案 0 :(得分:9)

首先确保使用

在解决方案中安装react,babble和其他依赖项
   npm install react --save 

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

   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']
}
}; 

答案 1 :(得分:5)

所以在给出所有反馈的情况下,我能够弄明白。谢谢所有回答的人。

以下是我需要做的事情:

npm install babel-preset-es2015

npm install babel-preset-react

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

&#13;
&#13;
`{
  "presets": [
    "react",
    "es2015"
  ]
}`
&#13;
&#13;
&#13;

答案 2 :(得分:0)

我认为我们正在观看相同的课程&Rails上的React.js:构建一个完整的堆栈Web应用程序&#39;作者:Samer Buna

要解决问题,我安装了这个模块:

npm install react --save

npm install babel-preset-es2015

npm install babel-preset-react

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

感谢@ milad-rezazadeh和@chrissavage