Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express serve static files in Vue 2 App

I'm having an issue with express static data serving in vue 2 project (webpack-simple template) because of different production and development structure.

development: localhost/app

production: server/some-directory/app

some-directory changes quite often so it is set dynamically in the config file.

My serving part of server.js:

if (config.root !== '/') {
  app.use(`/${config.root}`, express.static(path.join(__dirname)));
}

app.use('/dist', express.static(path.join(__dirname, 'dist')));

Transpiled JS files are in /dist folder.

This is index.html file which serves as app entry point:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>App Demo</title>
  </head>
  <body>
    <div id="app"></div>
    <script src="/dist/build.js"></script>
  </body>
</html>

It works in development because app is in root.

But in production build it doesn't work because app is served from server subfolder.

Any ideas how to solve this?

Thanks.

like image 934
user2199236 Avatar asked Apr 19 '17 09:04

user2199236


1 Answers

Assuming your express js server is in the same folder as your vue app:

const express = require('express');
const path = require('path');

const hostname = 'localhost';
const port = 3000;

const app = express();
app.use(express.static(path.join(__dirname, 'dist')));

app.get('*', (req, res) => {
  res.sendFile(__dirname, '/dist/index.html');
});

app.listen(port, hostname, () => {
  console.log("Listening at http://%s:%s/", hostname, port);
});

Don't forget to build your Vue app first!

like image 183
DBFS Avatar answered Sep 23 '22 20:09

DBFS