Before we finish, let's also document the commands we've run into npm scripts. This will make building and serving our application easier in the future.
In the package.json, define the build step with the following scripts property:
"scripts": {
"build": "rm -rf dist/ && webpack"
}
Then, we will write a script to serve our application. We'd like to specify the host and port of the application using environment variables (instead of hard-coding it), so let's create an .env and an .env.example file, and fill them with the following content:
WEB_SERVER_PORT_TEST=8200
WEB_SERVER_HOST_TEST=localhost
Then, create a Bash script at scripts/serve.sh and give it the execute permission:
$ mkdir scripts && touch scripts/serve.sh
$ chmod u+x scripts/serve.sh
Inside the Bash script, we will simply load the environment variables, build the application, and use htttp-server to serve the bundled files:
#!/usr/bin/env bash
# Set environment variables from .env and set NODE_ENV to test
source <(dotenv-export | sed 's/\\n/\n/g')
export NODE_ENV=test
yarn run build
http-server dist/ -- -p $WEB_SERVER_PORT_TEST --cors
Now, we just need to run our Bash script using an npm script:
"serve": "./scripts/serve.sh"