How to use Preact with Laravel Mix
Ostap Brehin
Posted on October 23, 2020
Update 2023: I highly advise using Vite with their official preset, as it's much easier to configure and miles faster than Webpack.
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
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');
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);
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>
That's all, happy coding! :)
Posted on October 23, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.