feat(ui): improved IpcMessenger with new options

This commit is contained in:
Guillaume Chau
2018-06-21 13:50:06 +02:00
parent 6023c2e586
commit c2da5fcc71
4 changed files with 59 additions and 8 deletions
+36 -3
View File
@@ -949,9 +949,6 @@ const { IpcMessenger } = require('@vue/cli-shared-utils')
// Create a new IpcMessenger instance
const ipc = new IpcMessenger()
// Connect to the vue-cli IPC network
ipc.connect()
function sendMessage (data) {
// Send a message to the cli-ui server
ipc.send({
@@ -978,6 +975,42 @@ function cleanup () {
}
```
Manual connection:
```js
const ipc = new IpcMessenger({
autoConnect: false
})
// This message will be queued
ipc.send({ ... })
ipc.connect()
```
Auto disconnect on idle (after some time without sending any message):
```js
const ipc = new IpcMessenger({
disconnectOnIdle: true,
idleTimeout: 3000 // Default
})
ipc.send({ ... })
setTimeout(() => {
console.log(ipc.connected) // false
}, 3000)
```
Connect to another IPC network:
```js
const ipc = new IpcMessenger({
networkId: 'my-ipc-network'
})
```
In a vue-cli plugin `ui.js` file, you can use the `ipcOn`, `ipcOff` and `ipcSend` methods:
```js
@@ -209,7 +209,6 @@ module.exports = (api, options) => {
// Send final app URL
if (args.dashboard) {
const ipc = new IpcMessenger()
ipc.connect()
ipc.send({
vueServe: {
url: urls.localUrlForBrowser
@@ -52,7 +52,6 @@ class DashboardPlugin {
let assetSources = new Map()
if (!sendData) {
ipc.connect()
sendData = data => ipc.send({
webpackDashboardData: {
type: this.type,
+23 -3
View File
@@ -1,10 +1,18 @@
const ipc = require('node-ipc')
const defaultId = process.env.VUE_CLI_IPC || 'vue-cli'
const DEFAULT_ID = process.env.VUE_CLI_IPC || 'vue-cli'
const DEFAULT_IDLE_TIMEOUT = 3000
const DEFAULT_OPTIONS = {
networkId: DEFAULT_ID,
autoConnect: true,
disconnectOnIdle: false,
idleTimeout: DEFAULT_IDLE_TIMEOUT
}
exports.IpcMessenger = class IpcMessenger {
constructor (id = defaultId) {
ipc.config.id = this.id = id
constructor (options = {}) {
options = Object.assign({}, DEFAULT_OPTIONS, options)
ipc.config.id = this.id = options.networkId
ipc.config.retry = 1500
ipc.config.silent = true
@@ -12,10 +20,12 @@ exports.IpcMessenger = class IpcMessenger {
this.connecting = false
this.disconnecting = false
this.queue = null
this.options = options
this.listeners = []
this.disconnectTimeout = 15000
this.idleTimer = null
// Prevent forced process exit
// (or else ipc messages may not be sent before kill)
@@ -29,8 +39,18 @@ exports.IpcMessenger = class IpcMessenger {
send (data, type = 'message') {
if (this.connected) {
ipc.of[this.id].emit(type, data)
clearTimeout(this.idleTimer)
if (this.options.disconnectOnIdle) {
this.idleTimer = setTimeout(() => {
this.disconnect()
}, this.options.idleTimeout)
}
} else {
this.queue.push(data)
if (this.options.autoConnect && !this.connecting) {
this.connect()
}
}
}