Build an express server
Please refer to Creating a Node Express-Webpack App with Dev and Prod Builds
You can understand that this is a translation.
-
Create a project called express web pack
- Manually create a new project express webpack
- Execute the following code under the current project
mkdir express-webpack cd express-webpack
-
npm initializes the project and generates package.json
npm init -y //-y selection means that output is skipped by default
-
Installing Express
npm install --save express
-
Create an Express Server
Create a new server.js in the root directory. The code is as follows
//Bring in required packages const path = require('path') const express = require('express') //Instantiate an express object to create an http server const app = express(), DIST_DIR = __dirname, //__dirname indicates the root directory where the current script runs HTML_FILE = path.join(DIST_DIR, 'index.html') app.use(express.static(DIST_DIR)) //Define the entry to a static resource //Send the default entry page to any api request app.get('*', (req, res) => { res.sendFile(HTML_FILE) }) //Define the server port, parameter passed in or 8080 const PORT = process.env.PORT || 8080 //Enable server port listening app.listen(PORT, () => { console.log(`App listening to ${PORT}....`) console.log('Press Ctrl+C to quit.') })
-
Create the entry page in 3, and create index.html in the root directory
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Express and Webpack App</title> <link rel="shortcut icon" href="#"> </head> <body> <h1>Expack</h1> <p class="description">Express and Webpack Boilerplate App</p> </body> </html>
-
Set up running script, and add script in package.json
"scripts": { "start": "node ./server.js" },
The final package.json is
{ "name": "express-webpack", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "node ./server.js" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "express": "^4.16.4" } }
The current directory is as follows:
node_modules index.html package-lock.json package.json server.js
-
Run the script,
npm run start
The console output is as follows:
App listening to 8080.... Press Ctrl+C to quit.
Open the web page and enter the address: http://localhost:8080/
The page is displayed as follows:
Expack
Express and Webpack Boilerplate App