Uncaught SyntaxError: Unexpected token 'export' in wasm.js file when trying to build a chrome extension

34 views Asked by At

I am trying to build a chrome extension using Rust and Wasm. The extension is supposed to add an authorization header to web requests.

Cargo.toml:

[package]
name = "chrome-extension"
version = "0.1.0"
edition = "2018"

[lib]
crate-type = ["cdylib", "rlib"]

[dependencies]
wasm-bindgen = "0.2.78"

[dependencies.web-sys]
version = "0.3"
features = [
    "console",
    "WorkerGlobalScope",
    "Window",
    'Headers',
    'Request',
    'RequestInit',
    'RequestMode',
    'Response',
]

src/lib.rs:

use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use web_sys::{Request, RequestInit};

#[wasm_bindgen]
extern "C" {
    #[wasm_bindgen(js_namespace = console)]
    fn log(s: &str);
}

#[wasm_bindgen]
pub fn add_authorization_header(request: &Request) -> Result<Request, JsValue> {
    let headers = request.headers();
    let headers_clone = headers.clone();
    headers_clone.set("Authorization", "Bearer <token>")?;
    let mut init = RequestInit::new();
    init.method(request.method().as_str());
    init.headers(&headers_clone);
    Request::new_with_str_and_init(request.url().as_str(), &init)
}

The build command I am using:

wasm-pack build --no-typescript --out-dir ./wasm --target web --out-name wasm

This correctly generates wasm.js and wasm_bg.wasm.

When I add this extension to chrome and try to make a web request, I get below error pointing to wasm.js

Uncaught SyntaxError: Unexpected token 'export' on below line.

export function add_authorization_header(request)

If I comment out the export word (which I shouldn't), I then get:

cannot use import outside of a module for below line in wasm.js
    
input = new URL('wasm_bg.wasm', import.meta.url);

Am I not building the Wasm correctly? What's going wrong here?

1

There are 1 answers

0
pr0gramista On

The --target web outputs the code as an ES module. You can still use it without a bundler directly in the browser, but you need to mark script as a module.

<html>
  <head>
    <meta content="text/html;charset=utf-8" http-equiv="Content-Type"/>
  </head>
  <body>
    <!-- Note the usage of `type=module` here as this is an ES6 module -->
    <script type="module">
      // Use ES module import syntax to import functionality from the module
      // that we have compiled.
      //
      // ...
    </script>
  </body>
</html>

You can also try to use --target no-modules, though it support less features.

See docs for complete examples: https://rustwasm.github.io/docs/wasm-bindgen/examples/without-a-bundler.html