Applying msw (mock service worker) to a webpack project
msw (mock service worker)
What is msw? A service worker that mocks API responses.
Implementation issues
- msw constraints
- msw’s mockServiceWorker only runs properly in an https environment. (When I checked again, it turns out it runs over http too…)
- Project constraints
- To integrate with other systems (the authentication server), the URL in the local development environment must be set to *.ourcompanyurl.co.kr.
- webpack-dev-server constraints
- webpack-dev-server’s SSL certificate uses ‘localhost’ as its host.
- (Since this is a project that uses React) create-react-app’s webpack-dev-server runs with ‘localhost’ as its host (default setting).
Steps taken
- TLS certificate
- Create a TLS certificate for the *.ourcompanyurl.co.kr domain.
- Create a /scripts directory under the project’s root path.
- Under the directory above, create a make_cert.sh file with the following contents.
- Run the shell script below.
## make_cert.sh
CONFIGDIR="ssl/"
# set /etc/hosts
# Proceed assuming the host configuration is already complete.
# install mkcert
brew install mkcert
# create local CA & system trust store
mkcert -install
# create certificate
mkdir -p $CONFIGDIR
cd $CONFIGDIR
mkcert live11-local.ourcompanyurl.co.kr
- webpack-dev-server
- Change webpack-dev-server’s host to *.ourcompanyurl.co.kr.
- Add the following setting to the env file
- Change webpack-dev-server’s host to *.ourcompanyurl.co.kr.
# .env file
HOST=live11-local.ourcompanyurl.co.kr
- Configure webpack-dev-server to run over HTTPS.
- Add the following setting to the env file
# .env file HTTPS=true
- Add the following setting to the env file
- Replace webpack-dev-server’s TLS certificate with the certificate created above.
- Register the following script in package.json
- The following script always runs before the start command.
"prestart": "rm ./node_modules/webpack-dev-server/ssl/server.pem && cp -f ./ssl/server.pem ./node_modules/webpack-dev-server/ssl"
Now if you run yarn start or npm start, msw should run just fine. The end.
20220119
Leave a comment