17

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?

dgb_nz
  • 231
  • 2
  • 11

2 Answers2

24

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

Yana Agun Siswanto
  • 1,932
  • 18
  • 30
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!

dgb_nz
  • 231
  • 2
  • 11
  • 1
    There is indeed documentation on this. https://github.com/developit/preact#import-what-you-need – rbenvenuto Sep 26 '18 at 20:41
  • Updating @rbenvenuto's comment: https://github.com/preactjs/preact/tree/e026d9e1a871a3f84fb88a499168b4af083673f6#import-what-you-need – spences10 Feb 20 '20 at 17:11