5
votes

I have a working vue project using vue cli 3 rc3, and I followed one of the many tutorials online for creating an express server to serve my files on heroku; however, none of those tutorials say how I can have my shiny new server.js also work for dev, which I think would be the whole point of deploying to something like heroku instead of something geared to static assets.

Obviously I could ditch the npm run serve command that the cli provides and use just my own server, but then I lose the hot loading and other amazing features.

I could create a separate project (I'm guessing this is common), but I want my backend and frontend to share code.

I've been trying to figure this out for a week now, even resorting to reading the cli code on github to see how hard it would be to replicate.

Webpack provides the functionality via the webpack-dev-middleware, but when I try to use that as-is I get missing config errors and things don’t quite work – presumably because of the defaults that the vue cli provides that I’m missing.

I would think something like this should work...

const express = require('express');
const serveStatic = require('serve-static');
const path = require('path');

const app = express();

if (process.env.NODE_ENV === 'production') {
  app.use('/', serveStatic(path.join(__dirname, '/dist')));
  app.get('*', function(req, res) {
    res.sendFile(__dirname + '/dist/index.html');
  });
} else {
  // TODO: Find/create some middleware that does
  // everything that vue-cli-service serve does
  // app.use(require('vue-dev-middleware'));
}

const port = process.env.PORT || 8080;
app.listen(port);

Does anyone have any guidance?

1
I'm also looking for the best approach to write some server-side code and run everything with a single "npm run serve" command while in dev mode. - rodvlopes
Hi @michaeldrotar, did you find any way to solve this problem? I am also searching for the same. - Sarath S Nair

1 Answers

0
votes

in your vue.config.js file

const configureAPI = require("./src/server/configure");

module.exports = {
  devServer: {
    before: configureAPI,
    disableHostCheck: true
  }
}

your express js file

//src/server/configure.js file
module.exports = app => {
    //do stuff
  }

the code above will run vuejs in express server. in other words

npm run serve

will run your expressjs

you can read more about vue.config.js here https://cli.vuejs.org/config/ (for example how to set the port,proxy ...)