-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuild.mjs
76 lines (61 loc) · 2.43 KB
/
build.mjs
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
import fs, {cpSync, mkdirSync, readFileSync, rmSync, writeFileSync} from 'fs'
import path from 'path'
//获取项目路径
import {dirname} from 'path'
import {fileURLToPath} from 'url'
//获取项目路径
const __dirname = dirname(fileURLToPath(import.meta.url))
// 打包工具
import archiver from 'archiver'
// 遍历浏览器配置文件,判断文件类型,生成不同浏览器配置文件
fs.readdirSync(__dirname).forEach(filename => {
if (filename.indexOf(".manifest.json") !== -1) {
// 浏览器名称
const browserName = filename.substring(0, filename.indexOf('.'));
// 配置文件名称
const manifest = filename.substring(filename.indexOf('.') + 1, filename.length);
//构建目录
const dist = path.resolve(__dirname, `./dist`);
// 构建目录
const browserPath = path.resolve(__dirname, `${dist}/_${browserName}`);
// 配置文件路径
const manifestPath = `${browserPath}/${manifest}`;
// 删除原有目录
rmSync(browserPath, {recursive: true, force: true});
// 创建目录
mkdirSync(browserPath);
// 创建文件
const build = path.resolve(dist, `build/`);
cpSync(build, `${browserPath}`, {recursive: true})
// 配置文件
cpSync(path.resolve(__dirname, `./${filename}`), manifestPath, {recursive: true})
//静态数据
cpSync(path.resolve(__dirname, `./src/static`), `${browserPath}/static`, {recursive: true})
//获取 'package.json' 中的版本号
const version = JSON.parse(readFileSync(path.resolve(__dirname, 'package.json')).toString())['version'] || "";
// 写入版本号
writeFileSync(manifestPath, readFileSync(manifestPath).toString().replace(new RegExp('##version##', 'g'), version))
//打包zip
createZip(browserPath, `${dist}/${browserName}.zip`);
}
})
/**
* 打包zip
* @param sourceDir
* @param targetZip
*/
function createZip(sourceDir, targetZip) {
const output = fs.createWriteStream(targetZip);
const archive = archiver('zip', {
zlib: {level: 9} // 设置压缩级别
});
output.on('close', () => {
console.log(`Zip file created: ${archive.pointer()} total bytes`);
});
archive.on('error', (err) => {
throw err;
});
archive.pipe(output);
archive.directory(sourceDir, false); // 将源文件夹添加到 zip 中
archive.finalize();
}