Snowpack - JavaScript Api

06/03/2021, Thu
Categories: #shell #typescript
Tags: #NodeJs

Control Over Start

When the Snowpack CLI is not able to provide fine-tune control over start operations, the Snowpack JavaScript Api should be used. Being able to programmatically control Snowpack is made possible when invoked inside other JavaScript files for enabling more configuration options.

One example of using Snowpack programmatically arises when one calls upon the execution of JavaScript file directly with node to start a Snowpack dev server. The "run-server.js" will display console output from the server information logs.

// run-server.js

const childProcess = require('child_process'),
  { spawn } = childProcess;

const server = spawn('node', ['./server.js']);

server.stdout.on('data', (data: any) => {
  console.error(`Info: ${data}`);
});

server.stdout.on('error', (data: any) => {
  console.error(`Error: ${data}`);
});

The following shows a minimal setup for Snowpack configuration that takes a plugin with hot module reloading enabled. This should allow for running a basic Snowpack live dev server when making changes to web assets.

// server.js

const snowpack = require('snowpack'),
    path = require('path');

const { loadConfiguration, startServer } = snowpack;

(async () => {
    const configPath = path.resolve(process.cwd(), 'snowpack.config.js');

    const config = await loadConfiguration({
        plugins: [
            ['./plugins/my-plugin.js', {}]
        ],
        devOptions: {
            hmr: true
        }
    }, configPath);
    startServer({ config });
})();

Snowpack's full configuration options can be found in the "types.ts". Look at the SnowpackConfig interface: https://github.com/snowpackjs/snowpack/blob/main/snowpack/src/types.ts.