Laravel 5.6集成React后使用箭头函数出现语法错误求助
Hey there, let's get that arrow function syntax error sorted out for you! This issue pops up because Laravel 5.6's default Babel setup doesn't handle class property arrow functions out of the box—those are the ones where you define a class method like handleClick = () => {} directly in your component class.
Here's how to fix it step by step:
1. Install the required Babel plugin
First, you need to add the plugin that handles class properties syntax. Open your terminal and run this command:
npm install @babel/plugin-proposal-class-properties --save-dev
If you prefer Yarn, use this instead:
yarn add @babel/plugin-proposal-class-properties --dev
2. Update your Laravel Mix configuration
Next, tell Laravel Mix to use this new plugin. Open your webpack.mix.js file and modify the react() call to include a Babel config:
mix.react('resources/js/app.js', 'public/js') .babelConfig({ plugins: ['@babel/plugin-proposal-class-properties'] });
3. Recompile your assets
Finally, rebuild your front-end resources to apply the changes. Run one of these commands depending on your environment:
- For development (with auto-reload):
npm run watch - For a one-time development build:
npm run dev - For production (minified assets):
npm run production
That should resolve the syntax error! Just to confirm, this fixes code like this in your React components:
class ExampleComponent extends React.Component { // This arrow function as a class property was causing the error handleSubmit = (e) => { e.preventDefault(); // Your logic here } render() { return ( <form onSubmit={this.handleSubmit}> {/* Form content */} </form> ); } }
内容的提问来源于stack exchange,提问作者Kallol Pratim

