vite-node 0.0.4 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +16 -7
  2. package/index.mjs +81 -25
  3. package/package.json +10 -10
package/README.md CHANGED
@@ -6,9 +6,6 @@ Vite as Node runtime.
6
6
 
7
7
  > **EXPERIMENTAL**
8
8
 
9
- ## Why?
10
-
11
- It runs Vite's id resolving, module transforming, and most importantly, the powerful plugins system!
12
9
 
13
10
  ## Usage
14
11
 
@@ -16,19 +13,31 @@ It runs Vite's id resolving, module transforming, and most importantly, the powe
16
13
  npx vite-node index.ts
17
14
  ```
18
15
 
16
+ Options:
17
+
18
+ ```bash
19
+ npx vite-node -h
20
+ ```
21
+
19
22
  ## Features
20
23
 
21
24
  - Out-of-box ESM & TypeScript support (possible for more with plugins)
22
25
  - Top-level await
23
- - Shims for `__dirname` and `__filename`
26
+ - Vite plugins, resolve, aliasing
24
27
  - Respect `vite.config.ts`
25
- - Access to node modules like `fs`, `path` etc.
28
+ - Shims for `__dirname` and `__filename` in ESM
29
+ - Access to native node modules like `fs`, `path`, etc.
30
+ - Watch mode (like `nodemon`)
26
31
 
27
32
  ## When NOT to Use
28
33
 
29
34
  - Production, yet - in very early stage, check it later
30
- - Most of the time when other tools can do that job
31
- - We will need to start a Vite server upon each execution, which will have certain overhead. Only use it when you want the exactly same behavior as Vite or the powerful plugins system (for example, testing components that have Vite-specific setup).
35
+ - Most of the time, when other tools can do that job
36
+ - We need to start a Vite server upon each execution, which inevitably introduces some overhead. Only use it when you want the same behavior as Vite or the powerful plugins system (for example, testing components with a Vite-specific setup).
37
+
38
+ ## Why?
39
+
40
+ It runs Vite's id resolving, module transforming, and most importantly, the powerful plugins system!
32
41
 
33
42
  ## How?
34
43
 
package/index.mjs CHANGED
@@ -1,19 +1,24 @@
1
+ /* eslint-disable no-console */
1
2
  import { builtinModules, createRequire } from 'module'
2
3
  import { pathToFileURL } from 'url'
3
4
  import { dirname, resolve, relative } from 'path'
5
+ import vm from 'vm'
4
6
  import { createServer } from 'vite'
5
7
  import createDebug from 'debug'
6
8
  import minimist from 'minimist'
7
- import { red, dim, yellow } from 'kolorist'
9
+ import { red, dim, yellow, green, inverse, cyan } from 'kolorist'
8
10
 
9
11
  const argv = minimist(process.argv.slice(2), {
10
- alias: {
12
+ 'alias': {
11
13
  r: 'root',
12
14
  c: 'config',
13
15
  h: 'help',
16
+ w: 'watch',
17
+ s: 'silent',
14
18
  },
15
- string: ['root', 'config'],
16
- boolean: ['help', 'vue'],
19
+ '--': true,
20
+ 'string': ['root', 'config'],
21
+ 'boolean': ['help', 'vue', 'watch', 'silent'],
17
22
  unknown(name) {
18
23
  if (name[0] === '-') {
19
24
  console.error(red(`Unknown argument: ${name}`))
@@ -35,14 +40,18 @@ if (!argv._.length) {
35
40
  process.exit(1)
36
41
  }
37
42
 
43
+ // forward argv
44
+ process.argv = [process.argv.slice(0, 2), ...argv['--']]
45
+
38
46
  const debugRequest = createDebug('vite-node:request')
39
47
  const debugTransform = createDebug('vite-node:transform')
40
- const AsyncFunction = Object.getPrototypeOf(async() => {}).constructor
41
48
 
42
49
  const root = argv.root || process.cwd()
43
50
  process.chdir(root)
44
51
 
45
52
  const server = await createServer({
53
+ logLevel: 'error',
54
+ clearScreen: false,
46
55
  configFile: argv.config,
47
56
  root,
48
57
  resolve: argv.vue
@@ -60,8 +69,50 @@ const server = await createServer({
60
69
  : {},
61
70
  })
62
71
  await server.pluginContainer.buildStart({})
63
- await execute(files, server, argv)
64
- await server.close()
72
+ let executing = false
73
+
74
+ async function run() {
75
+ process.exitCode = 0
76
+ executing = true
77
+ let err
78
+ try {
79
+ await execute(files, server, argv)
80
+ }
81
+ catch (e) {
82
+ console.error(e)
83
+ err = e
84
+ if (!argv.watch)
85
+ process.exit(1)
86
+ }
87
+ finally {
88
+ executing = false
89
+ }
90
+
91
+ if (argv.watch) {
92
+ setTimeout(() => {
93
+ if (err || process.exitCode)
94
+ log(inverse(red(' vite node ')), red('program exited with error, waiting for file changes...'))
95
+ else
96
+ log(inverse(green(' vite node ')), green('program exited, waiting for file changes...'))
97
+ }, 10)
98
+ }
99
+ else {
100
+ await server.close()
101
+ }
102
+ }
103
+
104
+ if (argv.watch) {
105
+ log(inverse(cyan(' vite node ')), cyan('watch mode enabled\n'))
106
+
107
+ server.watcher.on('change', (file) => {
108
+ if (!executing) {
109
+ log(inverse(yellow(' vite node ')), yellow(`${file} changed, restarting...\n`))
110
+ run()
111
+ }
112
+ })
113
+ }
114
+
115
+ await run(files, server, argv)
65
116
 
66
117
  // --- CLI END ---
67
118
 
@@ -85,6 +136,11 @@ function toFilePath(id) {
85
136
  async function execute(files, server) {
86
137
  const __pendingModules__ = new Map()
87
138
 
139
+ const result = []
140
+ for (const file of files)
141
+ result.push(await cachedRequest(`/@fs/${slash(resolve(file))}`, []))
142
+ return result
143
+
88
144
  async function directRequest(rawId, callstack) {
89
145
  if (builtinModules.includes(rawId))
90
146
  return import(rawId)
@@ -133,22 +189,20 @@ async function execute(files, server) {
133
189
  __vite_ssr_import_meta__: { url },
134
190
  }
135
191
 
136
- const fn = new AsyncFunction(
137
- ...Object.keys(context),
138
- result.code,
139
- )
140
-
141
- // prefetch deps
142
- result.deps.forEach(dep => request(dep))
143
-
192
+ const fn = vm.runInThisContext(`async (${Object.keys(context).join(',')}) => { ${result.code} }`, {
193
+ filename: absolute,
194
+ lineOffset: 0,
195
+ })
144
196
  await fn(...Object.values(context))
197
+
145
198
  return exports
146
199
  }
147
200
 
148
- function cachedRequest(id, callstack) {
149
- if (!__pendingModules__[id])
150
- __pendingModules__[id] = directRequest(id, callstack)
151
- return __pendingModules__[id]
201
+ async function cachedRequest(id, callstack) {
202
+ if (__pendingModules__[id])
203
+ return __pendingModules__[id]
204
+ __pendingModules__[id] = directRequest(id, callstack)
205
+ return await __pendingModules__[id]
152
206
  }
153
207
 
154
208
  function exportAll(exports, sourceModule) {
@@ -166,11 +220,6 @@ async function execute(files, server) {
166
220
  }
167
221
  }
168
222
  }
169
-
170
- const result = []
171
- for (const file of files)
172
- result.push(await cachedRequest(`/@fs/${slash(resolve(file))}`, []))
173
- return result
174
223
  }
175
224
 
176
225
  function slash(path) {
@@ -178,7 +227,6 @@ function slash(path) {
178
227
  }
179
228
 
180
229
  function help() {
181
- // eslint-disable-next-line no-console
182
230
  console.log(`
183
231
  Usage:
184
232
  $ vite-node [options] [files]
@@ -186,6 +234,14 @@ Usage:
186
234
  Options:
187
235
  -r, --root <path> ${dim('[string]')} use specified root directory
188
236
  -c, --config <file> ${dim('[string]')} use specified config file
237
+ -w, --watch ${dim('[boolean]')} restart on file changes, similar to "nodemon"
238
+ -s, --silent ${dim('[boolean]')} do not emit errors and logs
189
239
  --vue ${dim('[boolean]')} support for importing Vue component
190
240
  `)
191
241
  }
242
+
243
+ function log(...args) {
244
+ if (argv.silent)
245
+ return
246
+ console.log(...args)
247
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vite-node",
3
- "version": "0.0.4",
3
+ "version": "0.1.2",
4
4
  "description": "Vite as Node runtime",
5
5
  "keywords": [
6
6
  "vite"
@@ -33,23 +33,23 @@
33
33
  "bin"
34
34
  ],
35
35
  "dependencies": {
36
- "debug": "^4.3.2",
36
+ "debug": "^4.3.3",
37
37
  "kolorist": "^1.5.0",
38
38
  "minimist": "^1.2.5",
39
39
  "vite": "^2.6.5"
40
40
  },
41
41
  "devDependencies": {
42
- "@antfu/eslint-config": "^0.9.0",
43
- "@antfu/ni": "^0.10.0",
42
+ "@antfu/eslint-config": "^0.11.1",
43
+ "@antfu/ni": "^0.11.0",
44
44
  "@types/debug": "^4.1.7",
45
- "@types/node": "^16.10.3",
46
- "@vitejs/plugin-vue": "^1.9.3",
45
+ "@types/node": "^16.11.11",
46
+ "@vitejs/plugin-vue": "^1.10.1",
47
47
  "bumpp": "^7.1.1",
48
- "eslint": "^7.32.0",
49
- "esno": "^0.10.1",
50
- "typescript": "^4.4.3",
48
+ "eslint": "^8.3.0",
49
+ "esno": "^0.12.1",
50
+ "typescript": "^4.5.2",
51
51
  "uvu": "^0.5.2",
52
- "vue": "^3.2.20"
52
+ "vue": "^3.2.23"
53
53
  },
54
54
  "engines": {
55
55
  "node": ">=14.0.0"