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?
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
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With