Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Migrating to preactjs

I have a universal react app where server side is built in babel and the client bundle is built in webpack. I have read preact-compact docs and it suggests to adding this in .babelrc for building using babel:

{
  "plugins": [
    [
      "transform-react-jsx",
      {
        "pragma": "h"
      }
    ],
    [
      "module-resolver",
      {
        "root": [
          "."
        ],
        "alias": {
          "react": "preact-compat",
          "react-dom": "preact-compat"
        }
      }
    ]
  ],
  "presets": [
    "react"
  ]
}

And for webpack:

{
  "resolve": {
    "alias": {
      "react": "preact-compat",
      "react-dom": "preact-compat"
    }
  }
}

But after building I get an error h is not defined

How to migrate to preact for a universal react app

like image 247
guru107 Avatar asked Feb 16 '17 14:02

guru107


Video Answer


1 Answers

But after building i get an error "h is not defined"

You added the transform-react-jsx plugin to your babel config.

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

This tells babel how to transpile your JSX code. For that to work, the function h needs to be in scope, that means you need to import it in every file you use JSX.

import { h } from 'preact';

Instead of having to change all your code that uses React, you can use preact-compat and alias both react and react-dom to preact-compat, as you did correctly, either with babel-plugin-module-resolver or with webpack. With that you can use react and react-dom in your code and preact-compat does the rest for you.

In order to make it work you have to remove ["transform-react-jsx", { "pragma":"h" }] from your babel config.

like image 147
Michael Jungo Avatar answered Oct 07 '22 05:10

Michael Jungo