Skip to content

Commit 67ff257

Browse files
authored
chore: reduce the usage of require (#8121)
1 parent 05e71d5 commit 67ff257

File tree

20 files changed

+63
-49
lines changed

20 files changed

+63
-49
lines changed

package.json

+1
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@
4848
"@types/less": "^3.0.3",
4949
"@types/micromatch": "^4.0.2",
5050
"@types/mime": "^2.0.3",
51+
"@types/minimist": "^1.2.2",
5152
"@types/node": "^17.0.31",
5253
"@types/prompts": "^2.4.0",
5354
"@types/resolve": "^1.20.2",

packages/vite/src/node/build.ts

+4-3
Original file line numberDiff line numberDiff line change
@@ -389,7 +389,6 @@ async function doBuild(
389389
)
390390
}
391391

392-
const rollup = require('rollup') as typeof Rollup
393392
const rollupOptions: RollupOptions = {
394393
input,
395394
context: 'globalThis',
@@ -470,7 +469,8 @@ async function doBuild(
470469
}
471470

472471
const watcherOptions = config.build.watch
473-
const watcher = rollup.watch({
472+
const { watch } = await import('rollup')
473+
const watcher = watch({
474474
...rollupOptions,
475475
output,
476476
watch: {
@@ -506,7 +506,8 @@ async function doBuild(
506506
}
507507

508508
// write or generate files with rollup
509-
const bundle = await rollup.rollup(rollupOptions)
509+
const { rollup } = await import('rollup')
510+
const bundle = await rollup(rollupOptions)
510511
parallelBuilds.push(bundle)
511512

512513
const generate = (output: OutputOptions = {}) => {

packages/vite/src/node/config.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -816,7 +816,7 @@ export async function loadConfigFromFile(
816816
let userConfig: UserConfigExport | undefined
817817

818818
if (isESM) {
819-
const fileUrl = require('url').pathToFileURL(resolvedPath)
819+
const fileUrl = pathToFileURL(resolvedPath)
820820
const bundled = await bundleConfigFile(resolvedPath, true)
821821
dependencies = bundled.dependencies
822822
if (isTS) {

packages/vite/src/node/http.ts

+9-5
Original file line numberDiff line numberDiff line change
@@ -95,23 +95,27 @@ export async function resolveHttpServer(
9595
httpsOptions?: HttpsServerOptions
9696
): Promise<HttpServer> {
9797
if (!httpsOptions) {
98-
return require('http').createServer(app)
98+
const { createServer } = await import('http')
99+
return createServer(app)
99100
}
100101

102+
// #484 fallback to http1 when proxy is needed.
101103
if (proxy) {
102-
// #484 fallback to http1 when proxy is needed.
103-
return require('https').createServer(httpsOptions, app)
104+
const { createServer } = await import('http')
105+
return createServer(httpsOptions, app)
104106
} else {
105-
return require('http2').createSecureServer(
107+
const { createSecureServer } = await import('http2')
108+
return createSecureServer(
106109
{
107110
// Manually increase the session memory to prevent 502 ENHANCE_YOUR_CALM
108111
// errors on large numbers of requests
109112
maxSessionMemory: 1000,
110113
...httpsOptions,
111114
allowHTTP1: true
112115
},
116+
// @ts-expect-error TODO: is this correct?
113117
app
114-
)
118+
) as unknown as HttpServer
115119
}
116120
}
117121

packages/vite/src/node/optimizer/esbuildDepPlugin.ts

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import path from 'path'
2+
import { promises as fs } from 'fs'
23
import type { ImportKind, Plugin } from 'esbuild'
34
import { KNOWN_ASSET_TYPES } from '../constants'
45
import type { ResolvedConfig } from '..'
@@ -220,7 +221,7 @@ export function esbuildDepPlugin(
220221
})
221222
)
222223
build.onLoad({ filter: /.*/ }, async (args) => ({
223-
contents: await require('fs').promises.readFile(args.path),
224+
contents: await fs.readFile(args.path),
224225
loader: 'default'
225226
}))
226227
}

packages/vite/src/node/plugins/terser.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import type { ResolvedConfig } from '..'
66
export function terserPlugin(config: ResolvedConfig): Plugin {
77
const makeWorker = () =>
88
new Worker(
9-
(basedir: string, code: string, options: Terser.MinifyOptions) => {
9+
async (basedir: string, code: string, options: Terser.MinifyOptions) => {
1010
// when vite is linked, the worker thread won't share the same resolve
1111
// root with vite itself, so we have to pass in the basedir and resolve
1212
// terser first.

packages/vite/src/node/plugins/worker.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -81,9 +81,9 @@ export async function bundleWorkerEntry(
8181
query: Record<string, string> | null
8282
): Promise<Buffer> {
8383
// bundle the file as entry to support imports
84-
const rollup = require('rollup') as typeof Rollup
84+
const { rollup } = await import('rollup')
8585
const { plugins, rollupOptions, format } = config.worker
86-
const bundle = await rollup.rollup({
86+
const bundle = await rollup({
8787
...rollupOptions,
8888
input: cleanUrl(id),
8989
plugins,

playground/css/__tests__/css.spec.ts

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { readFileSync } from 'fs'
12
import {
23
editFile,
34
findAssetFile,
@@ -394,7 +395,7 @@ test('?raw', async () => {
394395
const rawImportCss = await page.$('.raw-imported-css')
395396

396397
expect(await rawImportCss.textContent()).toBe(
397-
require('fs').readFileSync(require.resolve('../raw-imported.css'), 'utf-8')
398+
readFileSync(require.resolve('../raw-imported.css'), 'utf-8')
398399
)
399400
})
400401

playground/fs-serve/__tests__/fs-serve.spec.ts

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1+
import testJSON from '../safe.json'
12
import { isServe, page, viteTestUrl } from '~utils'
23

3-
const json = require('../safe.json')
4-
const stringified = JSON.stringify(json)
4+
const stringified = JSON.stringify(testJSON)
55

66
describe.runIf(isServe)('main', () => {
77
beforeAll(async () => {
@@ -13,7 +13,7 @@ describe.runIf(isServe)('main', () => {
1313
})
1414

1515
test('named import', async () => {
16-
expect(await page.textContent('.named')).toBe(json.msg)
16+
expect(await page.textContent('.named')).toBe(testJSON.msg)
1717
})
1818

1919
test('safe fetch', async () => {

playground/json/__tests__/json.spec.ts

+6-5
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,17 @@
1+
import { readFileSync } from 'fs'
2+
import testJson from '../test.json'
13
import { isBuild, page } from '~utils'
24

35
const deepJson = require('vue/package.json')
4-
const json = require('../test.json')
5-
const stringified = JSON.stringify(json)
6+
const stringified = JSON.stringify(testJson)
67
const deepStringified = JSON.stringify(deepJson)
78

89
test('default import', async () => {
910
expect(await page.textContent('.full')).toBe(stringified)
1011
})
1112

1213
test('named import', async () => {
13-
expect(await page.textContent('.named')).toBe(json.hello)
14+
expect(await page.textContent('.named')).toBe(testJson.hello)
1415
})
1516

1617
test('deep import', async () => {
@@ -26,7 +27,7 @@ test('dynamic import', async () => {
2627
})
2728

2829
test('dynamic import, named', async () => {
29-
expect(await page.textContent('.dynamic-named')).toBe(json.hello)
30+
expect(await page.textContent('.dynamic-named')).toBe(testJson.hello)
3031
})
3132

3233
test('fetch', async () => {
@@ -41,6 +42,6 @@ test('?url', async () => {
4142

4243
test('?raw', async () => {
4344
expect(await page.textContent('.raw')).toBe(
44-
require('fs').readFileSync(require.resolve('../test.json'), 'utf-8')
45+
readFileSync(require.resolve('../test.json'), 'utf-8')
4546
)
4647
})

playground/legacy/__tests__/legacy.spec.ts

+8-8
Original file line numberDiff line numberDiff line change
@@ -81,15 +81,15 @@ describe.runIf(isBuild)('build', () => {
8181
// This is a ghetto heuristic, but terser output seems to reliably start
8282
// with one of the following, and non-terser output (including unminified or
8383
// ebuild-minified) does not!
84-
const terserPatt = /^(?:!function|System.register)/
84+
const terserPattern = /^(?:!function|System.register)/
8585

86-
expect(findAssetFile(/chunk-async-legacy/)).toMatch(terserPatt)
87-
expect(findAssetFile(/chunk-async\./)).not.toMatch(terserPatt)
88-
expect(findAssetFile(/immutable-chunk-legacy/)).toMatch(terserPatt)
89-
expect(findAssetFile(/immutable-chunk\./)).not.toMatch(terserPatt)
90-
expect(findAssetFile(/index-legacy/)).toMatch(terserPatt)
91-
expect(findAssetFile(/index\./)).not.toMatch(terserPatt)
92-
expect(findAssetFile(/polyfills-legacy/)).toMatch(terserPatt)
86+
expect(findAssetFile(/chunk-async-legacy/)).toMatch(terserPattern)
87+
expect(findAssetFile(/chunk-async\./)).not.toMatch(terserPattern)
88+
expect(findAssetFile(/immutable-chunk-legacy/)).toMatch(terserPattern)
89+
expect(findAssetFile(/immutable-chunk\./)).not.toMatch(terserPattern)
90+
expect(findAssetFile(/index-legacy/)).toMatch(terserPattern)
91+
expect(findAssetFile(/index\./)).not.toMatch(terserPattern)
92+
expect(findAssetFile(/polyfills-legacy/)).toMatch(terserPattern)
9393
})
9494

9595
test('should emit css file', async () => {

playground/legacy/__tests__/ssr/serve.ts

+5-6
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import { ports } from '~utils'
66
export const port = ports['legacy/ssr']
77

88
export async function serve(root: string, _isProd: boolean) {
9-
const { build } = require('vite')
9+
const { build } = await import('vite')
1010
await build({
1111
root,
1212
logLevel: 'silent',
@@ -17,14 +17,13 @@ export async function serve(root: string, _isProd: boolean) {
1717
}
1818
})
1919

20-
const express = require('express')
20+
const { default: express } = await import('express')
2121
const app = express()
2222

2323
app.use('/', async (_req, res) => {
24-
const { render } = require(path.resolve(
25-
root,
26-
'./dist/server/entry-server.js'
27-
))
24+
const { render } = await import(
25+
path.resolve(root, './dist/server/entry-server.js')
26+
)
2827
const html = await render()
2928
res.status(200).set({ 'Content-Type': 'text/html' }).end(html)
3029
})

playground/lib/__tests__/serve.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ export async function serve(root, isBuildTest) {
1212
setupConsoleWarnCollector()
1313

1414
if (!isBuildTest) {
15-
const { createServer } = require('vite')
15+
const { createServer } = await import('vite')
1616
process.env.VITE_INLINE = 'inline-serve'
1717
const viteServer = await (
1818
await createServer({
@@ -40,7 +40,7 @@ export async function serve(root, isBuildTest) {
4040

4141
return viteServer
4242
} else {
43-
const { build } = require('vite')
43+
const { build } = await import('vite')
4444
await build({
4545
root,
4646
logLevel: 'silent',

playground/ssr-react/__tests__/serve.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ export const port = ports['ssr-react']
1010
export async function serve(root: string, isProd: boolean) {
1111
if (isProd) {
1212
// build first
13-
const { build } = require('vite')
13+
const { build } = await import('vite')
1414
// client build
1515
await build({
1616
root,

playground/ssr-vue/__tests__/serve.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ export const port = ports['ssr-vue']
1010
export async function serve(root, isProd) {
1111
if (isProd) {
1212
// build first
13-
const { build } = require('vite')
13+
const { build } = await import('vite')
1414
// client build
1515
await build({
1616
root,

playground/ssr-webworker/__tests__/serve.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ export async function serve(root: string, isProd: boolean) {
1212

1313
// we build first, regardless of whether it's prod/build mode
1414
// because Vite doesn't support the concept of a "webworker server"
15-
const { build } = require('vite')
15+
const { build } = await import('vite')
1616

1717
// worker build
1818
await build({

playground/vitestSetup.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ beforeAll(async (s) => {
6767
browser = await chromium.connect(wsEndpoint)
6868
page = await browser.newPage()
6969

70-
const globalConsole = globalThis.console
70+
const globalConsole = global.console
7171
const warn = globalConsole.warn
7272
globalConsole.warn = (msg, ...args) => {
7373
// suppress @vue/reactivity-transform warning

playground/vue/CustomBlockPlugin.ts

+3-2
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,13 @@ import type { Plugin } from 'vite'
22

33
export const vueI18nPlugin: Plugin = {
44
name: 'vue-i18n',
5-
transform(code, id) {
5+
async transform(code, id) {
66
if (!/vue&type=i18n/.test(id)) {
77
return
88
}
99
if (/\.ya?ml$/.test(id)) {
10-
code = JSON.stringify(require('js-yaml').load(code.trim()))
10+
const { load } = await import('js-yaml')
11+
code = JSON.stringify(load(code.trim()))
1112
}
1213
return {
1314
code: `export default Comp => {

pnpm-lock.yaml

+2
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

scripts/releaseUtils.ts

+8-5
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,17 @@
11
/**
22
* modified from https://github.com/vuejs/core/blob/master/scripts/release.js
33
*/
4-
import { existsSync, readFileSync, readdirSync, writeFileSync } from 'fs'
4+
import { existsSync, readdirSync, writeFileSync } from 'fs'
55
import path from 'path'
66
import colors from 'picocolors'
77
import type { Options as ExecaOptions } from 'execa'
88
import execa from 'execa'
99
import type { ReleaseType } from 'semver'
1010
import semver from 'semver'
11+
import fs from 'fs-extra'
12+
import minimist from 'minimist'
1113

12-
export const args = require('minimist')(process.argv.slice(2))
14+
export const args = minimist(process.argv.slice(2))
1315

1416
export const isDryRun = !!args.dry
1517

@@ -136,7 +138,7 @@ export function getVersionChoices(currentVersion: string) {
136138
}
137139

138140
export function updateVersion(pkgPath: string, version: string): void {
139-
const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'))
141+
const pkg = fs.readJSONSync(pkgPath)
140142
pkg.version = version
141143
writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n')
142144
}
@@ -195,7 +197,8 @@ export async function logRecentCommits(pkgName: string) {
195197
}
196198

197199
export async function updateTemplateVersions() {
198-
const viteVersion = require('../packages/vite/package.json').version
200+
const viteVersion = (await fs.readJSON('../packages/vite/package.json'))
201+
.version
199202
if (/beta|alpha|rc/.test(viteVersion)) return
200203

201204
const dir = path.resolve(__dirname, '../packages/create-vite')
@@ -209,7 +212,7 @@ export async function updateTemplateVersions() {
209212
pkg.devDependencies.vite = `^` + viteVersion
210213
if (template.startsWith('template-vue')) {
211214
pkg.devDependencies['@vitejs/plugin-vue'] =
212-
`^` + require('../packages/plugin-vue/package.json').version
215+
`^` + (await fs.readJSON('../packages/plugin-vue/package.json')).version
213216
}
214217
writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n')
215218
}

0 commit comments

Comments
 (0)