Sfoglia il codice sorgente

refactor: replace fs methods with destructured imports and improve type annotations

daiwei 4 mesi fa
parent
commit
c90bc48e66

+ 1 - 0
rollup.config.js

@@ -190,6 +190,7 @@ function createConfig(format, output, plugins = []) {
     // Global and Browser ESM builds inlines everything so that they can be
     // Global and Browser ESM builds inlines everything so that they can be
     // used alone.
     // used alone.
     external: resolveExternal(),
     external: resolveExternal(),
+    // @ts-expect-error
     plugins: [
     plugins: [
       ...trimVaporExportsPlugin(format, pkg.name),
       ...trimVaporExportsPlugin(format, pkg.name),
       json({
       json({

+ 56 - 22
scripts/build-with-rollup.js

@@ -5,20 +5,22 @@ Produces production builds and stitches together d.ts files.
 
 
 To specify the package to build, simply pass its name and the desired build
 To specify the package to build, simply pass its name and the desired build
 formats to output (defaults to `buildOptions.formats` specified in that package,
 formats to output (defaults to `buildOptions.formats` specified in that package,
-or "esm,cjs"):
+or ["esm-bundler", "cjs"]):
 
 
 ```
 ```
 # name supports fuzzy match. will build all packages with name containing "dom":
 # name supports fuzzy match. will build all packages with name containing "dom":
 nr build dom
 nr build dom
 
 
 # specify the format to output
 # specify the format to output
-nr build core --formats cjs
+nr build vue -f cjs
+
+# to specify multiple formats, separate with "+":
+nr build vue -f esm-bundler+esm-browser
 ```
 ```
 */
 */
 
 
 import fs from 'node:fs'
 import fs from 'node:fs'
 import { parseArgs } from 'node:util'
 import { parseArgs } from 'node:util'
-import { existsSync, readFileSync } from 'node:fs'
 import path from 'node:path'
 import path from 'node:path'
 import { brotliCompressSync, gzipSync } from 'node:zlib'
 import { brotliCompressSync, gzipSync } from 'node:zlib'
 import pico from 'picocolors'
 import pico from 'picocolors'
@@ -163,34 +165,63 @@ async function build(target) {
     ? `packages-private`
     ? `packages-private`
     : `packages`
     : `packages`
   const pkgDir = path.resolve(`${pkgBase}/${target}`)
   const pkgDir = path.resolve(`${pkgBase}/${target}`)
-  const pkg = JSON.parse(readFileSync(`${pkgDir}/package.json`, 'utf-8'))
+  const pkg = JSON.parse(fs.readFileSync(`${pkgDir}/package.json`, 'utf-8'))
 
 
   // if this is a full build (no specific targets), ignore private packages
   // if this is a full build (no specific targets), ignore private packages
   if ((isRelease || !targets.length) && pkg.private) {
   if ((isRelease || !targets.length) && pkg.private) {
     return
     return
   }
   }
 
 
+  /**
+   * @type {string[]}
+   */
+  let resolvedFormats
+  if (formats) {
+    const isNegation = formats.startsWith('~')
+    resolvedFormats = (isNegation ? formats.slice(1) : formats).split('+')
+    const pkgFormats = pkg.buildOptions?.formats
+    if (pkgFormats) {
+      if (isNegation) {
+        resolvedFormats = pkgFormats.filter(
+          (/** @type {string} */ f) => !resolvedFormats.includes(f),
+        )
+      } else {
+        resolvedFormats = resolvedFormats.filter(f => pkgFormats.includes(f))
+      }
+    }
+    if (!resolvedFormats.length) {
+      return
+    }
+  }
+
   // if building a specific format, do not remove dist.
   // if building a specific format, do not remove dist.
-  if (!formats && existsSync(`${pkgDir}/dist`)) {
+  if (!formats && fs.existsSync(`${pkgDir}/dist`)) {
     fs.rmSync(`${pkgDir}/dist`, { recursive: true })
     fs.rmSync(`${pkgDir}/dist`, { recursive: true })
   }
   }
 
 
-  const env = {
-    ...process.env,
-    TARGET: target,
-    COMMIT: commit,
-    NODE_ENV:
-      (pkg.buildOptions && pkg.buildOptions.env) ||
-      (devOnly ? 'development' : 'production'),
-    ...(formats ? { FORMATS: formats } : null),
-    ...(prodOnly ? { PROD_ONLY: true } : null),
-    ...(sourceMap ? { SOURCE_MAP: true } : null),
-  }
+  const env =
+    (pkg.buildOptions && pkg.buildOptions.env) ||
+    (devOnly ? 'development' : 'production')
 
 
-  await exec('rollup', ['-c'], {
-    stdio: 'inherit',
-    env,
-  })
+  await exec(
+    'rollup',
+    [
+      '-c',
+      '--environment',
+      [
+        `COMMIT:${commit}`,
+        `NODE_ENV:${env}`,
+        `TARGET:${target}`,
+        // @ts-expect-error
+        resolvedFormats ? `FORMATS:${resolvedFormats.join('+')}` : ``,
+        prodOnly ? `PROD_ONLY:true` : ``,
+        sourceMap ? `SOURCE_MAP:true` : ``,
+      ]
+        .filter(Boolean)
+        .join(','),
+    ],
+    { stdio: 'inherit' },
+  )
 }
 }
 
 
 /**
 /**
@@ -199,7 +230,10 @@ async function build(target) {
  * @returns {Promise<void>}
  * @returns {Promise<void>}
  */
  */
 async function checkAllSizes(targets) {
 async function checkAllSizes(targets) {
-  if (devOnly || (formats && !formats.includes('global'))) {
+  if (
+    devOnly ||
+    (formats && (formats.startsWith('~') || !formats.includes('global')))
+  ) {
     return
     return
   }
   }
   console.log()
   console.log()
@@ -228,7 +262,7 @@ async function checkSize(target) {
  * @returns {Promise<void>}
  * @returns {Promise<void>}
  */
  */
 async function checkFileSize(filePath) {
 async function checkFileSize(filePath) {
-  if (!existsSync(filePath)) {
+  if (!fs.existsSync(filePath)) {
     return
     return
   }
   }
   const file = fs.readFileSync(filePath)
   const file = fs.readFileSync(filePath)

+ 33 - 29
scripts/build.js

@@ -20,7 +20,14 @@ nr build vue -f esm-bundler+esm-browser
 */
 */
 
 
 import { rolldown } from 'rolldown'
 import { rolldown } from 'rolldown'
-import fs from 'node:fs'
+import {
+  existsSync,
+  mkdirSync,
+  readFileSync,
+  readdirSync,
+  rmSync,
+  writeFileSync,
+} from 'node:fs'
 import { parseArgs } from 'node:util'
 import { parseArgs } from 'node:util'
 import path from 'node:path'
 import path from 'node:path'
 import { brotliCompressSync, gzipSync } from 'node:zlib'
 import { brotliCompressSync, gzipSync } from 'node:zlib'
@@ -33,7 +40,7 @@ import { scanEnums } from './inline-enums.js'
 import { fileURLToPath } from 'node:url'
 import { fileURLToPath } from 'node:url'
 
 
 const __dirname = fileURLToPath(new URL('.', import.meta.url))
 const __dirname = fileURLToPath(new URL('.', import.meta.url))
-const privatePackages = fs.readdirSync('packages-private')
+const privatePackages = readdirSync('packages-private')
 const commit = spawnSync('git', ['rev-parse', '--short=7', 'HEAD'])
 const commit = spawnSync('git', ['rev-parse', '--short=7', 'HEAD'])
   .stdout.toString()
   .stdout.toString()
   .trim()
   .trim()
@@ -91,7 +98,7 @@ const sizeDir = path.resolve('temp/size')
 run()
 run()
 
 
 async function run() {
 async function run() {
-  if (size) fs.mkdirSync(sizeDir, { recursive: true })
+  if (size) mkdirSync(sizeDir, { recursive: true })
   const removeCache = scanEnums()
   const removeCache = scanEnums()
   try {
   try {
     const resolvedTargets = targets.length
     const resolvedTargets = targets.length
@@ -132,7 +139,7 @@ async function buildAll(targets) {
           }),
           }),
         ).then(files => {
         ).then(files => {
           const from = process.cwd()
           const from = process.cwd()
-          files.forEach(f => {
+          files.forEach((/** @type {string} */ f) => {
             count++
             count++
             console.log(
             console.log(
               pico.gray('built: ') + pico.green(path.relative(from, f)),
               pico.gray('built: ') + pico.green(path.relative(from, f)),
@@ -165,26 +172,26 @@ function createConfigsForTarget(target) {
     return
     return
   }
   }
 
 
-  let resolvedFormats
-  if (formats) {
-    const isNegation = formats.startsWith('~')
-    resolvedFormats = (isNegation ? formats.slice(1) : formats).split('+')
-    const pkgFormats = pkg.buildOptions?.formats
-    if (pkgFormats) {
-      if (isNegation) {
-        resolvedFormats = pkgFormats.filter(f => !resolvedFormats.includes(f))
-      } else {
-        resolvedFormats = resolvedFormats.filter(f => pkgFormats.includes(f))
-      }
-    }
-    if (!resolvedFormats.length) {
-      return
-    }
-  }
+  // let resolvedFormats
+  // if (formats) {
+  //   const isNegation = formats.startsWith('~')
+  //   resolvedFormats = (isNegation ? formats.slice(1) : formats).split('+')
+  //   const pkgFormats = pkg.buildOptions?.formats
+  //   if (pkgFormats) {
+  //     if (isNegation) {
+  //       resolvedFormats = pkgFormats.filter(f => !resolvedFormats.includes(f))
+  //     } else {
+  //       resolvedFormats = resolvedFormats.filter(f => pkgFormats.includes(f))
+  //     }
+  //   }
+  //   if (!resolvedFormats.length) {
+  //     return
+  //   }
+  // }
 
 
   // if building a specific format, do not remove dist.
   // if building a specific format, do not remove dist.
-  if (!formats && fs.existsSync(`${pkgDir}/dist`)) {
-    fs.rmSync(`${pkgDir}/dist`, { recursive: true })
+  if (!formats && existsSync(`${pkgDir}/dist`)) {
+    rmSync(`${pkgDir}/dist`, { recursive: true })
   }
   }
 
 
   return createConfigsForPackage({
   return createConfigsForPackage({
@@ -205,10 +212,7 @@ function createConfigsForTarget(target) {
  * @returns {Promise<void>}
  * @returns {Promise<void>}
  */
  */
 async function checkAllSizes(targets) {
 async function checkAllSizes(targets) {
-  if (
-    devOnly ||
-    (formats && (formats.startsWith('~') || !formats.includes('global')))
-  ) {
+  if (devOnly || (formats && !formats.includes('global'))) {
     return
     return
   }
   }
   console.log()
   console.log()
@@ -237,10 +241,10 @@ async function checkSize(target) {
  * @returns {Promise<void>}
  * @returns {Promise<void>}
  */
  */
 async function checkFileSize(filePath) {
 async function checkFileSize(filePath) {
-  if (!fs.existsSync(filePath)) {
+  if (!existsSync(filePath)) {
     return
     return
   }
   }
-  const file = fs.readFileSync(filePath)
+  const file = readFileSync(filePath)
   const fileName = path.basename(filePath)
   const fileName = path.basename(filePath)
 
 
   const gzipped = gzipSync(file)
   const gzipped = gzipSync(file)
@@ -255,7 +259,7 @@ async function checkFileSize(filePath) {
   )
   )
 
 
   if (size)
   if (size)
-    fs.writeFileSync(
+    writeFileSync(
       path.resolve(sizeDir, `${fileName}.json`),
       path.resolve(sizeDir, `${fileName}.json`),
       JSON.stringify({
       JSON.stringify({
         file: fileName,
         file: fileName,

+ 2 - 2
scripts/create-rolldown-config.js

@@ -88,11 +88,11 @@ export function createConfigsForPackage({
     },
     },
   }
   }
 
 
+  /** @type {PackageFormat[]} */
   const resolvedFormats = (
   const resolvedFormats = (
     formats ||
     formats ||
-    /** @type {PackageFormat[]} */
     packageOptions.formats || ['esm-bundler', 'cjs']
     packageOptions.formats || ['esm-bundler', 'cjs']
-  ).filter(format => outputConfigs[format])
+  ).filter((/** @type {PackageFormat} */ format) => outputConfigs[format])
 
 
   const packageConfigs = prodOnly
   const packageConfigs = prodOnly
     ? []
     ? []

+ 2 - 0
scripts/dev.js

@@ -44,9 +44,11 @@ const [config, prodConfig] = createConfigsForPackage({
 
 
 const configToUse = prod ? prodConfig : config
 const configToUse = prod ? prodConfig : config
 
 
+// @ts-expect-error
 console.log(`watching: ${configToUse.output.file}`)
 console.log(`watching: ${configToUse.output.file}`)
 watch(configToUse).on('event', event => {
 watch(configToUse).on('event', event => {
   if (event.code === 'BUNDLE_END') {
   if (event.code === 'BUNDLE_END') {
+    // @ts-expect-error
     console.log(`rebuilt ${config.output.file} in ${event.duration}ms`)
     console.log(`rebuilt ${config.output.file} in ${event.duration}ms`)
   }
   }
 })
 })

+ 1 - 1
scripts/size-report.js

@@ -41,7 +41,7 @@ async function run() {
  * Renders file sizes and diffs between current and previous versions
  * Renders file sizes and diffs between current and previous versions
  */
  */
 async function renderFiles() {
 async function renderFiles() {
-  const filterFiles = files =>
+  const filterFiles = (/** @type {string[]} */ files) =>
     files.filter(file => file[0] !== '_' && !file.endsWith('.txt'))
     files.filter(file => file[0] !== '_' && !file.endsWith('.txt'))
 
 
   const curr = filterFiles(await readdir(currDir))
   const curr = filterFiles(await readdir(currDir))

+ 5 - 1
scripts/usage-size.js

@@ -97,7 +97,11 @@ async function main() {
  */
  */
 async function generateBundle(preset) {
 async function generateBundle(preset) {
   const id = 'virtual:entry'
   const id = 'virtual:entry'
-  const content = `export { ${preset.imports.join(', ')} } from '${vuePath}'`
+  const exportSpecifiers =
+    preset.imports === '*'
+      ? `* as ${preset.name}`
+      : `{ ${preset.imports.join(', ')} }`
+  const content = `export ${exportSpecifiers} from '${vuePath}'`
 
 
   const result = await rolldown({
   const result = await rolldown({
     input: id,
     input: id,