Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

import { h } from preact - when is it necessary

Tags:

preact

I'm currently building a Preact PWA with the CLI.

My understanding was that wherever I have a component defined with JSX, I need to have import { h } from 'preact' at the top of the file.

I removed all instances of that import statement, yet the application still runs and builds perfectly fine.

Can someone set me straight here, as I'm a little confused now - perhaps there is some magic going on behind the scenes somewhere?

like image 967
dgb_nz Avatar asked Sep 20 '18 03:09

dgb_nz


Video Answer


2 Answers

When you write a jsx syntax like

render() {
  return <div id="abc">Hello World</div>
}

Behind the screen it will be converted to

render() {
  return h('div', { id: 'abc' }, 'Hello World')
}

So, when it is necessary to import h?

The answer is Every time you use a jsx syntax. JSX is not part of the JavaScript spec, it have to be converted to the equivalent function call. Which in preact using h or in react using React.createElement.

As you mention, we can make the import automatic by using additional babel-plugin-jsx-pragmatic plugin.

module.exports = {
  presets: [],
  'plugins': [
    ['@babel/plugin-transform-react-jsx', { pragma: 'h' }],
    ['babel-plugin-jsx-pragmatic', {
      module: 'preact',
      import: 'h',
      export: 'h',
    }],
  ],
}

Learn more at: https://github.com/jmm/babel-plugin-jsx-pragmatic

like image 106
Yana Agun Siswanto Avatar answered Sep 20 '22 14:09

Yana Agun Siswanto


Ok, after some digging around I see there is a babel-config in the preact-cli node module, which is adding the following code:

plugins: [ [require.resolve('babel-plugin-transform-react-jsx'), { pragma: 'h' }], [require.resolve('babel-plugin-jsx-pragmatic'), { module: 'preact', export: 'h', import: 'h' }] ]

It appears to mean imports of h are automatic and not explicitly required. Would be nice it this were mentioned in their documentation!

like image 27
dgb_nz Avatar answered Sep 24 '22 14:09

dgb_nz