Crate mz_npm

source ·
Expand description

A lightweight JavaScript package manager, like npm.

There are several goals here:

  • Embed the JavaScript assets into the production binary so that the binary does not depend on any external resources, like JavaScript CDNs. Access to these CDNs may be blocked by corporate firewalls, and old versions of environmentd may outlive the CDNs they refer to.

  • Avoid checking in the code for JavaScript assets. Checking in blobs of JavaScript code bloats the repository and leads to merge conflicts. Plus it is hard to verify the origin of blobs in code review.

  • Avoid depending on a full Node.js/npm/webpack stack. Materialize is primarily a Rust project, and thus most Materialize developers do not have a Node.js installation available nor do they have the expertise to debug the inevitable errors that arise.

Our needs are simple enough that it is straightforward to download the JavaScript and CSS files we need directly from the NPM registry, without involving the actual npm tool.

In our worldview, an NpmPackage consists of a name, version, an optional CSS file, a non-minified “development” JavaScript file, and a minified “production” JavaScript file. The CSS file, if present, is extracted into CSS_VENDOR. The production and development JS files are extracted into JS_PROD_VENDOR and JS_DEV_VENDOR, respectively. A SHA-256 digest of these files is computed and used to determine when the files need to be updated.

To determine the file paths to use when adding a new package, visit

http://unpkg.com/PACKAGE@VERSION/

and browse the directory contents. (Note the trailing slash on the URL.) The compiled JavaScript/CSS assets are usually in a folder named “dist” or “UMD”.

To determine the correct digest, the easiest course of action is to provide a bogus digest, then build environmentd. The error message will contain the actual digest computed from the downloaded assets, which you can then copy into the NpmPackage struct.

To reference the vendored assets, use HTML tags like the following in your templates:

The “/js/vendor/PACKAGE.js” will automatically switch between the production and development assets based on the presence of the dev-web feature.

Functions