Giter VIP home page Giter VIP logo

vite-rust-plugin's Introduction

vite-rust-plugin

Vite plugin for Rust

Requirement

You need wasm-pack for Rust compile to WebAssembly.

Install

npm install --save-dev vite-rust-plugin

Usage

1. Creating cargo in your project

cargo new rust --lib

Add the following to Cargo.toml.

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

[dependencies]
wasm-bindgen = "^0.2"

src/lib.rs

use wasm_bindgen::prelude::*;

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

#[wasm_bindgen(start)]
pub fn start() {
    log("hello wasm :)");
}

2. Setting vite.config.js

import { defineConfig } from 'vite';
import ViteRustPlugin from 'vite-rust-plugin';

export default defineConfig({
    base: './',
    plugins: [
        new ViteRustPlugin({
            crateDir: './rust',
            extraArgs: '--no-typescript',
        }),
    ],
});

3. Setting index.html

The target bundle of wasm-pack build is not yet supported. Therefore, it is necessary to manually import using target web.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>My App</title>
    </head>

    <body>
        <div id="app"></div>
        <h1>Hello</h1>
        <script type="module">
            import init from './rust/pkg';
            (async function () {
                await init();
            })();
        </script>
    </body>
</html>

4. Start dev server

vite --open

5. Build for production

vite build

vite-rust-plugin's People

Contributors

whtsht avatar

Watchers

 avatar

vite-rust-plugin's Issues

"Now compiling. Please wait..." No wasm is included when building with vite.

When trying to setup a base project with this plugin, the plugin works as expected when running a dev server. However, when the project is built using npm, none of the wasm is included in the final build. When running the built site, none of the rust wasm code is executed and instead, only the string "Now compiling. Please wait..." is logged to the console. This issue occurred both in a project that I setup manually and cloned from the provided template.

The only two files generated when built are shown below. Note that the javascript file is actually all one line, however I've formatted it to be (somewhat) human readable.

index.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>My App</title>
  <script type="module" crossorigin src="./assets/index.15345b7d.js"></script>
</head>

<body>
  <h1>Hello</h1>
  <div id="app"></div>
  
</body>

</html>

assets\index.15345b7d.js

const s = function() {
    const o = document.createElement("link").relList;
    if (o && o.supports && o.supports("modulepreload")) return;
    for (const e of document.querySelectorAll('link[rel="modulepreload"]')) n(e);
    new MutationObserver(e => {
        for (const t of e)
            if (t.type === "childList")
                for (const r of t.addedNodes) r.tagName === "LINK" && r.rel === "modulepreload" && n(r)
    }).observe(document, {
        childList: !0,
        subtree: !0
    });

    function i(e) {
        const t = {};
        return e.integrity && (t.integrity = e.integrity), e.referrerpolicy && (t.referrerPolicy = e.referrerpolicy), e.crossorigin === "use-credentials" ? t.credentials = "include" : e.crossorigin === "anonymous" ? t.credentials = "omit" : t.credentials = "same-origin", t
    }

    function n(e) {
        if (e.ep) return;
        e.ep = !0;
        const t = i(e);
        fetch(e.href, t)
    }
};
s();

function l() {
    console.log("Now compiling. Please wait...")
}(async function() {
    await l()
})();

Steps to Reproduce

  1. Clone the project template
  2. Run npm install
  3. Run npm run build
  4. Run a server from this newly created dist directory.
    1. I did this by adding "preview": "vite preview", to the scripts section of package.json and running npm run preview but this can alternatively be done by any HTML server.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.