import { h } from preact - when is it necessary
Asked Answered
W

2

18

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?

Witting answered 20/9, 2018 at 3:44 Comment(0)
P
25

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

Phillipp answered 1/11, 2018 at 10:44 Comment(0)
W
3

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!

Witting answered 20/9, 2018 at 4:51 Comment(2)
There is indeed documentation on this. github.com/developit/preact#import-what-you-needBaryon
Updating @rbenvenuto's comment: github.com/preactjs/preact/tree/…Solenoid

© 2022 - 2024 — McMap. All rights reserved.