I am trying to create a web app using vue.js, express.js and node.js using the Visual Studio Code IDE on Linux. Following some documentation online, I have read that after installing vue.js, one can create a vue.js app using the following command:
vue create my-app
Following other documentation, it is stated that one can create an express.js app by executing this command:
express myExpressApp
How can I create an app, that I will be developing using the VS Code IDE that is both a vue.js app and an express.js app?
I would recommend creating your vue app first. The add in the Express stuff manually, because that bit is quick and easy.
If you follow the vue documentation here, using the vue-cli it will structure everything for you
The contents of your vue source will live inside the src
directory in your project root. Once you've run npm run build
(same as vue-cli-service build
) a dist
directory will be created, containing the built client-side code.
I'd recommend putting your server side code in a new directory in your project root, say server
, then create a file in that dir, and add in the below code...
const express = require('express');
const history = require('connect-history-api-fallback');
const path = require('path');
require('dotenv').config()
const app = express();
const port = process.env.PORT || 8080;
// Serve up built vue app, at the main root
const staticFileMiddleware = express.static(path.join('dist'));
app.use(staticFileMiddleware);
app.use(history({
disableDotRule: true,
verbose: true
}));
app.use(staticFileMiddleware);
// Make all public assets available
app.use('/public', express.static('public'))
// App has started
app.listen(port, () =>
console.log(`Awesome app has started and is running on port ${port} 🚀`)
);
There are a couple of dependencies you will need, for the above sample you'll have to yarn add express connect-history-api-fallback dotenv
(or use npm).
express
is obviously neededconnect-history-api-fallback dotenv
is needed if your using history mode in vue, it is required to not get a 404 on every sub-page.dotenv
, is just a nice-to-have to read constants from your .env
file, which you should also createFinally to run it, type node server/main
(or whatever you called that file in your server dir).
You will probably want to add that command to your package.json..
"scripts": {
"start": "node server/main",
...
If your using Heroku, double check all your dependencies are correct in your package.json
, then create a file called Procfile
in your root, containing the following web: node ./server/main.js
(or whatever your server file was called), and boom, your vue app is now an Express vue app, and ready for deploy!
Source: I've done this setup a lot of times for my own sites.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With