Scripting with NodeJS
In this guide, we are going to use the meta.json
(explained below) file packaged with one of our icon libraries and in the end generates a single html
file.
- Empty Folder named "preview".
- NodeJS Installed (for
npm
command line)
The NodeJS command line will allow us to pull down some helper scripts and execute our build.js
we'll be writing.
The first step will require you to open a command line of your choice.
- Run
npm init
in your/preview
folder - Press enter a few times to accept all the defaults.
- Run
npm install @mdi/svg @mdi/util
(or@mdi/svg-light
for Material Design Icons Light)
Awesome, you will now see a folder called node_modules
. This contains a copy of the latest version of the SVG's and the meta.json
file.
The meta.json
file is stored in the @mdi/svg
package. This contains all the icon information. The data is normalized to cut down on the file size.
[ { "id": "039be9b8-08ad-11e4-bf19-842b2b6cfe1b", "name": "vector-square", "codepoint": "F001", "aliases": [ "mdi" ], "tags": [ "Vector" ], "author": "Austin Andrews", "version": "1.5.54" }, ... ]
The build.js
file is below. We'll break down what each part does and what the @mdi/util
provides.
const util = require('@mdi/util'); const fileName = "./preview.html"; const version = util.getVersion(); const meta = util.getMeta(true); // withPaths const body = meta.map(icon => ` <span onClick="a('${icon.name}')" title="${icon.name}"> <svg viewBox="0 0 24 24"> <path d="${icon.path}" /> </svg> </span> `).join(''); const template = ` <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Material Design Icons - Preview</title> <style> svg { width: 24px; height: 24px } </style> <script> window.a = x => alert(x); </script> </head> <body> <h1>MDI Preview</h1> ${body} </body> </html> `; util.write(fileName, template); console.log(`\u2714 Build ${version}`);
The @mdi/util
includes a few helper methods for working with the @mdi/svg
package's data with NodeJS.
util.getVersion()
Get the semver formatted stringmajor.minor.build
of the current@mdi/svg
release.util.getMeta(true)
Get themeta.json
data. Passing true will parse the SVG folder for path data assigning it to.path
.util.write(file, data)
Write data to a file.util.read(file)
Read data from a file.
View the util.js to understand these utilities.
In the package.json
a new script needs to be added to handle build
.
"scripts": { "test": "echo \"Error: no test specified\" && exit 1", "build": "node build.js" },
To run the build execute npm run build
.
Hopefully, you found the above tutorial useful and it allows you to create more complex build scripts.