Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to bundle some React components with webpack.

But when I launch webpack --mode=development, i get this error :

Module parse failed: Unexpected token (6:4) You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders | const OwnButton = () => { | return ( <Button color='secondary' variant='outlined'

This is my webpack config :

const path = require('path');

module.exports = {
   entry: './src/app.js', // relative path
   output: {
      path: path.join(__dirname, 'public'), // absolute path
      filename: 'js/bundle.js' // file name
   },
   module: {
      rules: [
         {
            test: /.js$/,
            exclude: /node_modules/,
            loader: 'babel-loader'
         }
      ]
   }
};

This is my app.js config :

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import Button from '@material-ui/core/Button';
import OwnButton from './Components/OwnButton';

const template = <Button>Hello from react jsx</Button>;

ReactDOM.render(template, document.getElementById('root'));
ReactDOM.render(<OwnButton/>, document.getElementById('React-OwnButton'));

And the wanted component (index.jsx) :

import Button from '@material-ui/core/Button';

const OwnButton = () => {
  return (
    <Button color='secondary' variant='outlined'>
      Hello from my own component
    </Button>
  );
};

export default OwnButton;

And my .babelrc

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

I don't understand how the call l.6 on app.js can work but not the on index.jsx l.6.

Where must I put the loader for this, in babel?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
171 views
Welcome To Ask or Share your Answers For Others

1 Answer

The problem is that you configured the Babel Loader to only intervene for .js files.

Try changing: test: /.js$/ -> test: /.((js)|(jsx))$/

This will make the loader work for .jsx files too.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...