4

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.)

2
  • 1
    So you want a single command that starts both server and client? Commented Dec 11, 2018 at 23:04
  • The single command should start the server, which hosts the client. But changes to both should be watched and automatically recompiled. Commented Dec 11, 2018 at 23:25

1 Answer 1

4

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...)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.