1
1
/** 用于开发环境的服务启动 **/
2
2
const path = require ( "path" ) ; // 获取绝对路径有用
3
3
const express = require ( "express" ) ; // express服务器端框架
4
- const bodyParser = require ( "body-parser" ) ;
5
4
const env = process . env . NODE_ENV ; // 模式(dev开发环境,production生产环境)
6
5
const webpack = require ( "webpack" ) ; // webpack核心
7
6
const webpackDevMiddleware = require ( "webpack-dev-middleware" ) ; // webpack服务器
8
7
const webpackHotMiddleware = require ( "webpack-hot-middleware" ) ; // HMR热更新中间件
9
8
const webpackConfig = require ( "./webpack.dev.config.js" ) ; // webpack开发环境的配置文件
10
- const mock = require ( "./mock/app-data" ) ; // mock模拟数据,模拟后台业务
11
9
12
- // const { createProxyMiddleware } = require("http-proxy-middleware "); // 跨域配置 需要跨域请打开注释即可
10
+ const mock = require ( "./mock/app-data " ) ; // mock模拟数据,模拟后台业务
13
11
14
12
const app = express ( ) ; // 实例化express服务
13
+ const DIST_DIR = webpackConfig . output . path ; // webpack配置中设置的文件输出路径,所有文件存放在内存中
15
14
let PORT = 8888 ; // 服务启动端口号
16
15
17
- // 跨域设置 需要跨域请打开注释,自己设置对应的域名
18
- // app.use(
19
- // "/proxy",
20
- // createProxyMiddleware({
21
- // target: "https://example.com", // 目标域名
22
- // changeOrigin: true,
23
- // ws: false,
24
- // pathRewrite: {
25
- // "^/proxy": "/",
26
- // },
27
- // })
28
- // );
29
-
30
- // bodyParser的配置需要放在Proxy代理的下面,否则post请求的代理参数无法处理
31
- app . use ( bodyParser . urlencoded ( { extended : false } ) ) ;
32
- app . use ( bodyParser . json ( ) ) ;
16
+ app . use ( express . urlencoded ( { extended : false } ) ) ;
17
+ app . use ( express . json ( ) ) ;
33
18
34
19
/** 监听POST请求,返回MOCK模拟数据 **/
35
20
app . post ( / \/ a p i .* / , ( req , res , next ) => {
@@ -45,24 +30,22 @@ if (env === "production") {
45
30
// 如果是生产环境,则运行build文件夹中的代码
46
31
PORT = 8889 ;
47
32
app . use ( express . static ( "build" ) ) ;
48
- app . get ( "*" , function ( req , res ) {
33
+ app . get ( "*" , ( req , res ) => {
49
34
res . sendFile ( path . join ( __dirname , "build" , "index.html" ) ) ;
50
35
} ) ;
51
36
} else {
52
37
const compiler = webpack ( webpackConfig ) ; // 实例化webpack
38
+ app . use ( express . static ( "dll" ) ) ;
53
39
app . use (
54
- // 挂载webpack小型服务器
55
40
webpackDevMiddleware ( compiler , {
56
41
publicPath : webpackConfig . output . publicPath , // 对应webpack配置中的publicPath
57
42
} ) ,
58
43
) ;
59
- // 挂载HMR热更新中间件
60
- app . use ( webpackHotMiddleware ( compiler ) ) ;
61
44
45
+ app . use ( webpackHotMiddleware ( compiler ) ) ; // 挂载HMR热更新中间件
62
46
// 所有请求都返回index.html
63
47
app . get ( "*" , ( req , res , next ) => {
64
- // webpack配置中设置的文件输出路径,所有文件存放在内存中
65
- const filename = path . join ( webpackConfig . output . path , "index.html" ) ;
48
+ const filename = path . join ( DIST_DIR , "index.html" ) ;
66
49
67
50
// 由于index.html是由html-webpack-plugin生成到内存中的,所以使用下面的方式获取
68
51
compiler . outputFileSystem . readFile ( filename , ( err , result ) => {
0 commit comments