Using Preact with Laravel Mix

Joe Cohen
dotdev
Published in
2 min readOct 30, 2017

--

Preact it’s a “Fast 3kB alternative to React with the same ES6 API.” you can learn more here https://preactjs.com/

If you are using Laravel Mix which is an awesome wrapper for Webpack with a simple and clean API shipped with the Laravel Framework, you already have support for React. Preact has a nice tool called preact-compat that makes really easy transition from React to Preact.

In this post we will review how to follow the guide to use it with the current React preset that built in Laravel Mix.

You’ll probably start with the basic config on webpack.mix.js:

let mix = require(‘laravel-mix’);mix.react(‘app.js’, ‘dist/js’)
.version();

First we have to alias preact-compat to react and react-dom, to do that we need to extend the Webpack config in webpack.mix.js:

let mix = require('laravel-mix');
mix.webpackConfig({ 'resolve': { 'alias': { 'react': 'preact-compat', 'react-dom': 'preact-compat', }, }, }) .react('app.js', 'dist/js') .version();

If you have a React app and you are just migrating to Preact your app should be running by now with the same code you had importing react and react-dom.

If you are starting a project or completely switching to Preac you’ll probably want to change the render function on your app.js to use Preact simple rendering.

To do that we need to create a .babelrc file in our root project directory to configure the h function of Preact:

{  "plugins": [    ["transform-react-jsx", { "pragma": "h" }]  ]}

Now we can start our project with the Preact render function on the app.js file:

import { h, render } from 'preact';let root;
function init() { let App = require('./components/App').default; root = render(<App />, document.body, root);}// in development, set up HMR:if (module.hot) {
//require('preact/devtools'); // turn this on if you want to enable React DevTools!
module.hot.accept('./components/App', () => requestAnimationFrame(init) );}
init();

And that’s it, enjoy using Preact with Laravel Mix!

PS: I’ve made a PR to support Preact natively in Laravel Mix anyway you can use the solution shown in this post to fully work with it https://github.com/JeffreyWay/laravel-mix/pull/1294

--

--

Multipreneur passionate about technology, product, and customers with an engineer and designer background. I love helping to create and grow businesses.