Webpack does not work when entering React

I followed the basic webpack guide and I have a server up and running. When I change files, it will be updated when saved, everything is fine. However, I introduced React back then, and it all went wrong.

Firstly, I get this error in the browser:

Unexpected token < You may need an appropriate loader to handle this file type. 

This points to line 4 in the entry.js file:

 var CommentBox = React.createClass({ render: function() { return ( <div className="commentBox"> Hello, world! I am a CommentBox. </div> ); } }); ReactDOM.render( <CommentBox />, document.getElementById('content') ); 

This is index.html

 <html> <head> <meta charset="utf-8"> </head> <body> <div id ="content"></div> <script type="text/javascript" src="bundle.js" charset="utf-8"></script> </body> </html> 

webpack.config.js:

 module.exports = { entry: "./entry.js", output: { path: __dirname, filename: "bundle.js" }, module: { loaders: [ { test: /\.jsx?$/, loader: 'jsx-loader?insertPragma=React.DOM&harmony' } ] }, externals: { 'react': 'React' }, resolve: { extensions: ['', '.js', '.jsx'] } }; 

If I entry.js file to just contain:

 document.write(require("./content.js")); 

It creates what I have in the content.js file:

 module.exports = "this is working"; 

So this has something to do with the / jsx reaction, etc. Has anyone got any solutions? I have seen other people on the Internet with this problem, but the solutions provided have not yet worked.

+5
source share
2 answers

Webpack and jsx-loader

webpack.config.js

 module.exports = { entry: './app.js', output: { path: __dirname, filename: 'bundle.js' }, module: { loaders: [{ test: /\.js/, loader: 'jsx-loader' }] } } 

app.js

 var React = require('react'); var App = React.createClass({ render: function() { return <h1>Hello World</h1> } }) React.render(<App/>, document.getElementById('app')) 

and a simple index.html file with a <div>

You might want to use React with ES6 syntax (React webpack and babel), so I hope my post will be useful to you.

Update:

As FakeRainBrigand jsx-loader , it would be nice if you try to use the babel loader instead of jsx-loader

thanks

+2
source

As FakeRainBrigand said jsx-loader deprecated, if you want to convert es6 or jsx, you probably want to use babel-loader . And since Babel 6 has been released now, you will have to explicitly declare which conversion to perform by setting the β€œpresets” in the .babelrc file as follows:

$ npm install --save-dev babel-loader

$ npm install --save-dev babel-preset-es2015

$ npm install --save-dev babel-preset-react

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

webpack.config.js

 module: { loaders: [ { test: /\.css$/, loader: "style!css" }, { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/, query: { presets: ['es2015'] } }, { test: /\.jsx$/, loader: 'babel-loader', exclude: /node_modules/, query: { presets: ['react'] } }, ] }, 
+2
source

Source: https://habr.com/ru/post/1236601/


All Articles