Skip to content

Commit 499ad3c

Browse files
authored
Add Vite example (#3)
1 parent 1318f4e commit 499ad3c

File tree

4 files changed

+497
-124
lines changed

4 files changed

+497
-124
lines changed

.github/workflows/CI.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,3 +18,4 @@ jobs:
1818
- run: yarn install
1919
- run: yarn run:webpack
2020
- run: yarn run:esbuild
21+
- run: yarn run:vite

package.json

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,19 @@
55
"type": "module",
66
"packageManager": "yarn@4.1.1",
77
"devDependencies": {
8-
"@node-rs/argon2": "^1.7.2",
8+
"@node-rs/argon2": "^1.8.0",
99
"@types/webpack": "^5.28.5",
10+
"builtin-modules": "^3.3.0",
1011
"esbuild": "^0.20.1",
1112
"node-loader": "^2.0.0",
12-
"rollup": "^4.12.0",
13+
"rollup": "^4.13.0",
14+
"vite": "^5.1.6",
1315
"webpack": "^5.90.3",
1416
"webpack-cli": "^5.1.4"
1517
},
1618
"scripts": {
1719
"run:esbuild": "yarn esbuild --bundle src/index.js --outfile=dist/esbuild.cjs --platform=node --loader:.node=copy --format=cjs && node dist/esbuild.cjs",
20+
"run:vite": "yarn vite build && node dist/vite.cjs",
1821
"run:webpack": "webpack --mode=production && node dist/bundled.cjs"
1922
}
2023
}

vite.config.ts

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import { existsSync } from "node:fs";
2+
import { readFile } from "node:fs/promises";
3+
import { basename } from "node:path";
4+
5+
import { Plugin, defineConfig } from "vite";
6+
import builtinModules from "builtin-modules";
7+
8+
const ViteNodeAddonPlugin = (): Plugin => {
9+
return {
10+
name: "native-addon",
11+
apply: "build",
12+
enforce: "pre",
13+
async load(id) {
14+
if (id.endsWith(".node") && existsSync(id)) {
15+
const refId = this.emitFile({
16+
type: "asset",
17+
fileName: basename(id),
18+
source: await readFile(id),
19+
});
20+
const runtimePath = `./${this.getFileName(refId)}`;
21+
return (
22+
`const id = ${JSON.stringify(runtimePath)};` +
23+
`export default require(id);`
24+
);
25+
}
26+
return null;
27+
},
28+
};
29+
};
30+
31+
export default defineConfig({
32+
resolve: {
33+
mainFields: ["module", "main"],
34+
},
35+
plugins: [ViteNodeAddonPlugin()],
36+
build: {
37+
rollupOptions: {
38+
input: "./src/index.js",
39+
output: {
40+
format: "cjs",
41+
entryFileNames: "vite.cjs",
42+
},
43+
},
44+
target: "esnext",
45+
ssr: true,
46+
ssrEmitAssets: true,
47+
},
48+
ssr: {
49+
external: builtinModules as string[],
50+
noExternal: true,
51+
},
52+
});

0 commit comments

Comments
 (0)