Here is a simple web app which was generated by typescript and cpp wasm.

This example displays how to load wasm module in TS.

Files in the project:

The logic of Loading wasm:

function App() {
  const [wasmModule, setWasmModule] = useState<WasmModule | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [workerCount, setWorkerCount] = useState(0);

  // Load WASM module when component mounts
  useEffect(() => {
    const loadWasm = async () => {
      try {
        console.log('Loading WASM module...');
        
        // Load the script as text and evaluate it
        const response = await fetch('/cppWasm.js');
        const scriptText = await response.text();
        
        // Create a script element and execute it
        const script = document.createElement('script');
        script.textContent = scriptText;
        document.head.appendChild(script);
        
        // Access the global createModule function
        const createModule = (window as any).createModule;
        const module = await createModule();
        
        console.log('WASM module loaded successfully:', module);
        setWasmModule(module);
        setError(null);
      } catch (err) {
        console.error('Failed to load WASM:', err);
        setError(err instanceof Error ? err.message : 'Unknown error');
      } finally {
        setLoading(false);
      }
    };

    loadWasm();
  }, []);

  // Function to create a new Worker instance
  const createWorker = () => {
    if (!wasmModule) {
      console.error('WASM module not loaded yet');
      return;
    }

    try {
      const cppObj = new wasmModule.Worker();
      console.log('Worker created:', cppObj);
      setWorkerCount(prev => prev + 1);
      cppObj.ShowMyself();
    } catch (err) {
      console.error('Failed to create worker:', err);
    }
  };

The project code has been uploaded to Github:

https://github.com/theArcticOcean/tutorials/tree/main/learnWebAssembly/use-wasm-in-ts

Categories: Web

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments

Tex To PDF
: convert the Latex file which suffix is tex to a PDF file

X
0
Would love your thoughts, please comment.x
()
x