7

I am new to esBuild and ReactJS and following a guid I decided to building a custom CLI Transpiling application. I got to the point that I am entering a text in textarea but on the console in the client the following error message came out Host version "0.8.27" does not match binary version "0.9.0". I know that I am using an older version, I did try to find a way to resolve the problem first with going trough the documentation since they have completly throw away the startService() method on the new version. But I couldn't find any possible solution to my problem, is there someone with the knowledge to help me solve the problem. Here is my code which has to start the transpiling:

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)
  }
DraksBG
  • 137
  • 1
  • 9

4 Answers4

16

The documentation for running esbuild in the browser is here: https://esbuild.github.io/api/#running-in-the-browser. In version 0.9.0, esbuild.startService() became esbuild.initialize() and service.build() became esbuild.build() (i.e. the explicit service object disappeared). So updated code might look something like this:

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)
}
constexpr
  • 1,021
  • 10
  • 7
  • 1
    I had the same issue, I replaced `esbuild.startService` with `esbuild.initialize` so that part was sought out, the only issues now that I'm facing is that `ref.current` is coming out to be undefined. Any idea what might be causing that? – Prhyme Jul 09 '21 at 20:58
  • 2
    The esbuild.initialize function doesn't return anything. There is no longer a way to get a handle to the service object. – Cameron O'Rourke Oct 08 '21 at 16:06
1

Note that there is no async API available when running in the browser. Also, I didn't want to be throwing 'already initialized' every time I hot reloaded while editing. This is how I set this up:

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;

  • it's running twice because React runs useEffect twice in `React.StrictMode`. A better solution to this than try...catch is to use ref like in the post above. – Sumit Wadhwa May 03 '22 at 12:43
0

Guys I have a better solution, you can hot reload, and no errors.

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)
  }
0

Came up with a better way:

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;

use it like


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>
  )
}

Singleton pattern

user3124360
  • 353
  • 4
  • 10