Skip to content

Commit

Permalink
feat: 更新rollup插件,防止windows下打包出错
Browse files Browse the repository at this point in the history
  • Loading branch information
ChingCdesu committed Nov 14, 2021
1 parent 9bc67e5 commit b3c6076
Show file tree
Hide file tree
Showing 12 changed files with 159 additions and 143 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@
"@cliqz/url-parser": "^1.1.4",
"@element-plus/icons": "^0.0.11",
"@rollup/plugin-alias": "^3.1.2",
"@rollup/plugin-commonjs": "^17.1.0",
"@rollup/plugin-commonjs": "^21.1.0",
"@rollup/plugin-json": "^4.1.0",
"@rollup/plugin-node-resolve": "^11.2.0",
"@rollup/plugin-typescript": "^8.2.1",
Expand Down
84 changes: 44 additions & 40 deletions script/build-main.ts
Original file line number Diff line number Diff line change
@@ -1,52 +1,56 @@
/**
* electron 打包
*/
import { join } from 'path'
import { spawn, ChildProcess } from 'child_process'
import { watch, rollup, OutputOptions } from 'rollup'
import minimist from 'minimist'
import chalk from 'chalk'
import ora from 'ora'
import electron from 'electron'
import dotenv from 'dotenv'
import { waitOn } from './utils'
import options from './rollup.config'
import { main } from '../package.json'
import { join } from "path";
import { spawn, ChildProcess } from "child_process";
import { watch, rollup, OutputOptions } from "rollup";
import minimist from "minimist";
import chalk from "chalk";
import ora from "ora";
import electron from "electron";
import dotenv from "dotenv";
import { waitOn } from "./utils";
import options from "./rollup.config";
import { main } from "../package.json";

dotenv.config({ path: join(__dirname, '../.env') })
dotenv.config({ path: join(__dirname, "../.env") });

const argv = minimist(process.argv.slice(2))
const opts = options(argv.env)
const TAG = '[build-main.ts]'
const spinner = ora(`${TAG} Electron build...`)
const argv = minimist(process.argv.slice(2));
const opts = options(argv.env);
const TAG = "[build-main.ts]";
const spinner = ora(`${TAG} Electron build...`);

if (argv.watch) {
waitOn({ port: process.env.PORT as string }).then(msg => {
const watcher = watch(opts)
let child: ChildProcess
watcher.on('change', filename => {
const log = chalk.green(`change -- ${filename}`)
console.log(TAG, log)
})
watcher.on('event', ev => {
if (ev.code === 'END') {
if (child) child.kill()
child = spawn(electron as any, [join(__dirname, `../${main}`), '--inspect'], { stdio: 'inherit' })
} else if (ev.code === 'ERROR') {
console.log(ev.error)
waitOn({ port: process.env.PORT as string }).then((msg) => {
const watcher = watch(opts);
let child: ChildProcess;
watcher.on("change", (filename) => {
const log = chalk.green(`change -- ${filename}`);
console.log(TAG, log);
});
watcher.on("event", (ev) => {
if (ev.code === "END") {
if (child) child.kill();
child = spawn(
electron as any,
[join(__dirname, `../${main}`), "--inspect"],
{ stdio: "inherit" }
);
} else if (ev.code === "ERROR") {
console.log(ev.error);
}
})
})
});
});
} else {
spinner.start()
spinner.start();
rollup(opts)
.then(build => {
spinner.stop()
console.log(TAG, chalk.green('Electron build successed.'))
build.write(opts.output as OutputOptions)
})
.catch(error => {
spinner.stop()
console.log(`\n${TAG} ${chalk.red('构建报错')}\n`, error, '\n')
.then((build) => {
spinner.stop();
console.log(TAG, chalk.green("Electron build successed."));
build.write(opts.output as OutputOptions);
})
.catch((error) => {
spinner.stop();
console.log(`\n${TAG} ${chalk.red("构建报错")}\n`, error, "\n");
});
}
90 changes: 48 additions & 42 deletions script/plugins/index.ts
Original file line number Diff line number Diff line change
@@ -1,87 +1,93 @@
import path from 'path'
import acorn from 'acorn'
import { Plugin as RollupPlugin } from 'rollup'
import { Plugin as VitePlugin } from 'vite'
import { vue_js_ts_extensions } from './utils'
import path from "path";
import acorn from "acorn";
import { Plugin as RollupPlugin } from "rollup";
import { Plugin as VitePlugin } from "vite";
import { vue_js_ts_extensions } from "./utils";

/**
* cjs2esm
* @deprecated
*/
export function cjs2esm() {
return {
name: '@rollup/plugin-cjs2esm',
name: "@rollup/plugin-cjs2esm",
transform(code: string, filename: string) {
if (filename.includes(`${path.sep}node_modules${path.sep}`)) {
return code
return code;
}

const cjsRegexp = /(const|let|var)[\n\s]+(\w+)[\n\s]*=[\n\s]*require\(["|'](.+)["|']\)/g
const res = code.match(cjsRegexp)
const cjsRegexp =
/(const|let|var)[\n\s]+(\w+)[\n\s]*=[\n\s]*require\(["|'](.+)["|']\)/g;
const res = code.match(cjsRegexp);
if (res) {
// const Store = require('electron-store') -> import Store from 'electron-store'
code = code.replace(cjsRegexp, `import $2 from '$3'`)
code = code.replace(cjsRegexp, "import $2 from '$3'");
}
return code
return code;
},
}
};
}

/** esm2cjs */
export function esm2cjs(moduleList: string[]): VitePlugin {
const filter = {
include: (id: string) => vue_js_ts_extensions.includes(path.parse(id).ext)
}
include: (id: string) => vue_js_ts_extensions.includes(path.parse(id).ext),
};

return {
name: 'cxmh:esm2cjs',
name: "cxmh:esm2cjs",
transform(code, id) {
if (filter.include(id)) {
const node: any = acorn.parse(code, {
ecmaVersion: 'latest',
sourceType: 'module',
})
ecmaVersion: "latest",
sourceType: "module",
});

const parsed = path.parse(id)
const parsed = path.parse(id);

let codeRet = code
let codeRet = code;
node.body.reverse().forEach((item) => {
if (item.type !== 'ImportDeclaration') return
if (!moduleList.includes(item.source.value)) return // 跳过不要转换的模块
if (item.type !== "ImportDeclaration") return;
if (!moduleList.includes(item.source.value)) return; // 跳过不要转换的模块

const start = codeRet.substring(0, item.start)
const end = codeRet.substring(item.end)
const deft = item.specifiers.find(({ type }) => type === 'ImportDefaultSpecifier')
const deftModule = deft ? deft.local.name : ''
const nameAs = item.specifiers.find(({ type }) => type === 'ImportNamespaceSpecifier')
const nameAsModule = nameAs ? nameAs.local.name : ''
const modules = item.
specifiers
.filter((({ type }) => type === 'ImportSpecifier'))
.reduce((acc, cur) => acc.concat(cur.imported.name), [])
const start = codeRet.substring(0, item.start);
const end = codeRet.substring(item.end);
const deft = item.specifiers.find(
({ type }) => type === "ImportDefaultSpecifier"
);
const deftModule = deft ? deft.local.name : "";
const nameAs = item.specifiers.find(
({ type }) => type === "ImportNamespaceSpecifier"
);
const nameAsModule = nameAs ? nameAs.local.name : "";
const modules = item.specifiers
.filter(({ type }) => type === "ImportSpecifier")
.reduce((acc, cur) => acc.concat(cur.imported.name), []);

// console.log(deftModule, '|', nameAsModule, '|', modules, '\n----')

if (nameAsModule) {
// import * as name from
codeRet = `${start}const ${nameAsModule} = require(${item.source.raw})${end}`
codeRet = `${start}const ${nameAsModule} = require(${item.source.raw})${end}`;
} else if (deftModule && !modules.length) {
// import name from 'mod'
codeRet = `${start}const ${deftModule} = require(${item.source.raw})${end}`
codeRet = `${start}const ${deftModule} = require(${item.source.raw})${end}`;
} else if (deftModule && modules.length) {
// import name, { name2, name3 } from 'mod'
codeRet = `${start}const ${deftModule} = require(${item.source.raw})
const { ${modules.join(', ')} } = ${deftModule}${end}`
const { ${modules.join(", ")} } = ${deftModule}${end}`;
} else {
// import { name1, name2 } from 'mod'
codeRet = `${start}const { ${modules.join(', ')} } = require(${item.source.raw})${end}`
codeRet = `${start}const { ${modules.join(", ")} } = require(${
item.source.raw
})${end}`;
}
})
});

return codeRet
return codeRet;
}
},
}
};
}

/**
Expand All @@ -91,16 +97,16 @@ const { ${modules.join(', ')} } = ${deftModule}${end}`
*/
export function ensureCwdCrrect(filename: string): RollupPlugin {
return {
name: 'cxmh:ensure-cwd-crrect',
name: "cxmh:ensure-cwd-crrect",
transform(code, id) {
if (id === filename) {
return `
// !!! ensure cwd crrect
process.chdir(__dirname)
${code}
`
`;
}
},
}
};
}
5 changes: 2 additions & 3 deletions script/plugins/utils.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@

/** HelloWorld.vue?vue&type=style&index=0&scoped=true&lang.css -> HelloWorld.vue */
export function cleanUrl(url: string) {
return url.replace(/(\?|#).*$/, '')
return url.replace(/(\?|#).*$/, "");
}

export const vue_js_ts_extensions = ['.vue', '.js', '.jsx', '.ts', '.tsx']
export const vue_js_ts_extensions = [".vue", ".js", ".jsx", ".ts", ".tsx"];
49 changes: 23 additions & 26 deletions script/rollup.config.ts
Original file line number Diff line number Diff line change
@@ -1,42 +1,39 @@
import { join } from 'path'
import { RollupOptions } from 'rollup'
import nodeResolve from '@rollup/plugin-node-resolve'
import commonjs from '@rollup/plugin-commonjs'
import typescript from '@rollup/plugin-typescript'
import alias from '@rollup/plugin-alias'
import json from '@rollup/plugin-json'
import { builtins } from './utils'
import { join } from "path";
import { RollupOptions } from "rollup";
import nodeResolve from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import typescript from "@rollup/plugin-typescript";
import alias from "@rollup/plugin-alias";
import json from "@rollup/plugin-json";
import { builtins } from "./utils";

export default (env = 'production') => {
export default (env = "production") => {
const options: RollupOptions = {
input: join(__dirname, '../src/main/index.ts'),
input: join(__dirname, "../src/main/index.ts"),
output: {
file: join(__dirname, '../dist/main/index.js'),
format: 'cjs',
name: 'ElectronMainBundle',
file: join(__dirname, "../dist/main/index.js"),
format: "cjs",
name: "ElectronMainBundle",
sourcemap: true,
},
plugins: [
nodeResolve(),
commonjs(),
json(),
typescript({
module: 'ESNext',
module: "ESNext",
}),
alias({
entries: [
{ find: '@', replacement: join(__dirname, '../src/render') },
{ find: '@main', replacement: join(__dirname, '../src/main') },
{ find: '@src', replacement: join(__dirname, '../src') },
{ find: '@root', replacement: join(__dirname, '..') },
]
{ find: "@", replacement: join(__dirname, "../src/render") },
{ find: "@main", replacement: join(__dirname, "../src/main") },
{ find: "@src", replacement: join(__dirname, "../src") },
{ find: "@root", replacement: join(__dirname, "..") },
],
}),
],
external: [
...builtins(),
'electron',
],
}
external: [...builtins(), "electron"],
};

return options
}
return options;
};
41 changes: 23 additions & 18 deletions script/utils.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,29 @@
import { builtinModules } from 'module'
import { get } from 'http'
import { green } from 'chalk'
import { builtinModules } from "module";
import { get } from "http";
import { green } from "chalk";

/** 轮询监听 vite 启动 */
export function waitOn(arg0: { port: string | number; interval?: number; }) {
return new Promise(resolve => {
const { port, interval = 149 } = arg0
const url = `http://localhost:${port}`
let counter = 0
export function waitOn(arg0: { port: string | number; interval?: number }) {
return new Promise((resolve) => {
const { port, interval = 149 } = arg0;
const url = `http://localhost:${port}`;
let counter = 0;
const timer: NodeJS.Timer = setInterval(() => {
get(url, res => {
clearInterval(timer)
console.log('[waitOn]', green(`"${url}" are already responsive.`), `(${res.statusCode}: ${res.statusMessage})`)
resolve(res.statusCode)
}).on('error', err => {
console.log('[waitOn]', `counter: ${counter++}`)
})
}, interval)
})
get(url, (res) => {
clearInterval(timer);
console.log(
"[waitOn]",
green(`"${url}" are already responsive.`),
`(${res.statusCode}: ${res.statusMessage})`
);
resolve(res.statusCode);
}).on("error", (err) => {
console.log("[waitOn]", `counter: ${counter++}`);
});
}, interval);
});
}

/** node.js builtins module */
export const builtins = () => builtinModules.filter(x => !/^_|^(internal|v8|node-inspect)\/|\//.test(x))
export const builtins = () =>
builtinModules.filter((x) => !/^_|^(internal|v8|node-inspect)\/|\//.test(x));
2 changes: 1 addition & 1 deletion src/main/app/protocol.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { BrowserWindow, protocol, app } from "electron";
import { app } from "electron";
import path from "path";

const agreement = "sayo";
Expand Down
Loading

0 comments on commit b3c6076

Please sign in to comment.