Imagine I have a project like this:
/moduleA/src...
/moduleB/src...
/mainApp/src...
I have a separate webpack.config for each module and the main app. The modules are libraries and the main app imports those libraries.
Is it possible to configure webpack-dev-server to serve all three?
What I want to avoid is having to stop the dev server, rebuild moduleA and moduleB, and restart the dev server, every time I want to make a change to moduleA or B.
Not with webpack-dev-server
only because that tool is built to watch and serve a single webpack application configuration only.
So the high level answer is: run webpack-dev-server
for the application and a watcher for each package dependency, at the same time. A rebuild by one of the watchers will cause a subsequent rebuild of the application by webpack.
I recommend if you are not already managing your packages within a monorepo that you do so, because it makes this all a little bit less ugly.
Assumptions:
- packages are managed within a monorepo using lerna
- each package (and the application) has a
webpack.config.js
- you are using Yarn
Steps:
for each dependency package, e.g. moduleA
:
install cross-env
:
yarn add cross-env
set up webpack as a watcher in development mode by adding watch
to the config:
watch: process.env.NODE_ENV === "development"
add an NPM script "start:dev"
:
"start:dev": "cross-env NODE_ENV=development webpack --config webpack.config.js"
for the application package, e.g. mainApp
:
in the monorepo root:
install concurrently
yarn add concurrently
add the NPM scripts* for calling the application and each dependency package's "start:dev"
and a "start:dev"
which uses them:
"watch:app": "cd packages/mainApp && npm run start:dev",
"watch:moduleA": "cd packages/moduleA && npm run start:dev",
"watch:moduleB": "cd packages/moduleB && npm run start:dev",
"start:dev": "
concurrently
\"npm run watch:app\"
\"npm run watch:moduleA\"
\"npm run watch:moduleB\"
"
Steps to run (in the root of the monorepo):
bootstrap your monorepo with lerna:
lerna bootstrap
start the app dev server and watchers for all of the dependency packages:
npm run start:dev
navigate to your application dev server endpoint, e.g. localhost:8080
___
Addendum: if a monorepo is out of the question, you can look at a combination of using yarn link
and an NPM script in your application's package.json
that looks something like*:
{
"start:dev": "
concurrently
\"cross-env NODE_ENV=development webpack --config webpack.config.js\"
\"cd ./node_modules/moduleA && npm run start:dev\"
\"cd ./node_modules/moduleB && npm run start:dev\"
"
}
___
*Note: newlines within NPM scripts are added for readability; you must collapse the newlines if you use these in your package.json
.