Add a New Express Project
Supported Features
Because we are using an Nx plugin for Express, all the features of Nx are available.
โ Run Tasks โ Cache Task Results โ Share Your Cache โ Explore the Graph โ Distribute Task Execution โ Integrate with Editors โ Automate Updating Nx โ Enforce Module Boundaries โ Use Code Generators โ Automate Updating Framework Dependencies
Install the Express Plugin
Make sure to install the @nx/express
version that matches the version of nx
in your repository. If the version numbers get out of sync, you can encounter some difficult to debug errors. You can fix Nx version mismatches with this recipe.
โฏ
nx add @nx/express
Create an Application
Use the app
generator to create a new Express app.
โฏ
nx g @nx/express:app apps/my-express-api
Serve the API by running
โฏ
nx serve my-express-api
This starts the application on localhost:3333/api by default.
Create a Library
The @nx/express
plugin does not have a library
generator, but we can use the library
generator from the @nx/js
plugin. To create a new library, install the @nx/js
package and run:
โฏ
nx g @nx/js:lib libs/my-lib
Once the library is created, update the following files.
1export function someFunction(): string {
2 return 'some function';
3}
4
1/**
2 * This is not a production server yet!
3 * This is only a minimal backend to get started.
4 */
5
6import express from 'express';
7import * as path from 'path';
8import { someFunction } from '@my-express-app/my-lib';
9
10const app = express();
11
12app.use('/assets', express.static(path.join(__dirname, 'assets')));
13
14app.get('/api', (req, res) => {
15 res.send({ message: `Welcome to my-express-app! ${someFunction()}` });
16});
17
18const port = process.env.PORT || 3333;
19const server = app.listen(port, () => {
20 console.log(`Listening at http://localhost:${port}/api`);
21});
22server.on('error', console.error);
23
Now when you serve your API, you'll see the content from the library being displayed.