将preact与babel-独立使用

ctrmrzij  于 2022-12-20  发布在  Babel
关注(0)|答案(1)|浏览(138)

我试着让preact和babel-standalone一起工作,这意味着我必须为preact加载一个新的preset
我不知道如何用Babel.registerPreset加载这个预设。
临时解决方案是在babel独立源中使用“h”(React. createElement的preact等效项)重命名“React.createElement”。
你知道如何用Babel.registerPreset加载预置或创建自己的预置吗?

qij5mzcb

qij5mzcb1#

这是直接在浏览器中使用cdn中的Preact和Babel,无需构建。您甚至可以从文件(drawing.js)导入组件。
无法让它在代码段中运行,但只需创建三个文件:索引. html、索引. js和绘图. js
index.js

window.React = { createElement: preact.h }
const { Drawing } = await imp("./drawing.js");

const App = () => {
    return (
      <div>
        <h1>Just a test</h1>  
        <Drawing/>      
      </div>
    );
  };

  
  preact.render(<App/>, document.body);

  async function imp(path, requestOrigin) {
    const { href } = new URL(
      path,
      requestOrigin
        ? requestOrigin.slice(0, requestOrigin.lastIndexOf("/"))
        : location.href
    ); // so the paths won't be messed up
    const res = await fetch(href);
    const text = await res.text();
    const { code } = Babel.transform(text, { presets: ["react"] });
    return await import(
      `data:application/javascript,${encodeURIComponent(code)}`
    );
  }
<!DOCTYPE html>
<html>
<head>
  <title></title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/preact/7.2.0/preact.js"></script>
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
  <script>
    async function imp(path, requestOrigin) {
      const { href } = new URL(
        path,
        requestOrigin
          ? requestOrigin.slice(0, requestOrigin.lastIndexOf("/"))
          : location.href
      ); // so the paths won't be messed up
      const res = await fetch(href);
      const text = await res.text();
      const { code } = Babel.transform(text, { presets: ["react"] });
      return await import(
        `data:application/javascript,${encodeURIComponent(code)}`
      );
    }
  </script>
  <script defer type="text/babel" data-type="module" src="index.js"></script>
</head>
<body>
  <div id='root'></div>
  
</body>
</html>
export function Drawing() {
    return <p>Random drawing</p>;
  }

相关问题