generated from imlinhanchao/vue-parcel-template
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
81 lines (70 loc) · 1.83 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
const { createProxyMiddleware } = require('http-proxy-middleware');
const Bundler = require('parcel-bundler');
const express = require('express');
const net = require('net');
const path = require('path');
const fs = require('fs');
if (!fs.existsSync(path.join(__dirname, 'config.json'))) {
console.info('[Info] Please execute `npm run init` to initialization config.')
process.exit(0);
}
const config = require('./config.json');
let port = Number(process.env.PORT || 8080);
const bundler = new Bundler('frontend/index.html', {
cache: false
})
function portIsOccupied(port, cb = (err, port) => {}) {
const server = net.createServer().listen(port)
server.on('listening', () => {
server.close()
cb(null, port)
})
server.on('error', (err) => {
if (err.code === 'EADDRINUSE') {
portIsOccupied(port + 1, cb)
} else {
cb(err)
}
})
}
const app = express();
app.use(
'/api',
createProxyMiddleware({
target: `http://localhost:${config.base.port}`
})
);
app.use(
'/res',
createProxyMiddleware({
target: `http://localhost:${config.base.port}`
})
);
app.use(
'/upload',
createProxyMiddleware({
target: `http://localhost:${config.base.port}`
})
);
app.use(
'/view',
createProxyMiddleware({
target: `http://localhost:${config.base.port}`
})
);
app.use(bundler.middleware());
let cmd;
if (process.platform == 'win32') {
cmd = 'explorer';
} else if (process.platform == 'linux') {
cmd = 'xdg-open';
} else if (process.platform == 'darwin') {
cmd = 'open';
}
portIsOccupied(port, (err, port) => {
console.log(`\rLaunch http://localhost:${port} .`)
app.listen(port, () => {
let url = 'http://localhost:' + port;
require('child_process').exec(`${cmd} "${url}"`);
});
});