-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
108 lines (93 loc) · 2.64 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/**
* @typedef {import('./utils').PathLike} PathLike
* @typedef {import('./utils').obj} obj
*/
/**
* @typedef {{
* publicPath?: string
* inject?: boolean
* envKey?: string
* versionFileName?: string
* }} UpdatePopupOptions
*/
const fs = require('fs-extra')
const _get = require('lodash.get')
const {
resolveWebpackEntry,
replaceStr,
correctPath,
resolve,
join,
resolveApp
} = require('./utils')
/** @type {(filePath: PathLike) => string} */
const readFile = filePath => fs.readFileSync(filePath, 'utf8')
const NAME = 'spa-update-notice'
class UpdatePopup {
/** @param {UpdatePopupOptions} options */
constructor(options) {
this.options = Object.assign({
publicPath: '',
inject: true, // 自动注入到 webpack.entry
envKey: 'UPDATE_POPUP_VERSION',
versionFileName: 'update_popup_version.txt',
isNeedNotice: false //是否需要主动提醒用户
},
options
)
this.version = process.env[this.options.envKey] || new Date().getTime()
}
/** @type {(compiler: import('webpack').Compiler) => void} */
apply (compiler) {
// common
if (process.env.NODE_ENV !== 'production') return
// v4
if (_get(compiler, 'options.mode') !== 'production') return
// 修改 webpack 入口文件
if (this.options.inject) {
compiler.options.entry = resolveWebpackEntry(compiler.options.entry, {
NAME,
filePath: resolveApp('main.js')
})
}
// 先生成写入版本号的文件到 app
compiler.hooks.beforeRun.tap(NAME, () => {
// 清空缓存文件夹
fs.emptyDirSync(resolveApp())
const publicPath =
_get(this, 'options.publicPath') ||
_get(compiler, 'options.output.publicPath', '')
this.generateFile(
resolveApp('main.js'),
readFile(resolve('src', 'main.js')), {
VERSION_FILE_PATH: correctPath(
publicPath,
this.options.versionFileName
)
}
)
})
// 复制文件到 webpack 输出目录
compiler.hooks.done.tap(NAME, () => {
const outputPath = _get(compiler, 'outputPath', '')
// 版本号文件
fs.outputFileSync(
join(outputPath, this.options.versionFileName),
this.version
)
})
}
/** @type {(dest: PathLike, content: string, extraReplacement: obj) => void} */
generateFile (dest = '', content = '', extraReplacement = {}) {
fs.outputFileSync(
dest,
replaceStr(content, {
envKey: this.options.envKey,
currentVersion: this.version,
isNeedNotice: this.options.isNeedNotice || false,
...extraReplacement
})
)
}
}
module.exports = UpdatePopup