Представлен инструмент wasm-pack для более глубокой интеграции JavaScript и Rust


Оглавление (нажмите, чтобы открыть):

Более глубокая интеграция JavaScript и Rust стала возможна с новым инструментом wasm-pack

Более глубокая интеграция JavaScript и Rust стала возможна с новым инструментом wasm-pack

Более глубокая интеграция JavaScript и Rust стала возможна с новым инструментом wasm-pack

Член команды Rust Core — Эшли Уильямс рассказала в Mozilla Hacks о новом инструменте для интеграции JavaScript и Rust — wasm-pack. Он предназначен для создания из проектов на Rust пакетов и публикации их в реестре npm. Исходный код уже опубликован на crates.io и GitHub.

Npm позволяет устанавливать пакеты для фронтенд-разработки. Он не умеет компилировать код на Rust, с этим помогает wasm. Однако создание npm-пакета для дальнейшего распространения — сложная задача, и wasm-pack упрощает работу.

По словам Уильямс, чтобы подготовить код на Rust для публикации пакета в реестре npm, необходимо пройти четыре шага: компиляция в WebAssembly, запуск wasm-bindgen, создание package.json, формирование документации — копирование README.md из Rust-проекта в npm-пакет.

Также отмечается, что проект в настоящее время активно развивается. В планах у разработчиков интеграция с rustdoc, расширение набора инструментов для работы в Rust с Node.js и так далее.

Наши специалисты готовы подобрать и поставить вам программное обеспечение как извесных разработчиков, так и «эксклюзивные» программные продукты

Запрос на программное обеспечение

Продажа лицензионного программного обеспечения, обслуживание компьютерной техники, выпуск электронных подписей.

Web­Assembly

Why Rust?

Predictable performance

No unpredictable garbage collection pauses. No JIT compiler performance cliffs. Just low-level control coupled with high-level ergonomics.

Small code size

Small code size means faster page loads. Rust-generated .wasm doesn’t include extra bloat, like a garbage collector. Advanced optimizations and tree shaking remove dead code.

Modern amenities

A lively ecosystem of libraries to help you hit the ground running. Expressive, zero-cost abstractions. And a welcoming community to help you learn.

Get started!

Learn more about the fast, safe, and open virtual machine called WebAssembly, and read its standard.

Learn how to build, debug, profile, and deploy WebAssembly applications using Rust!

Learn more about WebAssembly on the Mozilla Developer Network.

Plays well with JavaScript

Augment, don’t replace

The dream of WebAssembly is not to kill JavaScript but to work alongside of it, to help super charge processing-heavy or low-level tasks — tasks that benefit from Rust’s focus on performance.

Works with familiar toolchains


Publish Rust WebAssembly packages to package registries like npm. Bundle and ship them with webpack, Parcel, and others. Maintain them with tools like npm audit and Greenkeeper.

Seamless interop

Automatically generate binding code between Rust, WebAssembly, and JavaScript APIs. Take advantage of libraries like web-sys that provide pre-packaged bindings for the entire web platform.

Production use

We can compile Rust to WASM, and call it from Serverless functions woven into the very fabric of the Internet. That’s huge and I can’t wait to do more of it.

The JavaScript implementation [of the source-map library] has accumulated convoluted code in the name of performance, and we replaced it with idiomatic Rust. Rust does not force us to choose between clearly expressing intent and runtime performance.

[Rust’s] properties make it easy to embed the DivANS codec in a webpage with WASM, as shown above.

Rust использует виртуальную машину?

Rust — это язык программирования, виртуальная машина — это среда выполнения. Вы можете скомпилировать Rust в wasm и запускать под виртуальной машиной (node.js или в браузере), или можете скомпилировать в машинный код и запускать как как обычное приложение. Правда, пока что экосистема wasm еще не развита, но в целом работает, да и сам язык до зрелости еще не дотягивает.

Отличие от языков, изначально рассчитанных на виртуальную машину, заключается в том, что сам Rust не содержит предположений по этому по этому поводу и не предоставляет дополнительных функций, основанных на возможностях виртуальной машины. В частности, в нём нет возможности управлять jit-компиляцией. Впрочем, всё то же самое можно сказать и про C++, но там исторически сложилось, что долгое время под него просто не было виртуальной машины (сейчас его тоже можно скомпилировать в wasm или в JavaScript).

Мастер Йода рекомендует:  Представлено приложение Seek, распознающее животных и растения по фотографиям

На практике Rust компилируется в LLVM — байт код, с которым можно делать что угодно — компилировать в машинный код, запускать напрямую на виртуальной машине (теоретически) или транслировать куда-то еще.

Видимо, данный вопрос возник из-за того что код на Rust сначала компилируется в LLVM-байткод, а далее этот байт-код компилируется в машинный код для заданной системы. Примерно так работает LLVM: исходный код → фронтенд (компилятор языка) → LLVM → бэкенд (транслятор из LLVM-байткода в машкод целевой платформы) → бинарник в машкодах целевой системы.
Таким образом, готовый бинарник является нативным кодом и не использует виртуальную машину или байт-код.

��️ Using rust modules in JavaScript/Web Development (Part 2 / 3) [Webpack]

Please read the Part 1 of the series here :

Part 1 of the post was primarily concerned with integrating rust modules with JavaScript with the help of wasm . But that involved a lot of manual procedures.

  1. Do a build of rust modules to generate wasm output.
  2. Move the generated web.wasm file to the assets directory.

One way of solving this is by writing a custom shell script which does this whenever the rust file changes.

Another more streamlined way is using webpack. ��‍♂️��

*Prerequisite:

Setup the rust project from Part 1 of this post. Follow the Setting up the rust project and Building wasm from rust part of the post.

Using rust modules on front-end using Webpack

Setting up a webpack based frontend project

Lets start by creating a new project

  1. mkdir webpackasm && cd webpackasm — creating the project directory
  2. git init && yarn init or git init && npm init — initialising git and npm/yarn
  3. yarn add —dev webpack webpack-cli webpack-dev-server — installing dependencies.


Now create the following directory/file structure

Change the contents of webpackasm/index.html to

Your webpack.config.js should look like:

You package.json should look like:

And finally webpackasm/src/index.js should look like this:

Lets try and run this:

yarn start or npm start

Should open up a browser window that would look like this.

Perfect! now we have a working webpack setup with livereload.

Now lets add the secret ingredients to make rust modules work with webpack.

  1. yarn add —dev wasm-loader rust-native-wasm-loader — add the necessary loaders
  2. Modify the webpack.config.js to

Also now add the following code to src/index.js

Let break down the above code.

This is the same lib.rs file from the web crate that we created. Webpack would detect that this is a rust file and run the loaders specified in the webpack config. In this case it would be rust-native-wasm-loader and wasm-loader. These loaders would compile lib.rs into wasm and then initialised the wasm in the javascript environment.

All the manual stuff that we did in the Part 1 is now automated by webpack.

yarn start should open up

How cool is that !! ��

Loading rust modules in the backend

You can use the same technique rust -> wasm to load rust modules in the node backend. But there is an alternate technique that makes working with rust modules much easier on the node s >wasm for nodejs is just overkill.

Part 3 would cover how to load up rust modules in the backend (NodeJS) without Webassembly.

Представлен инструмент wasm-pack для более глубокой интеграции JavaScript и Rust

Эшли Уильямс (Ashley Williams), член команды Rust Core, рассказала в Mozilla Hacks о новом инструменте для интеграции JavaScript и Rust. Она представила wasm-pack, предназначенный для создания из проектов на Rust пакетов и публикации их в реестре npm. Исходный код опубликован на crates.ioи GitHub.

Функциональность

С npm можно устанавливать пакеты для фронтенд-разработки, а так как он не умеет компилировать код на Rust, с этим помогает wasm. Однако создание npm-пакета для дальнейшего распространения — сложная задача, и wasm-pack упрощает работу.

Уильямс рассказала о четырех шагах, которые подготовят код на Rust для публикации пакета в реестре npm:


wasm-pack 0.3.1

  • Authors
  • Ashley Williams
  • Links 2144 128 74
  • Crates.io
  • Dependencies

pack up the wasm and publish it to npm!

the goal of this project is to create a portable command line tool for publishing compiled wasm projects to the npm registry for the consumption of js devs using the npm CLI, yarn, or any other CLI tool that interfaces with the npm registry.

this project is a part of the rust-wasm group. you can find more info by visiting that repo!

�� prerequisities

this project is written in rust. get rust to work on this project.

if you want to publish packages, you’ll also need an account on npm and have node/npm installed.

Представлен инструмент wasm-pack для более глубокой интеграции JavaScript и Rust

A simple boilerplate to get WebAssembly (WASM) code generated by Rust and bundled by Webpack!

This project now uses the awesome rust-native-wasm-loader рџљЂ.

To get started, we need to install rustup, the Rust toolchain installer:

Please refer to its documentation.

First, install the necessary NodeJS dependencies:

The next step will update to the latest Rust nightly, add the wasm32-unknown-unknown toolchain and install wasm-gc from git. The latter is a small command to clean a wasm module and remove all unneeded exports, imports, functions, etc.

You can skip this step and directly launch the dev server.

Представлен инструмент wasm-pack для более глубокой интеграции JavaScript и Rust

Facilitating high-level interactions between wasm modules and JavaScript. Import JavaScript things into Rust and export Rust things to JavaScript.

wasm-pack — ��✨ your favorite rust -> wasm workflow tool!

This tool seeks to be a one-stop shop for building and working with rust- generated WebAssembly that you would like to interop with JavaScript, in the browser or with Node.js. wasm-pack helps you build and publish rust-generated WebAssembly to the npm registry to be used alongside any other javascript package in workflows that you already use, such as webpack or greenkeeper. We generate a wasm-pack.log file if wasm-pack errors on you, and you can customize the log verbosity using the verbosity flag.

book — The Rust and WebAssembly Book


This repo contains documentation on using Rust for wasm, common workflows, how to get started and more. It acts as a guide for how to do some neat things with it. If you would like to start learning how to use Rust and WebAssembly together immediately, you can read the book online here.

console_error_panic_hook — A panic hook for wasm32-unknown-unknown that logs panics with console

This crate lets you debug panics on wasm32-unknown-unknown by providing a panic hook that forwards panic messages to console.error. When an error is reported with console.error, browser devtools and node.js will typically capture a stack trace and display it with the logged error message.

rfcs — The Rust and WebAssembly RFCs

Many changes, including bug fixes and documentation improvements can be implemented and reviewed via the normal GitHub pull request workflow. Some changes though are «substantial», and we ask that these be put through a bit of a design process and produce a consensus among the Rust and WebAssembly community.

wasm_game_of_life — A Rust and WebAssembly tutorial implementing the Game of Life

This repository contains the complete code for the Rust and WebAssembly tutorial. The tutorial builds increasingly featureful implementations of Conway’s Game of Life.

wee_alloc — The Wasm-Enabled, Elfin Allocator

wee_alloc: The Wasm-Enabled, Elfin Allocator. Elfin, i.e. small: Generates less than a kilobyte of uncompressed WebAssembly code. Doesn’t pull in the heavy panicking or formatting infrastructure. wee_alloc won’t bloat your .wasm download size on the Web.

serde-wasm-bindgen — Native integration of Serde with wasm-bindgen

This is an alternative native integration of Serde with wasm-bindgen. This library was created to address rustwasm/wasm-bindgen#1258 and provide a native Serde integration for wasm-bindgen to directly convert values between JavaScript and Rust (compiled to WebAssembly).

wasm-pdf — Generate PDF files with JavaScript and WASM (WebAssembly)

Idea here is to push all the work involved in creating a PDF to the browser side, instead of using precious server resources. Example that generates a sample PDF document from JSON file. Title in PDF is changed dynamically (in JavaScript) to show current date. Note: this example routes directly to the PDF data blob, so 2 backsteps are needed to return to this page.

Building and augmenting libraries by calling Rust from JavaScript

Explore how to use WebAssembly (Wasm) to embed Rust inside JavaScript.

Subscribe now

Get the highlights in your inbox every week.

In Why should you use Rust in WebAssembly?, I looked at why you might want to write WebAssembly (Wasm), and why you might choose Rust as the language to do it in. Now I’ll share what that looks like by exploring ways to embed Rust inside JavaScript.

This is something that separates Rust from Go, C#, and other languages with large runtimes that can compile to Wasm. Rust has a minimal runtime (basically just an allocator), making it easy to use Rust from JavaScript libraries. C and C++ have similar stories, but what sets Rust apart is its tooling, which we’ll take a look at now.

The basics

If you’ve never used Rust before, you’ll first want to get that set up. It’s pretty easy. First download Rustup, which is a way to control versions of Rust and different toolchains for cross-compilation. This will give you access to Cargo, which is the Rust build tool and package manager.

Now we have a decision to make. We can easily write Rust code that runs in the browser through WebAssembly, but if we want to do anything other than make people’s CPU fans spin, we’ll probably at some point want to interact with the Document Object Model (DOM) or use some JavaScript API. In other words: we need JavaScript interop (aka the JavaScript interoperability API).

The problem and the solutions

The good news is there are two libraries that facilitate communication between Rust-based Wasm and JavaScript: wasm-bindgen and stdweb. The bad news, however, is these two libraries are unfortunately incompatible with each other. wasm-bindgen is lower-level than stdweb and attempts to provide full control over how JavaScript and Rust interact. In fact, there is even talk of rewriting stdweb using wasm-bindgen, which would get rid of the issue of incompatibility.

Because wasm-bindgen is the lighter-weight option (and the option officially worked on by the official Rust WebAssembly working group), we’ll focus at that.

wasm-bindgen and wasm-pack


We’re going to create a function that takes a string from JavaScript, makes it uppercase and prepends «HELLO, » to it, and returns it back to JavaScript. We’ll call this function excited_greeting!

First, let’s create our Rust library that will house this fabulous function:

Now we’ll want to replace the contents of src/lib.rs with our exciting logic. I think it’s best to write the code out instead of copy/pasting.

Second, we’ll have to make two changes to our Cargo.toml configuration file:

  • Add wasm_bindgen as a dependency.
  • Configure the type of library binary to be a cdylib or dynamic system library. In this case, our system is wasm, and setting this option is how we produce .wasm binary files.

Now let’s build! If we just use cargo build, we’ll get a .wasm binary, but in order to make it easy to call our Rust code from JavaScript, we’d like to have some JavaScript code that converts rich JavaScript types like strings and objects to pointers and passes these pointers to the Wasm module on our behalf. Doing this manually is tedious and prone to bugs.

Luckily, in addition to being a library, wasm-bindgen also has the ability to create this «glue» JavaScript for us. This means in our code we can interact with our Wasm module using normal JavaScript types, and the generated code from wasm-bindgen will do the dirty work of converting these rich types into the pointer types that Wasm actually understands.

We can use the awesome wasm-pack to build our Wasm binary, invoke the wasm-bindgen CLI tool, and package all of our JavaScript (and any optional generated TypeScript types) into one nice and neat package. Let’s do that now!

First we’ll need to install wasm-pack:

By default, wasm-bindgen produces ES6 modules. We’ll use our code from a simple script tag, so we just want it to produce a plain old JavaScript object that gives us access to our Wasm functions. To do this, we’ll pass it the —target no-modules option.

We now have a pkg directory in our project. If we look at the contents, we’ll see the following:

  • package.json: useful if we want to package this up as an NPM module
  • my_wasm_library_bg.wasm: our actual Wasm code
  • my_wasm_library.js: the JavaScript «glue» code
  • Some TypeScript definition files

Now we can create an index.html file that will make use of our JavaScript and Wasm:

You may be tempted to open the HTML file in your browser, but unfortunately, this is not possible. For security reasons, Wasm files have to be served from the same domain as the HTML file. You’ll need an HTTP server. If you have a favorite static HTTP server that can serve files from your filesystem, feel free to use that. I like to use basic-http-server, which you can install and run like so:

Now open the index.html file through the web server by going to https://localhost:4000/index.html and check your JavaScript console. You should see a very exciting greeting there!

If you have any questions, please let me know. Next time, we’ll take a look at how we can use various browser and JavaScript APIs from within our Rust code.

Create and Publish a NPM Package Containing Rust Generated WebAssembly using wasm-pack

wasm-pack is a tool that seeks to be a one-stop shop for building and working with Rust generated WebAssembly that you would like to interop with JavaScript. This includes ability to publish modules so that you can share your Rust generated WebAssembly code with others.

In this lesson we create a npm package and export a Rust function that will log to the console in the browser. We publish the module to NPM and afterwards use a rust-webpack-template to install and use the newly published package.

You must be a Member to view code

Access all courses and lessons, track your progress, gain confidence and expertise.

Discuss

Transcript

Instructor: We start out by creating a new Rust library. In our Cargo.toml, we set the create type to be CDY lib, and add the dependency, wasm-bindgen. Right after that, we switch to our Rust lib file and remove the existing code.

We declare that we use the create wasm-bindgen, import the function console.log, and export the function greet, accepting a name. Next up, we run wasm-pack build. Don’t be surprised, this might take a couple minutes.

This creates a package directory. In previous lessons, I mentioned that it contains a WASM and a Javascript file. What I haven’t mentioned yet is that it also creates a package.json based on our Cargo.toml.

Using wasm-pack publish, we can publish this package to NPM, and use it in any app supporting WASM. For example, a Rust webpack template. Keep in mind, you need to use wasm-pack login to log into NPM. I did this before I started the lesson.

Let’s verify that this actually works. We switch over to our Rust webpack project and install our package, myWasmLib. Then we open the index.js file of our application, and add an import to our just-published library.

Once our libary’s imported, we can import the greet function we previously exported. In the browser, we now can see «Hello World.» This means we can use any library using WebAssembly in our code, as well as we can publish our own using wasm-pack.

Мастер Йода рекомендует:  Создаем тему WordPress на базе статического HTML Добавляем характерные изображения
Добавить комментарий