Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(renderer-app): change render app bundler to vite #1265

Merged
merged 27 commits into from
Jan 14, 2022
Merged
Show file tree
Hide file tree
Changes from 25 commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
c167ead
feat(renderer-app): change to vite,and need resolve electron path
Cyberhan123 Dec 12, 2021
22a4cde
Merge branch 'netless-io:main' into feature/render-vite
Cyberhan123 Dec 18, 2021
c4b3b53
feat(renderer-app): vite-plugin-electron
Cyberhan123 Dec 18, 2021
94427f1
Merge branch 'netless-io:main' into feature/render-vite
Cyberhan123 Dec 28, 2021
3f10182
feat(renderer-app): fix require.context
Cyberhan123 Dec 28, 2021
9107094
Merge branch 'netless-io:main' into feature/render-vite
Cyberhan123 Dec 29, 2021
11ca442
feat(renderer-app): resolve `fs-extra` by esbuild
Cyberhan123 Dec 29, 2021
159c330
Merge branch 'netless-io:main' into feature/render-vite
Cyberhan123 Jan 4, 2022
df0b3fb
feat(renderer-app): resolve all node_model
Cyberhan123 Jan 4, 2022
5d7845f
feat(renderer-app): add eslint plugin and analyzer plugin
Cyberhan123 Jan 4, 2022
491cdbc
chore(renderer-app): add missing package
Cyberhan123 Jan 4, 2022
02f380e
Merge branch 'netless-io:main' into feature/render-vite
Cyberhan123 Jan 5, 2022
5c72f87
refactor(renderer-app): change file layout and split code
Cyberhan123 Jan 5, 2022
6789ec7
chore(renderer-app): remove empty string from config
Cyberhan123 Jan 5, 2022
bfa8666
chore(renderer-app): remove description field
Cyberhan123 Jan 5, 2022
f36a7f1
chore(renderer-app): rename lib.ts and move options to template
Cyberhan123 Jan 6, 2022
0d5e949
Merge branch 'netless-io:main' into feature/render-vite
Cyberhan123 Jan 6, 2022
5ad7c40
Merge remote-tracking branch 'origin/feature/render-vite' into featur…
Cyberhan123 Jan 6, 2022
9aff790
Merge remote-tracking branch 'origin/main' into feature/render-vite
BlackHole1 Jan 7, 2022
bec8a51
refactor(renderer-app): sync main code
BlackHole1 Jan 7, 2022
e5dad4a
refactor(renderer-app): refactor needParse
Cyberhan123 Jan 7, 2022
9678801
chore(renderer-app): add comment
Cyberhan123 Jan 7, 2022
b4ee1b3
Merge branch 'netless-io:main' into feature/render-vite
Cyberhan123 Jan 11, 2022
707630e
chore(renderer-app): lint style and rename method
Cyberhan123 Jan 11, 2022
fc10ce6
Merge branch 'netless-io:main' into feature/render-vite
Cyberhan123 Jan 12, 2022
fab03c4
fix(renderer-app): fix vite build path
Cyberhan123 Jan 12, 2022
55e1f00
Merge remote-tracking branch 'origin/main' into feature/render-vite
BlackHole1 Jan 14, 2022
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions desktop/renderer-app/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<title>Flat</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script type="module" src="/src/index.ts"></script>
</body>
</html>
Cyberhan123 marked this conversation as resolved.
Show resolved Hide resolved
14 changes: 11 additions & 3 deletions desktop/renderer-app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"axios": "^0.21.2",
"classnames": "^2.3.1",
"date-fns": "^2.22.1",
"eventemitter3": "^4.0.7",
"extract-zip": "^2.0.1",
"fs-extra": "^9.0.1",
"i18next": "^20.3.1",
Expand Down Expand Up @@ -79,6 +80,8 @@
"eslint-plugin-eslint-comments": "^3.2.0",
"eslint-plugin-jsx-a11y": "^6.4.1",
"eslint-plugin-prettier": "^3.4.0",
"@vitejs/plugin-react-refresh": "^1.3.3",
"esbuild": "^0.12.20",
"eslint-plugin-react": "^7.24.0",
"eslint-plugin-react-app": "^6.2.2",
"eslint-webpack-plugin": "^3.0.1",
Expand All @@ -96,22 +99,27 @@
"react-refresh": "^0.10.0",
"react-resize-detector": "^6.7.5",
"react-transition-group": "^4.4.2",
"rollup-plugin-visualizer": "^5.5.2",
"style-loader": "^2.0.0",
"terser-webpack-plugin": "^5.1.2",
"thread-loader": "^3.0.4",
"ts-loader": "^9.1.2",
"typescript": "^4.2.4",
"url-loader": "^4.1.1",
"vite": "^2.5.0",
"vite-plugin-eslint": "^1.3.0",
"webpack": "^5.37.0",
"webpack-bundle-analyzer": "^4.4.2",
"webpack-cli": "^4.7.0",
"webpack-dev-server": "^3.11.2",
"webpack-merge": "^5.7.3"
},
"scripts": {
"start": "cross-env NODE_ENV=development node scripts/start.js",
"build": "cross-env NODE_ENV=production webpack --config webpack/webpack.prod.js",
"build:analyzer": "cross-env NODE_ENV=production ANALYZER=true webpack --config webpack/webpack.prod.js",
"start:webpack": "cross-env NODE_ENV=development node scripts/start.js",
"start": "cross-env NODE_ENV=development vite",
"build": "cross-env NODE_ENV=production NODE_OPTIONS=\"--max-old-space-size=6144\" vite build",
"build:analyzer": "cross-env NODE_ENV=production ANALYZER=true NODE_OPTIONS=\"--max-old-space-size=6144\" vite build",
"build:webpack:analyzer": "cross-env NODE_ENV=production ANALYZER=true webpack --config webpack/webpack.prod.js",
"lint": "lint-staged"
}
}
72 changes: 72 additions & 0 deletions desktop/renderer-app/scripts/vite-plugin-electron/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { builtinModules } from "module";
import { Plugin as VitePlugin } from "vite";
import { cjs2esm } from "./utils";
import { options } from "./template/options";

// based on https://github.com/caoxiemeihao/vite-plugins/blob/main/packages/electron/src/index.ts

/**
* The externals will be work on 'viteConfig.build.rollupOptions.external', 'viteConfig.optimizeDeps.exclude' option.
* and we should external ['electron', ...require('module').builtinModules]
*/
const externals = ["electron", ...builtinModules];

export function electron(): VitePlugin[] {
const nodeModelResolve: VitePlugin = {
name: "vite-plugin-electron:node-model-resolve",
Cyberhan123 marked this conversation as resolved.
Show resolved Hide resolved
apply: "serve",
transform(_code, id) {
return cjs2esm(id, options);
},
};

const builtinModulesResolve: VitePlugin = {
apply: "serve",
name: "vite-plugin-electron:builtinModules-resolve",
transform(_code, id) {
/**
* vite not support node build in model so will throw Error to tell `node api is not support in browser`
* We need transform and overwrite error.
* e.g:
* `import path from 'path'`
* vite will analyze this import statement and replace to
* `throw new Error('path is not support in browser!')`
*/
if (!id.startsWith("__vite-browser-external:")) {
return null;
}

const moduleName = id.split(":")[1];

if (!builtinModules.includes(moduleName)) {
return null;
}

// require all project import `nodeModule`
const nodeModule = require(moduleName);
const exportKeys = Object.keys(nodeModule);
const requireTpl = `const __nodeModule = require("${moduleName}");`;
const declaresTpl = exportKeys
.map(key => `const ${key} = __nodeModule.${key};`)
.join("\n");

// transform all `nodeModule` to ESM grammar
const exportTpl = `export { ${exportKeys.join(", ")} };`;
const exportDefault = `export default { ${exportKeys.join(", ")} };`;

const nodeModuleCode = ["", requireTpl, declaresTpl, exportTpl, exportDefault, ""].join(
"\n",
);

return {
code: nodeModuleCode,
map: null,
};
},
};

return [builtinModulesResolve, nodeModelResolve];
}

electron.externals = externals;
export default electron;
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// We will use hack method to bundle file and export it with ESM
const {
clipboard,
nativeImage,
shell,
contextBridge,
crashReporter,
ipcRenderer,
webFrame,
desktopCapturer,
} = require('electron');
export {
clipboard,
nativeImage,
shell,
contextBridge,
crashReporter,
ipcRenderer,
webFrame,
desktopCapturer,
}
export default { clipboard, nativeImage, shell, contextBridge, crashReporter, ipcRenderer, webFrame, desktopCapturer };
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// We will use hack method to bundle file and export it with ESM
const {
EventEmitter,
} = require('events');
export {
EventEmitter,
}
export default { EventEmitter };
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
// We will use hack method to bundle file and export it with ESM
const extract = require('fs-extra');
export default extract;
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// We will use hack method to bundle file and export it with ESM
const {
copy,
ensureDir,
remove,
pathExists ,
} = require('fs-extra');
export {
copy,
ensureDir,
remove,
pathExists,
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { getTemplate } from "../utils";

const electronCode = getTemplate("./template/electron.template.js");
const eventsCode = getTemplate("./template/events.template.js");
const fsExtraCode = getTemplate("./template/fs-extra.template.js");
const extractZipCode = getTemplate("./template/extract-zip.template.js");

export const options = [
{
entryPoints: "electron/index.js",
code: electronCode,
shouldBundle: false,
},
{
entryPoints: "events/events.js",
code: eventsCode,
shouldBundle: false,
},
{
entryPoints: "fs-extra/lib/index.js",
code: fsExtraCode,
shouldBundle: true,
},
{
entryPoints: "extract-zip/index.js",
code: extractZipCode,
shouldBundle: true,
},
];
54 changes: 54 additions & 0 deletions desktop/renderer-app/scripts/vite-plugin-electron/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { build, OutputFile } from "esbuild";
import { readFileSync } from "fs";
import { join } from "path";

// e.g:
// flat/node_modules/electron/index.js?v=19cea64f => flat/node_modules/electron/index.js
const removeQueryString = (url: string): string => url.replace(/\?.*$/s, "").replace(/#.*$/s, "");

const bundleModel = (filePath: string): Promise<OutputFile[]> => {
return build({
entryPoints: [filePath],
bundle: true,
outfile: "index.js",
platform: "node",
write: false,
})
.then(({ outputFiles }) => outputFiles)
.catch(error => {
console.error(error);
return [];
});
};

export const cjs2esm = async (
id: string,
entries: Array<{ entryPoints: string; code: string; shouldBundle: boolean }>,
): Promise<string | null> => {
const filePath = removeQueryString(id);

for (const { entryPoints, code, shouldBundle } of entries) {
if (!filePath.endsWith(entryPoints)) {
continue;
}

if (!shouldBundle) {
return code;
}

const outputFiles = await bundleModel(filePath);
if (outputFiles.length === 0) {
return code;
}

return outputFiles
.map(({ text }) => text)
.join("")
.concat(code);
}
return null;
Cyberhan123 marked this conversation as resolved.
Show resolved Hide resolved
};

export function getTemplate(path: string): string {
return readFileSync(join(__dirname, path), "utf8");
}
2 changes: 1 addition & 1 deletion desktop/renderer-app/src/theme.less
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
@import "~flat-components/theme/fancy-scrollbar.less";
@import "flat-components/theme/fancy-scrollbar.less";

* {
user-select: none;
Expand Down
7 changes: 4 additions & 3 deletions desktop/renderer-app/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,16 @@
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"lib": ["dom", "es2017"],
"module": "CommonJS",
"module": "ESNext",
"jsx": "react",
"baseUrl": ".",
"paths": {
"flat-types": ["../../packages/flat-types/src"],
"flat-i18n": ["../../packages/flat-i18n/locales"],
"flat-components": ["../../packages/flat-components/src"]
}
},
"types": ["vite/client"]
},
"exclude": ["node_modules", "dist", "public"],
"include": ["src/**/*.ts", "src/**/*.tsx", "typings/*.ts"]
"include": ["src/**/*.ts", "src/**/*.tsx", "typings/*.ts", "vite.config.ts","scripts/**/*.ts"]
}
81 changes: 81 additions & 0 deletions desktop/renderer-app/vite.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import refresh from "@vitejs/plugin-react-refresh";
import { defineConfig } from "vite";
import path from "path";
// TODO: find new place to store vite-plugin-dotenv
import { dotenv } from "../../web/flat-web/scripts/vite-plugin-dotenv";
Cyberhan123 marked this conversation as resolved.
Show resolved Hide resolved
import { visualizer } from "rollup-plugin-visualizer";
import { electron } from "./scripts/vite-plugin-electron";
import eslintPlugin from "vite-plugin-eslint";

export default defineConfig(() => {
const plugins = [refresh(), dotenv("../../config"), electron(), eslintPlugin()];
if (process.env.ANALYZER) {
Cyberhan123 marked this conversation as resolved.
Show resolved Hide resolved
plugins.push({
...visualizer(),
enforce: "post",
apply: "build",
});
}
return {
Cyberhan123 marked this conversation as resolved.
Show resolved Hide resolved
plugins,
Cyberhan123 marked this conversation as resolved.
Show resolved Hide resolved
resolve: {
alias: [
// replace webpack alias
{
find: /^~/,
replacement: "",
},
{
find: "flat-types",
replacement: path.join(__dirname, "..", "..", "packages", "flat-types", "src"),
},
{
find: "flat-i18n",
replacement: path.join(
__dirname,
"..",
"..",
"packages",
"flat-i18n",
"locales",
),
},
{
find: "flat-components",
replacement: path.join(
__dirname,
"..",
"..",
"packages",
"flat-components",
"src",
),
},
],
},
build: {
sourcemap: true,
Cyberhan123 marked this conversation as resolved.
Show resolved Hide resolved
rollupOptions: {
output: {
format: "cjs",
},
external: [...electron.externals],
Cyberhan123 marked this conversation as resolved.
Show resolved Hide resolved
},
},
clearScreen: false,
optimizeDeps: {
exclude: [...electron.externals, "fs-extra", "extract-zip"],
Cyberhan123 marked this conversation as resolved.
Show resolved Hide resolved
},
css: {
preprocessorOptions: {
less: {
javascriptEnabled: true,
modifyVars: {
"primary-color": "#3381FF",
"link-color": "#3381FF",
},
},
},
},
};
});
Loading