Snowpack - "Unbundler"

02/07/2021, Sun
Categories: #Tooling
Tags: #frontend

Configure a Snowpack Plugin

Snowpack is a frontend build tool that promotes itself as an alternative to Webpack because it uses new JS modules features, and the workflow is "unbundled" which skips the build steps during development to make for a faster workflow.

Snowpack has some sensible defaults which permits the import of commonly used asset files such as scss, .css, .svg in your JavaScript files.

Start a Snowpack project by initializing a npm project

mkdir snowpack-test
cd snowpack-test
touch package.json
touch index.html

Update the "package.json" to install Snowpack

{
    "name": "project",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "author": "",
    "license": "ISC",
    "dependencies": {
        "snowpack": "^3.0.11"
    },
    "scripts": {
        "start": "snowpack dev"
    }
}

Entry Point HTML

The entry point html file that Snowpack looks at will need to be named "index.html".

.
├── index.html
├── my-cool-file.myfileextensiontowatch
├── node_modules
├── package.json
├── package-lock.json
└── snowpack.config.js

To customize the directory for where the index.html is served, update "snowpack.config.js" with the following.

...
mount: {
  "site": "/"
}
...

This will permit you to move the "index.html" file to the "site" folder.

.
├── node_modules
├── package.json
├── package-lock.json
├── site
   └── index.html
└── snowpack.config.js

In the case where you would like to detect a file type change which is not supported by Snowpack natively, you can create a plugin.

// new-plugin-for-detecting-file-type-change.js

module.exports = function (snowpackConfig, pluginOptions) {
  return {
    name: 'my-first-snowpack-plugin',
    load() { },
    resolve: { input: [".myfileextensiontowatch"], output: [".html"] },
    onChange(change) {
      console.log('changed', change);
    }
  };
};

The files being watched will be monitor based on where your "index.html" file is located. Watching will be done on the same folder level placement of "index.html" and any folder that is nested under the parent folder of "index.html".

If we were to use a custom folder for "index.html", the file extension to watch will be moved to the same folder as "index.html".

.
├── node_modules
├── package.json
├── package-lock.json
├── site
   │── index.html
   └── my-cool-file.myfileextensiontowatch
└── snowpack.config.js

The Snowpack plugin can be placed in any location as long as the path to it can be referenced.

// snowpack.config.js

"plugins": [
    ["./new-plugin-for-detecting-file-type-change.js", {/* pluginOptions */ }]
]

Along with the Snowpack's Plugin Api, there are Apis for use with the CLI and HMR.

Although Snowpack's is on v3, its Api is not as extensive as Webpack, but it is simple enough for smaller projects where you might not be interested in downloading more for what might be used.