DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,673 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Ostap Brehin
Ostap Brehin

Posted on

How to use Preact with Laravel Mix

In this article, I share my configuration for Preact usage with Laravel Mix.

Install these dependencies before you get started:

  • preact
  • @babel/plugin-proposal-class-properties
  • @babel/preset-react

You can do it with this command:

npm install preact @babel/plugin-proposal-class-properties @babel/preset-react
Enter fullscreen mode Exit fullscreen mode

Next, add this content to your webpack.mix.js

// webpack.mix.js
const mix = require('laravel-mix');

mix.webpackConfig({
    "resolve": {
        "alias": {
            "react": "preact/compat",
            "react-dom": "preact/compat"
        }
    }
});

mix.babelConfig({
    "plugins": [
        "@babel/plugin-proposal-class-properties"
    ],
});

mix.react('resources/js/app.js', 'public/js');
Enter fullscreen mode Exit fullscreen mode

And here is an example app component, you can store it in resources/js/app.js file:

// app.js
import { h, render, Component } from 'preact';

window.React = require('preact');

class App extends Component {
    render() {
        return <h1>Preact from Laravel Mix</h1>;
    }
}

render(<App />, document.body);

Enter fullscreen mode Exit fullscreen mode

Note: As we set out rendering node as document.body, you should place your script tag inside <body> tag. If you need to place <script> tag in the <head> section - you will need to add defer attribute.

<body>
<script src="{{ mix('js/app.js') }}"></script>
</body>
Enter fullscreen mode Exit fullscreen mode

That's all, happy coding! :)

Top comments (1)

Collapse
 
abdes profile image
Zakari Abdessamad • Edited on

Thanks for the post ... but What's benfit of using "babel/plugin-proposal-class-properties"?

Head over to your dashboard

See your total reactions, views, and listings.