question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Typescript example

See original GitHub issue

Seems that ts-loader and/or awesome-typescript-loader don’t play nicely with the async->sync import solution bindgen produces.

This was already raised and closed here: https://github.com/rustwasm/wasm-bindgen/issues/700 but it might be helpful to have a Typescript boilerplate as a reference someday 😃

Issue Analytics

  • State:open
  • Created 5 years ago
  • Reactions:4
  • Comments:6

github_iconTop GitHub Comments

23reactions
emkcommented, Oct 3, 2018

TL;DR: The magic tricks are:

  • "module": "esNext" in tsconfig.json
  • await import('./mymod')
  • typeof import('./mymod')

Details

In your tsconfig.json, set "module": "esNext" so that you can use async import(...):

{
  "compilerOptions": {
    "target": "es5",
    "module": "esNext",
    "lib": ["dom", "es2015"],
    "strict": true,  
    "esModuleInterop": true
  }
}

In your webpack.config.js, enable ts-loader (as per the usual instructions) and the experimental built-in *.wasm loader:

  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/
      },
      {
        test: /\.wasm$/,
        type: "webassembly/experimental"
      }
    ]
  },
  resolve: {
    extensions: [ '.tsx', '.ts', '.js', '.wasm' ]
  },

Finally, let’s assume you have the following files generated by wasm-bindgen:

  • mymod.js
  • mymod.d.ts
  • mymod_bg.wasm

Then you can use a structure like this in your top-level *.ts file:

function start(mymod: typeof import('./mymod')) {
    console.log("All modules loaded");
    mymod.my_exported_rust_function();
}

async function load() {
    start(await import('./mymod'));
}

load();

The magic trick here is typeof import('./mymod'), which allows you declare the type of the asynchronously-loaded module.

I’d be happy to try to turn this into a fully-worked test case that can run on CI and that can be used as example, but it might need to wait a few days until I have time.

7reactions
d-doraziocommented, Oct 12, 2018

wasm-pack-plugin version 0.1.0 was recently released and among other improvements, it now has the option to configure wasm-pack to generate TypeScript bindings that can be used in your code.

Here’s an example webpack configuration to make use of it:

webpack.config.js

const path = require("path");
const WasmPackPlugin = require("@wasm-tool/wasm-pack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  entry: "./index.ts",
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "bundle.js"
  },
  plugins: [
    new HtmlWebpackPlugin(),
    new WasmPackPlugin({
      crateDirectory: path.resolve(__dirname, "."),
      withTypeScript: true // this is new
    }),
  ],
  resolve: {
    extensions: [".ts", ".tsx", ".js", ".wasm"]
  },
  module: {
    rules: [{
      test: /\.tsx?$/,
      loader: "ts-loader"
    }]
  }
};

tsconfig.json

{
    "compilerOptions": {
        "module": "esnext", // needed to have dynamic imports
        "lib": [
            "dom",
            "es2015"
        ]
    },
    "files": [
        "./index.ts"
    ]
}

example index.ts

import("./pkg/yourlib").then(module => {
  // won't typecheck if yourlib does not expose the run function
  module.run();
});

Read more comments on GitHub >

github_iconTop Results From Across the Web

Documentation - TypeScript for JavaScript Programmers
TypeScript knows the JavaScript language and will generate types for you in many cases. For example in creating a variable and assigning it...
Read more >
Typescript example: Beginners Guide To ... - AppDividend
Typescript is a typed superset of Javascript that compiles to plain JavaScript. TypeScript is open source language maintained by Microsoft.
Read more >
TypeScript Tutorial - W3Schools
Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, Python,...
Read more >
TypeScript Tutorial - Tutorialspoint
TypeScript is pure object oriented with classes, interfaces and statically typed like C# or Java. The popular JavaScript framework Angular 2.0 is written...
Read more >
TypeScript Tutorial: What is, Interface, Enum, Array with Example
Above TypeScript example throws an error, but the same would have worked fine if it was with the var keyword. Variables using let...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found