Error in loaders in webpack

1

I want to set up a project in React from scratch.

Launches the following error:

ERROR in ./src/js/main.js
Module build failed: SyntaxError: Unexpected token (5:4)

  3 | 
  4 | ReactDOM.render(
> 5 |     <h1>Hello, world!</h1>,
    |     ^
  6 |     document.getElementById('app')
  7 | );

npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! [email protected] build: 'webpack --config webpack.config.js'
npm ERR! Exit status 2
npm ERR! 
npm ERR! Failed at the [email protected] build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

Package.json:

{
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack --config webpack.config.js"
  },
  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.4",
    "babel-preset-env": "^1.6.1",
    "webpack": "^4.3.0",
    "webpack-cli": "^2.0.13"
  },
  "dependencies": {
    "react": "^16.2.0",
    "react-dom": "^16.2.0"
  }
}

Webpack.config.js:

const path = require('path');

module.exports = {
    entry: './src/js/main.js',
    output: {
        filename: 'script.js',
        path: path.resolve(__dirname, 'dist/js')
    },
    module: {
        rules: [{
            test: /\.js$/,
            exclude: /node_modules/,
            use:{
                loader: "babel-loader",
            }
        }]
    }
};


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

ReactDOM.render(
    <h1>Hello, world!</h1>,
    document.getElementById('app')
);
    
asked by Franklin'j Gil'z 28.03.2018 в 22:07
source

1 answer

1

React uses an extension on JavaScript called JSX that allows you to define tags similar to HTML. To work with these scripts it is necessary to transform the code.

In your webpack.config.js you have associated the babel-loader for the .js files. In addition, you must include a plugin for transform JSX or a Babel preset for react (which includes the previous plugin and other useful ones) in the configuration of the loader .

Example using babel-loader with preset-react to work with script that includes JSX syntax. The babel-preset-env is also included to transpile the JavaScript version.

You must include a .babelrc file in your project to set the babel-loader :

.babelrc

{
    "presets": ["babel-preset-env", "babel-preset-react"]
}

Packages of Babel required as devDependencies :

  • babel-core
  • babel-loader
  • babel-preset-env
  • babel-preset-react

I recently answered about a similar problem where an appropriate loader was required to handle the jsx file. Read answer .

You can also check the settings of

answered by 29.03.2018 / 18:42
source