Skip to content

Commit

Permalink
chore: reduce the usage of require (#8121)
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed May 12, 2022
1 parent 05e71d5 commit 67ff257
Show file tree
Hide file tree
Showing 20 changed files with 63 additions and 49 deletions.
1 change: 1 addition & 0 deletions package.json
Expand Up @@ -48,6 +48,7 @@
"@types/less": "^3.0.3",
"@types/micromatch": "^4.0.2",
"@types/mime": "^2.0.3",
"@types/minimist": "^1.2.2",
"@types/node": "^17.0.31",
"@types/prompts": "^2.4.0",
"@types/resolve": "^1.20.2",
Expand Down
7 changes: 4 additions & 3 deletions packages/vite/src/node/build.ts
Expand Up @@ -389,7 +389,6 @@ async function doBuild(
)
}

const rollup = require('rollup') as typeof Rollup
const rollupOptions: RollupOptions = {
input,
context: 'globalThis',
Expand Down Expand Up @@ -470,7 +469,8 @@ async function doBuild(
}

const watcherOptions = config.build.watch
const watcher = rollup.watch({
const { watch } = await import('rollup')
const watcher = watch({
...rollupOptions,
output,
watch: {
Expand Down Expand Up @@ -506,7 +506,8 @@ async function doBuild(
}

// write or generate files with rollup
const bundle = await rollup.rollup(rollupOptions)
const { rollup } = await import('rollup')
const bundle = await rollup(rollupOptions)
parallelBuilds.push(bundle)

const generate = (output: OutputOptions = {}) => {
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/config.ts
Expand Up @@ -816,7 +816,7 @@ export async function loadConfigFromFile(
let userConfig: UserConfigExport | undefined

if (isESM) {
const fileUrl = require('url').pathToFileURL(resolvedPath)
const fileUrl = pathToFileURL(resolvedPath)
const bundled = await bundleConfigFile(resolvedPath, true)
dependencies = bundled.dependencies
if (isTS) {
Expand Down
14 changes: 9 additions & 5 deletions packages/vite/src/node/http.ts
Expand Up @@ -95,23 +95,27 @@ export async function resolveHttpServer(
httpsOptions?: HttpsServerOptions
): Promise<HttpServer> {
if (!httpsOptions) {
return require('http').createServer(app)
const { createServer } = await import('http')
return createServer(app)
}

// #484 fallback to http1 when proxy is needed.
if (proxy) {
// #484 fallback to http1 when proxy is needed.
return require('https').createServer(httpsOptions, app)
const { createServer } = await import('http')
return createServer(httpsOptions, app)
} else {
return require('http2').createSecureServer(
const { createSecureServer } = await import('http2')
return createSecureServer(
{
// Manually increase the session memory to prevent 502 ENHANCE_YOUR_CALM
// errors on large numbers of requests
maxSessionMemory: 1000,
...httpsOptions,
allowHTTP1: true
},
// @ts-expect-error TODO: is this correct?
app
)
) as unknown as HttpServer
}
}

Expand Down
3 changes: 2 additions & 1 deletion packages/vite/src/node/optimizer/esbuildDepPlugin.ts
@@ -1,4 +1,5 @@
import path from 'path'
import { promises as fs } from 'fs'
import type { ImportKind, Plugin } from 'esbuild'
import { KNOWN_ASSET_TYPES } from '../constants'
import type { ResolvedConfig } from '..'
Expand Down Expand Up @@ -220,7 +221,7 @@ export function esbuildDepPlugin(
})
)
build.onLoad({ filter: /.*/ }, async (args) => ({
contents: await require('fs').promises.readFile(args.path),
contents: await fs.readFile(args.path),
loader: 'default'
}))
}
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/plugins/terser.ts
Expand Up @@ -6,7 +6,7 @@ import type { ResolvedConfig } from '..'
export function terserPlugin(config: ResolvedConfig): Plugin {
const makeWorker = () =>
new Worker(
(basedir: string, code: string, options: Terser.MinifyOptions) => {
async (basedir: string, code: string, options: Terser.MinifyOptions) => {
// when vite is linked, the worker thread won't share the same resolve
// root with vite itself, so we have to pass in the basedir and resolve
// terser first.
Expand Down
4 changes: 2 additions & 2 deletions packages/vite/src/node/plugins/worker.ts
Expand Up @@ -81,9 +81,9 @@ export async function bundleWorkerEntry(
query: Record<string, string> | null
): Promise<Buffer> {
// bundle the file as entry to support imports
const rollup = require('rollup') as typeof Rollup
const { rollup } = await import('rollup')
const { plugins, rollupOptions, format } = config.worker
const bundle = await rollup.rollup({
const bundle = await rollup({
...rollupOptions,
input: cleanUrl(id),
plugins,
Expand Down
3 changes: 2 additions & 1 deletion playground/css/__tests__/css.spec.ts
@@ -1,3 +1,4 @@
import { readFileSync } from 'fs'
import {
editFile,
findAssetFile,
Expand Down Expand Up @@ -394,7 +395,7 @@ test('?raw', async () => {
const rawImportCss = await page.$('.raw-imported-css')

expect(await rawImportCss.textContent()).toBe(
require('fs').readFileSync(require.resolve('../raw-imported.css'), 'utf-8')
readFileSync(require.resolve('../raw-imported.css'), 'utf-8')
)
})

Expand Down
6 changes: 3 additions & 3 deletions playground/fs-serve/__tests__/fs-serve.spec.ts
@@ -1,7 +1,7 @@
import testJSON from '../safe.json'
import { isServe, page, viteTestUrl } from '~utils'

const json = require('../safe.json')
const stringified = JSON.stringify(json)
const stringified = JSON.stringify(testJSON)

describe.runIf(isServe)('main', () => {
beforeAll(async () => {
Expand All @@ -13,7 +13,7 @@ describe.runIf(isServe)('main', () => {
})

test('named import', async () => {
expect(await page.textContent('.named')).toBe(json.msg)
expect(await page.textContent('.named')).toBe(testJSON.msg)
})

test('safe fetch', async () => {
Expand Down
11 changes: 6 additions & 5 deletions playground/json/__tests__/json.spec.ts
@@ -1,16 +1,17 @@
import { readFileSync } from 'fs'
import testJson from '../test.json'
import { isBuild, page } from '~utils'

const deepJson = require('vue/package.json')
const json = require('../test.json')
const stringified = JSON.stringify(json)
const stringified = JSON.stringify(testJson)
const deepStringified = JSON.stringify(deepJson)

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

test('named import', async () => {
expect(await page.textContent('.named')).toBe(json.hello)
expect(await page.textContent('.named')).toBe(testJson.hello)
})

test('deep import', async () => {
Expand All @@ -26,7 +27,7 @@ test('dynamic import', async () => {
})

test('dynamic import, named', async () => {
expect(await page.textContent('.dynamic-named')).toBe(json.hello)
expect(await page.textContent('.dynamic-named')).toBe(testJson.hello)
})

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

test('?raw', async () => {
expect(await page.textContent('.raw')).toBe(
require('fs').readFileSync(require.resolve('../test.json'), 'utf-8')
readFileSync(require.resolve('../test.json'), 'utf-8')
)
})
16 changes: 8 additions & 8 deletions playground/legacy/__tests__/legacy.spec.ts
Expand Up @@ -81,15 +81,15 @@ describe.runIf(isBuild)('build', () => {
// This is a ghetto heuristic, but terser output seems to reliably start
// with one of the following, and non-terser output (including unminified or
// ebuild-minified) does not!
const terserPatt = /^(?:!function|System.register)/
const terserPattern = /^(?:!function|System.register)/

expect(findAssetFile(/chunk-async-legacy/)).toMatch(terserPatt)
expect(findAssetFile(/chunk-async\./)).not.toMatch(terserPatt)
expect(findAssetFile(/immutable-chunk-legacy/)).toMatch(terserPatt)
expect(findAssetFile(/immutable-chunk\./)).not.toMatch(terserPatt)
expect(findAssetFile(/index-legacy/)).toMatch(terserPatt)
expect(findAssetFile(/index\./)).not.toMatch(terserPatt)
expect(findAssetFile(/polyfills-legacy/)).toMatch(terserPatt)
expect(findAssetFile(/chunk-async-legacy/)).toMatch(terserPattern)
expect(findAssetFile(/chunk-async\./)).not.toMatch(terserPattern)
expect(findAssetFile(/immutable-chunk-legacy/)).toMatch(terserPattern)
expect(findAssetFile(/immutable-chunk\./)).not.toMatch(terserPattern)
expect(findAssetFile(/index-legacy/)).toMatch(terserPattern)
expect(findAssetFile(/index\./)).not.toMatch(terserPattern)
expect(findAssetFile(/polyfills-legacy/)).toMatch(terserPattern)
})

test('should emit css file', async () => {
Expand Down
11 changes: 5 additions & 6 deletions playground/legacy/__tests__/ssr/serve.ts
Expand Up @@ -6,7 +6,7 @@ import { ports } from '~utils'
export const port = ports['legacy/ssr']

export async function serve(root: string, _isProd: boolean) {
const { build } = require('vite')
const { build } = await import('vite')
await build({
root,
logLevel: 'silent',
Expand All @@ -17,14 +17,13 @@ export async function serve(root: string, _isProd: boolean) {
}
})

const express = require('express')
const { default: express } = await import('express')
const app = express()

app.use('/', async (_req, res) => {
const { render } = require(path.resolve(
root,
'./dist/server/entry-server.js'
))
const { render } = await import(
path.resolve(root, './dist/server/entry-server.js')
)
const html = await render()
res.status(200).set({ 'Content-Type': 'text/html' }).end(html)
})
Expand Down
4 changes: 2 additions & 2 deletions playground/lib/__tests__/serve.ts
Expand Up @@ -12,7 +12,7 @@ export async function serve(root, isBuildTest) {
setupConsoleWarnCollector()

if (!isBuildTest) {
const { createServer } = require('vite')
const { createServer } = await import('vite')
process.env.VITE_INLINE = 'inline-serve'
const viteServer = await (
await createServer({
Expand Down Expand Up @@ -40,7 +40,7 @@ export async function serve(root, isBuildTest) {

return viteServer
} else {
const { build } = require('vite')
const { build } = await import('vite')
await build({
root,
logLevel: 'silent',
Expand Down
2 changes: 1 addition & 1 deletion playground/ssr-react/__tests__/serve.ts
Expand Up @@ -10,7 +10,7 @@ export const port = ports['ssr-react']
export async function serve(root: string, isProd: boolean) {
if (isProd) {
// build first
const { build } = require('vite')
const { build } = await import('vite')
// client build
await build({
root,
Expand Down
2 changes: 1 addition & 1 deletion playground/ssr-vue/__tests__/serve.ts
Expand Up @@ -10,7 +10,7 @@ export const port = ports['ssr-vue']
export async function serve(root, isProd) {
if (isProd) {
// build first
const { build } = require('vite')
const { build } = await import('vite')
// client build
await build({
root,
Expand Down
2 changes: 1 addition & 1 deletion playground/ssr-webworker/__tests__/serve.ts
Expand Up @@ -12,7 +12,7 @@ export async function serve(root: string, isProd: boolean) {

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

// worker build
await build({
Expand Down
2 changes: 1 addition & 1 deletion playground/vitestSetup.ts
Expand Up @@ -67,7 +67,7 @@ beforeAll(async (s) => {
browser = await chromium.connect(wsEndpoint)
page = await browser.newPage()

const globalConsole = globalThis.console
const globalConsole = global.console
const warn = globalConsole.warn
globalConsole.warn = (msg, ...args) => {
// suppress @vue/reactivity-transform warning
Expand Down
5 changes: 3 additions & 2 deletions playground/vue/CustomBlockPlugin.ts
Expand Up @@ -2,12 +2,13 @@ import type { Plugin } from 'vite'

export const vueI18nPlugin: Plugin = {
name: 'vue-i18n',
transform(code, id) {
async transform(code, id) {
if (!/vue&type=i18n/.test(id)) {
return
}
if (/\.ya?ml$/.test(id)) {
code = JSON.stringify(require('js-yaml').load(code.trim()))
const { load } = await import('js-yaml')
code = JSON.stringify(load(code.trim()))
}
return {
code: `export default Comp => {
Expand Down
2 changes: 2 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 8 additions & 5 deletions scripts/releaseUtils.ts
@@ -1,15 +1,17 @@
/**
* modified from https://github.com/vuejs/core/blob/master/scripts/release.js
*/
import { existsSync, readFileSync, readdirSync, writeFileSync } from 'fs'
import { existsSync, readdirSync, writeFileSync } from 'fs'
import path from 'path'
import colors from 'picocolors'
import type { Options as ExecaOptions } from 'execa'
import execa from 'execa'
import type { ReleaseType } from 'semver'
import semver from 'semver'
import fs from 'fs-extra'
import minimist from 'minimist'

export const args = require('minimist')(process.argv.slice(2))
export const args = minimist(process.argv.slice(2))

export const isDryRun = !!args.dry

Expand Down Expand Up @@ -136,7 +138,7 @@ export function getVersionChoices(currentVersion: string) {
}

export function updateVersion(pkgPath: string, version: string): void {
const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'))
const pkg = fs.readJSONSync(pkgPath)
pkg.version = version
writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n')
}
Expand Down Expand Up @@ -195,7 +197,8 @@ export async function logRecentCommits(pkgName: string) {
}

export async function updateTemplateVersions() {
const viteVersion = require('../packages/vite/package.json').version
const viteVersion = (await fs.readJSON('../packages/vite/package.json'))
.version
if (/beta|alpha|rc/.test(viteVersion)) return

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

0 comments on commit 67ff257

Please sign in to comment.