rustwasm / book

The Rust and WebAssembly Book
https://rustwasm.github.io/docs/book/
MIT License
1.73k stars 208 forks source link

Universe.new is not a function #211

Open jp3492 opened 4 years ago

jp3492 commented 4 years ago

Describe the bug In the implementing life section I've ran into this error when trying to create a new Universe from the wasm-game-of-life package: Error importing index.js: TypeError: "wasm_game_of_life__WEBPACK_IMPORTED_MODULE_0__.Universe.new is not a function"

To Reproduce Follow the tutorial as described

Expected behavior It is supposed to show the Universe rendered into the html page but I receive the error as stated above

Screenshots If applicable, add screenshots to help explain your problem.

Additional context Error importing index.js: TypeError: "wasm_game_of_life__WEBPACK_IMPORTED_MODULE_0__.Universe.new is not a function"

webpack:///./index.js?:6 js http://localhost:8080/0.bootstrap.js:34 __webpack_require__ http://localhost:8080/bootstrap.js:81 bootstrap.js:5:23 webpack:///./bootstrap.js?:5
mydnicq commented 4 years ago

I have the same error. Even the typescript definition file doesn't have all Universe's pub methods defined:

export enum Cell {
  Dead,
  Alive,
}
export class Universe {
  free(): void;
}

Don't know from where free method was taken from?

mydnicq commented 4 years ago

The root of this problem is in this block of code:

impl Universe {
    fn get_index(&self, row: u32, column: u32) -> usize {
        (row * self.width + column) as usize
    }

    // ...
}

What is missing here is #[wasm_bindgen] annotation before the impl block. Further examples of this block have the required annotation so when you start using this tutorial you can easily overlook this detail.

collinco commented 4 years ago

Awesome, just got me unstuck. To add on to this, #[wasm_bindgen] is only needed in blocks containing public methods. see #164.

JamieCrisman commented 3 years ago

Thanks @tadejstanic This snagged me too!

YesSeri commented 3 years ago

When I do the tutorial, it gives me an error if I add the #[wasm_bindgen] line. If I don't add it the program compiles, but it doesn't work. Nothing is displayed on screen. When I compile the program with #[wasm_bindgen], it does work in the first part of the tutorial with the \

 but it doesn't work where it is rendered to the \.

What should I do?

Lazerbeak12345 commented 2 years ago

This is definitely the same issue as #265

Linking them to "link all the things"

Lazerbeak12345 commented 2 years ago

As for the canvas part of the issue, it worked for me.

nft2 commented 2 years ago

One thing that can cause this problem is forgetting to run wasm-pack build after you're done the Rust part of the code.

I did this tutorial over multiple days and forgot that was a thing. It produces the same error as OP is describing.