从预设中导入{h}-何时需要

dgb*_*_nz 8 preact

我目前正在使用CLI构建Preact PWA。

我的理解是,无论我在哪里使用JSX定义了组件,都需要import { h } from 'preact'在文件顶部。

我删除了该import语句的所有实例,但该应用程序仍然可以运行并构建得很好。

就像我现在有些困惑一样,有人可以让我直觉到这里吗?也许幕后某个地方发生了一些魔术?

Yan*_*nto 10

当您编写类似jsx的语法时

render() {
  return <div id="abc">Hello World</div>
}
Run Code Online (Sandbox Code Playgroud)

在屏幕后面,它将转换为

render() {
  return h('div', { id: 'abc' }, 'Hello World')
}
Run Code Online (Sandbox Code Playgroud)

那么,什么时候有必要进口h

答案是每次您使用jsx语法。JSX不是JavaScript规范的一部分,必须将其转换为等效的函数调用。预先使用h或使用进行反应React.createElement

如您所述,我们可以import通过使用其他babel-plugin-jsx-pragmatic插件来实现自动。

module.exports = {
  presets: [],
  'plugins': [
    ['@babel/plugin-transform-react-jsx', { pragma: 'h' }],
    ['babel-plugin-jsx-pragmatic', {
      module: 'preact',
      import: 'h',
      export: 'h',
    }],
  ],
}
Run Code Online (Sandbox Code Playgroud)

了解更多信息:https : //github.com/jmm/babel-plugin-jsx-pragmatic


dgb*_*_nz 3

好吧,经过一番挖掘后,我发现 preact-cli 节点模块中有一个 babel-config,它添加了以下代码:

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

这似乎意味着导入h是自动的并且没有明确要求。如果他们的文档中提到了这一点,那就太好了!