18910140161

JavaScript-在这种情况下,我如何在没有React的情况下使用WebPack?-堆栈溢出

顺晟科技

2022-10-18 12:40:07

152

我创建了一个这样的简单文件:

function Welcome() {
  return <h1>Hello, World</h1>;
}

然而,当我运行webpack时,它说:

Add @babel/preset-react (https://git.io/JfeDR) to the 'presets' section of your Babel config to enable transformation.

它要求我添加反应。

我想开发纯JavaScript/JSX/XML/HTML/CSS,并使用WebPack来捆绑我的函数和类,而不使用React.

怎么能这么做?

为什么webpack需要为我的简单功能做出反应?


顺晟科技:

对于您的用例,

您可能仍然需要@babel/preset-react。这个预设实际上不限于处理React JSX,它可以处理一般的JSX.

您需要修改选项以满足您的需要。我从文档中复制粘贴了以下内容。注意"pragma": "dom""pragmaFrag": "DomFrag"零件.

<代码>{";预设";:[[“@Babel/Preset-React ”,{";杂注";:";DOM";,//默认编译指示为react.createElement(仅在经典运行时中)";pragmafrag";:";domfrag";,//默认为react.fragment(仅在经典运行时中)";ThrowIfNamespace";:false,//默认为true";运行时:";经典";//默认为经典//";导入来源";:";自定义JSX-库";//默认为React(仅在自动运行时)}]]}

使用上述配置,您的代码将转换为:

{
  "presets": [
    [
      "@babel/preset-react",
      {
        "pragma": "dom", // default pragma is React.createElement (only in classic runtime)
        "pragmaFrag": "DomFrag", // default is React.Fragment (only in classic runtime)
        "throwIfNamespace": false, // defaults to true
        "runtime": "classic" // defaults to classic
        // "importSource": "custom-jsx-library" // defaults to react (only in automatic runtime)
      }
    ]
  ]
}
如果您使用片段

,如:

function Welcome() {
  return dom("h", null, "Hello, World");
}

它将被转化为:

function Welcome() {
  return (
    <>
      <div>hello</div>
      <div>world</div>
    </>
  )
}

当然,您需要在源文件中提供并手动导入function Welcome() { return dom( DomFrag, null, [ dom("div", null, "hello"), dom("div", null, "world") ] ) } dom

  • TAG:
相关文章
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航