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

时间:2018-09-20 03:44:22

标签: preact

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

我的理解是,无论我在哪里使用JSX定义了组件,都需要在文件顶部添加$ ldd apps/openssl not a dynamic executable $ file apps/openssl apps/openssl: ELF 64-bit LSB executable, x86-64, version 1 (GNU/Linux), statically linked, for GNU/Linux 3.2.0, BuildID[sha1]=7c1d00e83b29cd1deaff2248cc8db8bbfc099d81, not stripped

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

有人让我直奔这里,因为我现在有点困惑-也许幕后某个地方发生了一些魔术?

2 个答案:

答案 0 :(得分:4)

当您编写类似jsx的语法时

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

在屏幕后面,它将转换为

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

那么,何时需要导入h

每次使用jsx语法。由于它不是JavaScript规范的一部分,因此必须将其转换为等效的语法。哪一个是使用h预先执行,还是使用React.createElement做出反应。

正如您提到的,我们可以通过使用其他import插件使babel-plugin-jsx-pragmatic自动运行。

https://github.com/jmm/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',
    }],
  ],
}

答案 1 :(得分:0)

好吧,经过一番挖掘后,我发现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的导入是自动的,没有明确要求。很好,这是他们的文档中提到的!