Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create Node.js Express app serving a Vue.js SPA?

I'm trying to set up a Node.js project that uses Express to provide a few backend APIs and serve a SPA built with Vue.js.

When I use the Vue cli to initialize a project, I get e.g. src/main.ts main file and commands npm run serve to run a dev server and watch for changes and npm run build to build a production release.

When I use the Express application generator to create a project, I get ./app.js main file and npm start to start the server and watch for changes.

How can I combine these into a single project, both served by the same Express server? Preferably so that a single command would watch + update changes to both server and client? I want to use Vue single file components and TypeScript, which (probably?) require a build step.

(I don't need dynamic server-side rendering of Vue templates, just the static SPA app provided. I prefer TypeScript, but JavaScript answers are fine as well.)

like image 885
Sampo Avatar asked Oct 13 '25 08:10

Sampo


1 Answers

These will be different for your dev and prod environments...

For development look into concurrently - it basically allows you to create a single script in your package.json to start both the client and server concurrently and will watch for changes etc...

For production, you would need something like this in your app.js:

if (process.env.NODE_ENV === 'production') {
  app.use(express.static('client/build'));

  const path = require('path');
  app.get('*', (req, res) => {
    res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
  });
}

(The code above assumes that your directory structure has a client folder with a build folder after having run npm run build I'm more familiar with React than Vue... but the logic should be the same...)

like image 186
SakoBu Avatar answered Oct 14 '25 21:10

SakoBu