reactjs EsBuild启动服务替换

tp5buhyn  于 2023-06-29  发布在  React
关注(0)|答案(4)|浏览(108)

我是esBuild和ReactJS的新手,根据一个guid,我决定构建一个自定义的CLI Transpiling应用程序。我到了这一点,我在textarea中输入文本,但在客户端的控制台上出现以下错误消息主机版本“0.8.27”与二进制版本“0.9.0”不匹配。我知道我使用的是一个旧版本,我确实试图找到一种方法来解决这个问题,首先通过文档,因为他们已经完全抛弃了新版本上的startService()方法。但我找不到任何可能的解决方案,我的问题,有没有人与知识,以帮助我解决这个问题。下面是我的代码,它必须开始转译:

const startService = async () => {
ref.current = await esbuild.startService({
  worker: true,
  wasmURL: '/esbuild.wasm'
})
  }

 useEffect(() => {
    startService()
  }, [])

  const onClick = async () => {
    if (!ref.current) {
      return;
    }
    const result = await ref.current.build({
      entryPoints: ['index.js'],
      bundle: true,
      write: false,
      plugins: [unpkgPathPlugin()]
    })
    console.log(result );
    setCode(result)
  }
vmpqdwk3

vmpqdwk31#

在浏览器中运行esbuild的文档在这里:https://esbuild.github.io/api/#running-in-the-browser0.9.0版本中,esbuild.startService()变为esbuild.initialize()service.build()变为esbuild.build()(即显式服务对象消失)。因此,更新后的代码可能看起来像这样:

const startService = async () => {
  await esbuild.initialize({
    worker: true,
    wasmURL: '/esbuild.wasm'
  })
  ref.current = true
}

useEffect(() => {
  startService()
}, [])

const onClick = async () => {
  if (!ref.current) {
    return;
  }
  const result = await esbuild.build({
    entryPoints: ['index.js'],
    bundle: true,
    write: false,
    plugins: [unpkgPathPlugin()]
  })
  console.log(result);
  setCode(result)
}
dddzy1tm

dddzy1tm2#

请注意,在浏览器中运行时没有可用的异步API。另外,我不想每次在编辑时热重新加载时都抛出“已经初始化”。这是我如何设置的:

import { useState, useEffect } from 'react';
import './App.css';
import * as esbuild from 'esbuild-wasm';

function App() {
  const [input, setInput] = useState('');
  const [code, setCode] = useState('');

  useEffect(() => {
    // This ugly code is to avoid calling initialize() more than once
    try {
      esbuild.build({});
    } catch (error) {
      if (error instanceof Error && error.message.includes('initialize')) {
        esbuild.initialize({
          worker: false,
          wasmURL: '/esbuild.wasm',
        });
      } else {
        throw error;
      }
    }
  }, []);

  const onClick = () => {
    esbuild
      .transform(input, {
        loader: 'jsx',
        target: 'es2015',
      })
      .then((result) => {
        setCode(result.code);
      });
  };

  return (
    <div className="App">
      <textarea
        value={input}
        onChange={(e) => setInput(e.target.value)}></textarea>
      <div>
        <button onClick={onClick}>Submit</button>
      </div>
      <pre>{code}</pre>
    </div>
  );
}

export default App;
t3irkdon

t3irkdon3#

伙计们,我有一个更好的解决方案,你可以热重新加载,没有错误。

const startService = async () => {
if (!window.isEsbuildRunning) {
    await esbuild.initialize({
      worker: true,
      wasmURL: '/esbuild.wasm'
    })
}
    window.isEsbuildRunning = true;
    ref.current = true
  }
  
  useEffect(() => {
    startService()
  }, [])
  
  const onClick = async () => {
    if (!ref.current) {
      return;
    }
    const result = await esbuild.build({
      entryPoints: ['index.js'],
      bundle: true,
      write: false,
      plugins: [unpkgPathPlugin()]
    })
    console.log(result);
    setCode(result)
  }
qfe3c7zg

qfe3c7zg4#

想出了一个更好的办法:

import * as esbuild from "esbuild-wasm";

const startService =  (() => {
    let esBuildRef: any;
    return async() => {
        if (esBuildRef) {
            return esBuildRef
        } else {
            await esbuild.initialize({
                worker: true,
                wasmURL: "./esbuild.wasm"
            });
            esBuildRef = esbuild;
            return esBuildRef;
        }
    }
})()

export default startService;

使用它就像

import { useState, useEffect } from 'react';
import startService from './plugins/esbuild';

export default function Home() {
  const [input, setInput] = useState('');
  const [code, setCode] = useState('');

  const submitHandler = async() => {
    const esBuildRef =  await startService();
    console.log(esBuildRef);
    const result = await esBuildRef.transform(input, {
      loader: 'jsx',
      target: 'es2015'
    })
    setCode(result.code);
  }

  return (
    <main>
      <textarea value = {input} onChange={(e) => setInput(e.target.value)}>

      </textarea>
      <div onClick={submitHandler}>
        Submit
      </div>
      <pre>
        {code}
      </pre>
    </main>
  )
}

单例模式

相关问题