From 7e9651014be8b8799ce688111448fb98a68729ba Mon Sep 17 00:00:00 2001 From: neverland Date: Wed, 26 Jun 2024 21:01:02 +0800 Subject: [PATCH] refactor: enable TypeScript isolatedDeclarations (#2709) --- packages/compat/babel-preset/src/node.ts | 4 +- .../src/pluginLockCorejsVersion.ts | 4 +- packages/compat/babel-preset/src/web.ts | 4 +- packages/compat/babel-preset/tsconfig.json | 3 +- packages/compat/plugin-swc/src/constants.ts | 8 +-- packages/compat/plugin-swc/src/loader.ts | 7 ++- packages/compat/plugin-swc/src/utils.ts | 4 +- packages/compat/plugin-swc/tsconfig.json | 3 +- packages/compat/webpack/src/webpackConfig.ts | 2 +- packages/core/src/cli/commands.ts | 2 +- packages/core/src/cli/init.ts | 3 +- packages/core/src/cli/prepare.ts | 2 +- packages/core/src/client/hmr.ts | 2 +- packages/core/src/config.ts | 8 +-- packages/core/src/configChain.ts | 4 +- packages/core/src/constants.ts | 36 +++++++---- packages/core/src/createContext.ts | 6 +- packages/core/src/helpers.ts | 63 ++++++++++++------- packages/core/src/helpers/path.ts | 4 +- packages/core/src/index.ts | 2 +- packages/core/src/initHooks.ts | 21 ++++++- packages/core/src/initPlugins.ts | 4 +- packages/core/src/loader/ignoreCssLoader.ts | 2 +- packages/core/src/loader/transformLoader.ts | 2 +- packages/core/src/logger.ts | 2 +- packages/core/src/pluginHelper.ts | 6 +- packages/core/src/pluginManager.ts | 2 +- packages/core/src/plugins/css.ts | 6 +- packages/core/src/plugins/fileSize.ts | 2 +- packages/core/src/plugins/html.ts | 16 ++--- packages/core/src/plugins/moduleFederation.ts | 2 +- packages/core/src/plugins/open.ts | 4 +- packages/core/src/plugins/rspackProfile.ts | 5 +- packages/core/src/plugins/splitChunks.ts | 6 +- packages/core/src/plugins/sri.ts | 2 +- packages/core/src/plugins/swc.ts | 2 +- packages/core/src/provider/build.ts | 2 +- packages/core/src/provider/inspectConfig.ts | 4 +- packages/core/src/rspack/HtmlAppIconPlugin.ts | 2 +- packages/core/src/rspack/HtmlBasicPlugin.ts | 6 +- .../core/src/rspack/InlineChunkHtmlPlugin.ts | 12 ++-- .../core/src/server/compilerDevMiddleware.ts | 8 +-- packages/core/src/server/devMiddleware.ts | 6 +- packages/core/src/server/getDevMiddlewares.ts | 8 ++- packages/core/src/server/helper.ts | 11 +++- packages/core/src/server/httpServer.ts | 4 +- packages/core/src/server/prodServer.ts | 6 +- packages/core/src/server/proxy.ts | 9 ++- packages/core/src/server/restart.ts | 8 ++- packages/core/src/server/socketServer.ts | 12 ++-- packages/core/src/server/watchFiles.ts | 7 ++- packages/core/tests/config.test.ts | 6 +- packages/core/tests/external.test.ts | 2 +- packages/core/tsconfig.json | 1 + .../src/AssetsRetryPlugin.ts | 4 +- .../src/AsyncChunkRetryPlugin.ts | 4 +- packages/plugin-assets-retry/tsconfig.json | 3 +- packages/plugin-babel/src/helper.ts | 6 +- packages/plugin-babel/tsconfig.json | 3 +- packages/plugin-basic-ssl/src/util.ts | 15 ++++- packages/plugin-basic-ssl/tsconfig.json | 3 +- .../src/CheckSyntaxPlugin.ts | 2 +- .../src/helpers/generateError.ts | 2 +- .../src/helpers/generateHtmlScripts.ts | 4 +- .../src/helpers/printErrors.ts | 2 +- .../plugin-check-syntax/src/helpers/utils.ts | 2 +- packages/plugin-check-syntax/tsconfig.json | 3 +- packages/plugin-css-minimizer/src/index.ts | 2 +- packages/plugin-css-minimizer/tsconfig.json | 3 +- packages/plugin-eslint/tsconfig.json | 3 +- .../plugin-image-compress/src/minimizer.ts | 4 +- packages/plugin-image-compress/tsconfig.json | 3 +- packages/plugin-less/tsconfig.json | 3 +- packages/plugin-lightningcss/src/minimizer.ts | 2 +- packages/plugin-lightningcss/tsconfig.json | 3 +- packages/plugin-mdx/tsconfig.json | 3 +- .../src/ProtocolImportsPlugin.ts | 2 +- packages/plugin-node-polyfill/src/libs.ts | 56 ++++++++--------- packages/plugin-node-polyfill/tsconfig.json | 3 +- packages/plugin-preact/tsconfig.json | 3 +- packages/plugin-pug/tsconfig.json | 3 +- packages/plugin-react/src/react.ts | 4 +- packages/plugin-react/src/splitChunks.ts | 2 +- packages/plugin-react/tsconfig.json | 3 +- .../src/AutoSetRootFontSizePlugin.ts | 6 +- packages/plugin-rem/tsconfig.json | 3 +- packages/plugin-sass/src/helpers.ts | 6 +- packages/plugin-sass/tsconfig.json | 3 +- packages/plugin-solid/tsconfig.json | 3 +- .../src/common/getProjects.ts | 2 +- .../plugin-source-build/src/common/pnpm.ts | 13 ++-- .../plugin-source-build/src/common/rush.ts | 2 +- packages/plugin-source-build/src/plugin.ts | 2 +- .../src/project-utils/filter.ts | 2 +- .../src/project-utils/getDependentProjects.ts | 3 +- .../src/{project => }/project.ts | 15 +++-- .../plugin-source-build/src/project/index.ts | 1 - packages/plugin-source-build/src/utils.ts | 10 ++- packages/plugin-source-build/tsconfig.json | 3 +- .../plugin-styled-components/tsconfig.json | 3 +- packages/plugin-stylus/tsconfig.json | 3 +- packages/plugin-svelte/tsconfig.json | 3 +- packages/plugin-svgr/src/index.ts | 2 +- packages/plugin-svgr/tsconfig.json | 3 +- packages/plugin-toml/tsconfig.json | 3 +- packages/plugin-type-check/tsconfig.json | 3 +- .../plugin-typed-css-modules/src/loader.ts | 21 +++++-- .../plugin-typed-css-modules/tsconfig.json | 3 +- packages/plugin-umd/tsconfig.json | 3 +- packages/plugin-vue-jsx/tsconfig.json | 3 +- packages/plugin-vue/tsconfig.json | 3 +- packages/plugin-vue2-jsx/tsconfig.json | 3 +- .../src/VueLoader15PitchFixPlugin.ts | 2 +- packages/plugin-vue2/src/splitChunks.ts | 2 +- packages/plugin-vue2/tsconfig.json | 3 +- packages/plugin-yaml/tsconfig.json | 3 +- packages/shared/src/index.ts | 14 ++--- packages/shared/tsconfig.json | 3 +- 118 files changed, 412 insertions(+), 269 deletions(-) rename packages/plugin-source-build/src/{project => }/project.ts (92%) delete mode 100644 packages/plugin-source-build/src/project/index.ts diff --git a/packages/compat/babel-preset/src/node.ts b/packages/compat/babel-preset/src/node.ts index 0b5fe5675f..8f4463be90 100644 --- a/packages/compat/babel-preset/src/node.ts +++ b/packages/compat/babel-preset/src/node.ts @@ -1,7 +1,9 @@ import { generateBaseConfig } from './base'; import type { BabelConfig, NodePresetOptions } from './types'; -export const getBabelConfigForNode = (options: NodePresetOptions = {}) => { +export const getBabelConfigForNode = ( + options: NodePresetOptions = {}, +): BabelConfig => { if (options.presetEnv !== false) { options.presetEnv ??= {}; options.presetEnv.targets ??= ['node >= 16']; diff --git a/packages/compat/babel-preset/src/pluginLockCorejsVersion.ts b/packages/compat/babel-preset/src/pluginLockCorejsVersion.ts index 00faf77e24..64ee5e3040 100644 --- a/packages/compat/babel-preset/src/pluginLockCorejsVersion.ts +++ b/packages/compat/babel-preset/src/pluginLockCorejsVersion.ts @@ -14,7 +14,7 @@ const REWRITE_TARGETS: Record = { const matchedKey = (value: string) => Object.keys(REWRITE_TARGETS).find((name) => value.startsWith(`${name}/`)); -export const getCoreJsVersion = () => { +export const getCoreJsVersion = (): string => { try { const { version } = JSON.parse(readFileSync(CORE_JS_PKG_PATH, 'utf-8')); const [major, minor] = version.split('.'); @@ -26,7 +26,7 @@ export const getCoreJsVersion = () => { export default (_: any) => { return { - post({ path }: any) { + post({ path }: any): void { for (const node of path.node.body as t.Node[]) { // import if (t.isImportDeclaration(node)) { diff --git a/packages/compat/babel-preset/src/web.ts b/packages/compat/babel-preset/src/web.ts index 9a58f064ba..eac6c41e9d 100644 --- a/packages/compat/babel-preset/src/web.ts +++ b/packages/compat/babel-preset/src/web.ts @@ -23,7 +23,9 @@ const getDefaultPresetEnvOption = ( }; }; -export const getBabelConfigForWeb = (options: WebPresetOptions) => { +export const getBabelConfigForWeb = ( + options: WebPresetOptions, +): BabelConfig => { if (options.presetEnv !== false) { options.presetEnv = { ...getDefaultPresetEnvOption(options), diff --git a/packages/compat/babel-preset/tsconfig.json b/packages/compat/babel-preset/tsconfig.json index 0bee237ba7..3d3de0a796 100644 --- a/packages/compat/babel-preset/tsconfig.json +++ b/packages/compat/babel-preset/tsconfig.json @@ -4,7 +4,8 @@ "outDir": "./dist", "baseUrl": "./", "rootDir": "src", - "composite": true + "composite": true, + "isolatedDeclarations": true }, "references": [ { diff --git a/packages/compat/plugin-swc/src/constants.ts b/packages/compat/plugin-swc/src/constants.ts index 08834674d9..ec49d509eb 100644 --- a/packages/compat/plugin-swc/src/constants.ts +++ b/packages/compat/plugin-swc/src/constants.ts @@ -1,8 +1,8 @@ import path from 'node:path'; -export const CORE_JS_PKG_PATH = require.resolve('core-js/package.json'); -export const CORE_JS_DIR = path.dirname(CORE_JS_PKG_PATH); -export const SWC_HELPERS_DIR = path.dirname( +export const CORE_JS_PKG_PATH: string = require.resolve('core-js/package.json'); +export const CORE_JS_DIR: string = path.dirname(CORE_JS_PKG_PATH); +export const SWC_HELPERS_DIR: string = path.dirname( require.resolve('@swc/helpers/package.json'), ); -export const JS_REGEX = /\.js$/; +export const JS_REGEX: RegExp = /\.js$/; diff --git a/packages/compat/plugin-swc/src/loader.ts b/packages/compat/plugin-swc/src/loader.ts index 778eb7ca93..9c7a43afc5 100644 --- a/packages/compat/plugin-swc/src/loader.ts +++ b/packages/compat/plugin-swc/src/loader.ts @@ -79,4 +79,9 @@ export function createLoader(): LoaderDefinitionFunction { }; } -export default createLoader(); +const loader: LoaderDefinitionFunction< + Record, + Record +> = createLoader(); + +export default loader; diff --git a/packages/compat/plugin-swc/src/utils.ts b/packages/compat/plugin-swc/src/utils.ts index 747069d685..d2a1f28f2e 100644 --- a/packages/compat/plugin-swc/src/utils.ts +++ b/packages/compat/plugin-swc/src/utils.ts @@ -67,7 +67,7 @@ const isBeyondReact17 = async (cwd: string) => { export async function determinePresetReact( root: string, pluginConfig: ObjPluginSwcOptions, -) { +): Promise { pluginConfig.presetReact ??= {}; pluginConfig.presetReact.runtime ??= (await isBeyondReact17(root)) ? 'automatic' @@ -78,7 +78,7 @@ export function checkUseMinify( options: ObjPluginSwcOptions, config: NormalizedEnvironmentConfig, isProd: boolean, -) { +): boolean { return ( isProd && config.output.minify && diff --git a/packages/compat/plugin-swc/tsconfig.json b/packages/compat/plugin-swc/tsconfig.json index fcd10194a0..313ea8fbc8 100644 --- a/packages/compat/plugin-swc/tsconfig.json +++ b/packages/compat/plugin-swc/tsconfig.json @@ -4,7 +4,8 @@ "outDir": "./dist", "baseUrl": "./", "rootDir": "src", - "composite": true + "composite": true, + "isolatedDeclarations": true }, "references": [ { diff --git a/packages/compat/webpack/src/webpackConfig.ts b/packages/compat/webpack/src/webpackConfig.ts index 85c1312a75..82a8e64ddf 100644 --- a/packages/compat/webpack/src/webpackConfig.ts +++ b/packages/compat/webpack/src/webpackConfig.ts @@ -141,7 +141,7 @@ export async function generateWebpackConfig({ environment: string; target: RsbuildTarget; context: InternalContext; -}) { +}): Promise { const chainUtils = await getChainUtils(target, environment); const { default: webpack } = await import('webpack'); const { diff --git a/packages/core/src/cli/commands.ts b/packages/core/src/cli/commands.ts index 592ca85084..62aa233eea 100644 --- a/packages/core/src/cli/commands.ts +++ b/packages/core/src/cli/commands.ts @@ -46,7 +46,7 @@ const applyServerOptions = (command: Command) => { .option('--host ', 'specify the host that the server listens to'); }; -export function runCli() { +export function runCli(): void { program.name('rsbuild').usage(' [options]').version(RSBUILD_VERSION); const devCommand = program.command('dev'); diff --git a/packages/core/src/cli/init.ts b/packages/core/src/cli/init.ts index aadaa62279..cc9d770325 100644 --- a/packages/core/src/cli/init.ts +++ b/packages/core/src/cli/init.ts @@ -3,6 +3,7 @@ import { isDev } from '../helpers'; import { loadEnv } from '../loadEnv'; import { logger } from '../logger'; import { onBeforeRestartServer } from '../server/restart'; +import type { RsbuildInstance } from '../types'; import type { CommonOptions } from './commands'; let commonOpts: CommonOptions = {}; @@ -13,7 +14,7 @@ export async function init({ }: { cliOptions?: CommonOptions; isRestart?: boolean; -}) { +}): Promise { if (cliOptions) { commonOpts = cliOptions; } diff --git a/packages/core/src/cli/prepare.ts b/packages/core/src/cli/prepare.ts index 1f358d4e51..bbd6f8ad58 100644 --- a/packages/core/src/cli/prepare.ts +++ b/packages/core/src/cli/prepare.ts @@ -9,7 +9,7 @@ function initNodeEnv() { } } -export function prepareCli() { +export function prepareCli(): void { initNodeEnv(); // Print a blank line to keep the greet log nice. diff --git a/packages/core/src/client/hmr.ts b/packages/core/src/client/hmr.ts index 2def519ce0..f661f7b328 100644 --- a/packages/core/src/client/hmr.ts +++ b/packages/core/src/client/hmr.ts @@ -63,7 +63,7 @@ let clearOverlay: undefined | (() => void); export const registerOverlay = ( createFn: (err: string[]) => void, clearFn: () => void, -) => { +): void => { createOverlay = createFn; clearOverlay = clearFn; }; diff --git a/packages/core/src/config.ts b/packages/core/src/config.ts index de2984df11..840a66fc9b 100644 --- a/packages/core/src/config.ts +++ b/packages/core/src/config.ts @@ -203,7 +203,7 @@ export function getDefaultEntry(root: string): RsbuildEntry { export const withDefaultConfig = async ( rootPath: string, config: RsbuildConfig, -) => { +): Promise => { const merged = mergeRsbuildConfig(createDefaultConfig(), config); merged.source ||= {}; @@ -292,7 +292,7 @@ const resolveConfigPath = (root: string, customConfig?: string) => { return null; }; -export async function watchFiles(files: string[]) { +export async function watchFiles(files: string[]): Promise { if (!files.length) { return; } @@ -407,7 +407,7 @@ export async function outputInspectConfigFiles({ inspectOptions: InspectConfigOptions & { outputPath: string; }; -}) { +}): Promise { const { outputPath } = inspectOptions; const files = [ @@ -455,7 +455,7 @@ export async function outputInspectConfigFiles({ ); } -export async function stringifyConfig(config: unknown, verbose?: boolean) { +export function stringifyConfig(config: unknown, verbose?: boolean): string { // webpackChain.toString can be used as a common stringify method const stringify = RspackChain.toString as ( config: unknown, diff --git a/packages/core/src/configChain.ts b/packages/core/src/configChain.ts index 90c4aeae7d..ce7383a85c 100644 --- a/packages/core/src/configChain.ts +++ b/packages/core/src/configChain.ts @@ -13,7 +13,7 @@ import { isPlainObject } from './helpers'; import { logger } from './logger'; import type { RsbuildConfig } from './types'; -export async function getBundlerChain() { +export function getBundlerChain(): RspackChain { const bundlerChain = new RspackChain(); return bundlerChain as unknown as RspackChain; @@ -30,7 +30,7 @@ export async function modifyBundlerChain( ): Promise { logger.debug('modify bundler chain'); - const bundlerChain = await getBundlerChain(); + const bundlerChain = getBundlerChain(); const [modifiedBundlerChain] = await context.hooks.modifyBundlerChain.call( bundlerChain, diff --git a/packages/core/src/constants.ts b/packages/core/src/constants.ts index 74f0f6ad92..1b61026780 100644 --- a/packages/core/src/constants.ts +++ b/packages/core/src/constants.ts @@ -11,9 +11,9 @@ export const FONT_DIST_DIR = 'static/font'; export const WASM_DIST_DIR = 'static/wasm'; export const IMAGE_DIST_DIR = 'static/image'; export const MEDIA_DIST_DIR = 'static/media'; -export const LOADER_PATH = join(__dirname); -export const STATIC_PATH = join(__dirname, '../static'); -export const COMPILED_PATH = join(__dirname, '../compiled'); +export const LOADER_PATH: string = join(__dirname); +export const STATIC_PATH: string = join(__dirname, '../static'); +export const COMPILED_PATH: string = join(__dirname, '../compiled'); export const TS_CONFIG_FILE = 'tsconfig.json'; export const HMR_SOCKET_PATH = '/rsbuild-hmr'; @@ -23,29 +23,36 @@ export const DEFAULT_DATA_URL_SIZE = 4096; export const DEFAULT_MOUNT_ID = 'root'; export const DEFAULT_DEV_HOST = '0.0.0.0'; export const DEFAULT_ASSET_PREFIX = '/'; -export const DEFAULT_WEB_BROWSERSLIST = [ +export const DEFAULT_WEB_BROWSERSLIST: string[] = [ 'chrome >= 87', 'edge >= 88', 'firefox >= 78', 'safari >= 14', ]; -export const DEFAULT_BROWSERSLIST = { +export const DEFAULT_BROWSERSLIST: Record = { web: DEFAULT_WEB_BROWSERSLIST, 'web-worker': DEFAULT_WEB_BROWSERSLIST, node: ['node >= 16'], }; // RegExp -export const HTML_REGEX = /\.html$/; -export const CSS_REGEX = /\.css$/; +export const HTML_REGEX: RegExp = /\.html$/; +export const CSS_REGEX: RegExp = /\.css$/; // Plugins export const PLUGIN_SWC_NAME = 'rsbuild:swc'; export const PLUGIN_CSS_NAME = 'rsbuild:css'; // Extensions -export const FONT_EXTENSIONS = ['woff', 'woff2', 'eot', 'ttf', 'otf', 'ttc']; -export const IMAGE_EXTENSIONS = [ +export const FONT_EXTENSIONS: string[] = [ + 'woff', + 'woff2', + 'eot', + 'ttf', + 'otf', + 'ttc', +]; +export const IMAGE_EXTENSIONS: string[] = [ 'png', 'jpg', 'jpeg', @@ -61,5 +68,12 @@ export const IMAGE_EXTENSIONS = [ 'tiff', 'jfif', ]; -export const VIDEO_EXTENSIONS = ['mp4', 'webm', 'ogg', 'mov']; -export const AUDIO_EXTENSIONS = ['mp3', 'wav', 'flac', 'aac', 'm4a', 'opus']; +export const VIDEO_EXTENSIONS: string[] = ['mp4', 'webm', 'ogg', 'mov']; +export const AUDIO_EXTENSIONS: string[] = [ + 'mp3', + 'wav', + 'flac', + 'aac', + 'm4a', + 'opus', +]; diff --git a/packages/core/src/createContext.ts b/packages/core/src/createContext.ts index 92a4d0c186..9b61e232fa 100644 --- a/packages/core/src/createContext.ts +++ b/packages/core/src/createContext.ts @@ -61,7 +61,7 @@ async function createContextByConfig( // using cache to avoid multiple calls to loadConfig const browsersListCache = new Map(); -export async function getBrowserslist(path: string) { +export async function getBrowserslist(path: string): Promise { const env = process.env.NODE_ENV; const cacheKey = path + env; @@ -131,7 +131,7 @@ const getEnvironmentHTMLPaths = ( export async function updateEnvironmentContext( context: RsbuildContext, configs: Record, -) { +): Promise { context.environments ||= {}; for (const [name, config] of Object.entries(configs)) { @@ -158,7 +158,7 @@ export async function updateEnvironmentContext( } } -export function updateContextByNormalizedConfig(context: RsbuildContext) { +export function updateContextByNormalizedConfig(context: RsbuildContext): void { // Try to get the parent dist path from all environments const distPaths = Object.values(context.environments).map( (item) => item.distPath, diff --git a/packages/core/src/helpers.ts b/packages/core/src/helpers.ts index 435aba2037..50c8a034fe 100644 --- a/packages/core/src/helpers.ts +++ b/packages/core/src/helpers.ts @@ -26,7 +26,7 @@ import { logger } from './logger'; export const rspackMinVersion = '0.7.0'; export const getNodeEnv = () => process.env.NODE_ENV as NodeEnv; -export const setNodeEnv = (env: NodeEnv) => { +export const setNodeEnv = (env: NodeEnv): void => { process.env.NODE_ENV = env; }; export const isDev = (): boolean => getNodeEnv() === 'development'; @@ -63,7 +63,9 @@ const compareSemver = (version1: string, version2: string) => { return 0; }; -export const isSatisfyRspackVersion = async (originalVersion: string) => { +export const isSatisfyRspackVersion = async ( + originalVersion: string, +): Promise => { let version = originalVersion; // The nightly version of rspack is to append `-canary-abc` to the current version @@ -167,7 +169,9 @@ function formatErrorMessage(errors: string[]) { return `${title}\n${tip}\n${text}`; } -export const getAllStatsErrors = (statsData: StatsCompilation) => { +export const getAllStatsErrors = ( + statsData: StatsCompilation, +): Rspack.StatsError[] | undefined => { // stats error + childCompiler error // only append child errors when stats error does not exist, because some errors will exist in both stats and childCompiler if (statsData.errorsCount && statsData.errors?.length === 0) { @@ -180,7 +184,9 @@ export const getAllStatsErrors = (statsData: StatsCompilation) => { return statsData.errors; }; -export const getAllStatsWarnings = (statsData: StatsCompilation) => { +export const getAllStatsWarnings = ( + statsData: StatsCompilation, +): Rspack.StatsError[] | undefined => { if (statsData.warningsCount && statsData.warnings?.length === 0) { return statsData.children?.reduce( (warnings, curr) => warnings.concat(curr.warnings || []), @@ -208,7 +214,10 @@ export function getStatsOptions( export function formatStats( stats: Stats | MultiStats, options: StatsValue = {}, -) { +): { + message?: string; + level?: string; +} { const statsData = stats.toJson( typeof options === 'object' ? { @@ -252,7 +261,10 @@ export const removeTailingSlash = (s: string): string => s.replace(/\/+$/, ''); export const addTrailingSlash = (s: string): string => s.endsWith('/') ? s : `${s}/`; -export const formatPublicPath = (publicPath: string, withSlash = true) => { +export const formatPublicPath = ( + publicPath: string, + withSlash = true, +): string => { // 'auto' is a magic value in Rspack and we should not add trailing slash if (publicPath === 'auto') { return publicPath; @@ -266,7 +278,7 @@ export const formatPublicPath = (publicPath: string, withSlash = true) => { export const getPublicPathFromChain = ( chain: RspackChain, withSlash = true, -) => { +): string => { const publicPath = chain.output.get('publicPath'); if (typeof publicPath === 'string') { @@ -276,7 +288,9 @@ export const getPublicPathFromChain = ( return formatPublicPath(DEFAULT_ASSET_PREFIX, withSlash); }; -export const getPublicPathFromCompiler = (compiler: Rspack.Compiler) => { +export const getPublicPathFromCompiler = ( + compiler: Rspack.Compiler, +): string => { const { publicPath } = compiler.options.output; if (typeof publicPath === 'string') { @@ -291,7 +305,7 @@ export const getPublicPathFromCompiler = (compiler: Rspack.Compiler) => { return DEFAULT_ASSET_PREFIX; }; -export const isFileSync = (filePath: string) => { +export const isFileSync = (filePath: string): boolean | undefined => { try { return fs.statSync(filePath, { throwIfNoEntry: false })?.isFile(); } catch (_) { @@ -299,7 +313,7 @@ export const isFileSync = (filePath: string) => { } }; -export function isEmptyDir(path: string) { +export function isEmptyDir(path: string): boolean { const files = fs.readdirSync(path); return files.length === 0 || (files.length === 1 && files[0] === '.git'); } @@ -318,21 +332,21 @@ export const findExists = (files: string[]): string | false => { return false; }; -export async function pathExists(path: string) { +export async function pathExists(path: string): Promise { return fs.promises .access(path) .then(() => true) .catch(() => false); } -export async function isFileExists(file: string) { +export async function isFileExists(file: string): Promise { return fs.promises .access(file, fs.constants.F_OK) .then(() => true) .catch(() => false); } -export async function emptyDir(dir: string) { +export async function emptyDir(dir: string): Promise { if (!(await pathExists(dir))) { return; } @@ -357,7 +371,7 @@ const urlJoin = (base: string, path: string) => { }; // Can be replaced with URL.canParse when we drop support for Node.js 16 -export const canParse = (url: string) => { +export const canParse = (url: string): boolean => { try { new URL(url); return true; @@ -368,8 +382,8 @@ export const canParse = (url: string) => { export const ensureAssetPrefix = ( url: string, - assetPrefix = DEFAULT_ASSET_PREFIX, -) => { + assetPrefix: string = DEFAULT_ASSET_PREFIX, +): string => { // The use of an absolute URL without a protocol is technically legal, // however it cannot be parsed as a URL instance, just return it. // e.g. str is //example.com/foo.js @@ -465,7 +479,7 @@ export function partition( export const applyToCompiler = ( compiler: Rspack.Compiler | Rspack.MultiCompiler, apply: (c: Rspack.Compiler, index: number) => void, -) => { +): void => { if (isMultiCompiler(compiler)) { compiler.compilers.forEach(apply); } else { @@ -473,7 +487,7 @@ export const applyToCompiler = ( } }; -export const upperFirst = (str: string) => +export const upperFirst = (str: string): string => str ? str.charAt(0).toUpperCase() + str.slice(1) : ''; export function debounce void>( @@ -494,7 +508,7 @@ export function debounce void>( } // Determine if the string is a URL -export const isURL = (str: string) => +export const isURL = (str: string): boolean => str.startsWith('http') || str.startsWith('//:'); export const createVirtualModule = (content: string) => @@ -503,7 +517,7 @@ export const createVirtualModule = (content: string) => export const isRegExp = (obj: any): obj is RegExp => Object.prototype.toString.call(obj) === '[object RegExp]'; -export function isWebTarget(target: RsbuildTarget | RsbuildTarget[]) { +export function isWebTarget(target: RsbuildTarget | RsbuildTarget[]): boolean { const targets = castArray(target); return targets.includes('web') || target.includes('web-worker'); } @@ -521,7 +535,7 @@ export const onCompileDone = ( compiler: Rspack.Compiler | Rspack.MultiCompiler, onDone: (stats: Stats | MultiStats) => Promise, MultiStatsCtor: new (stats: Stats[]) => MultiStats, -) => { +): void => { // The MultiCompiler of Rspack does not supports `done.tapPromise`, // so we need to use the `done` hook of `MultiCompiler.compilers` to implement it. if (isMultiCompiler(compiler)) { @@ -559,7 +573,10 @@ export const onCompileDone = ( } }; -export function pick(obj: T, keys: ReadonlyArray) { +export function pick( + obj: T, + keys: ReadonlyArray, +): Pick { return keys.reduce( (ret, key) => { if (obj[key] !== undefined) { @@ -574,7 +591,7 @@ export function pick(obj: T, keys: ReadonlyArray) { export const camelCase = (input: string): string => input.replace(/[-_](\w)/g, (_, c) => c.toUpperCase()); -export const prettyTime = (seconds: number) => { +export const prettyTime = (seconds: number): string => { const format = (time: string) => color.bold(time); if (seconds < 10) { diff --git a/packages/core/src/helpers/path.ts b/packages/core/src/helpers/path.ts index 1fcaa8b250..712892d59d 100644 --- a/packages/core/src/helpers/path.ts +++ b/packages/core/src/helpers/path.ts @@ -1,7 +1,7 @@ import { isAbsolute, join, resolve, sep } from 'node:path'; import { COMPILED_PATH } from '../constants'; -export function getCommonParentPath(paths: string[]) { +export function getCommonParentPath(paths: string[]): string { const uniquePaths = [...new Set(paths)]; if (uniquePaths.length === 1) { @@ -22,7 +22,7 @@ export function getCommonParentPath(paths: string[]) { return common.join(sep); } -export const getCompiledPath = (packageName: string) => +export const getCompiledPath = (packageName: string): string => join(COMPILED_PATH, packageName); /** diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index bf44074372..88865efcac 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -12,7 +12,7 @@ export { createRsbuild } from './createRsbuild'; export { loadConfig, defineConfig } from './config'; // Rsbuild version -export const version = RSBUILD_VERSION; +export const version: string = RSBUILD_VERSION; // Rspack instance export { rspack }; diff --git a/packages/core/src/initHooks.ts b/packages/core/src/initHooks.ts index 23abfa8a06..582092572e 100644 --- a/packages/core/src/initHooks.ts +++ b/packages/core/src/initHooks.ts @@ -62,7 +62,26 @@ export function createAsyncHook< }; } -export function initHooks() { +export function initHooks(): { + onExit: AsyncHook; + onAfterBuild: AsyncHook; + onBeforeBuild: AsyncHook; + onDevCompileDone: AsyncHook; + onCloseDevServer: AsyncHook; + onAfterStartDevServer: AsyncHook; + onBeforeStartDevServer: AsyncHook; + onAfterStartProdServer: AsyncHook; + onBeforeStartProdServer: AsyncHook; + onAfterCreateCompiler: AsyncHook; + onBeforeCreateCompiler: AsyncHook; + modifyHTMLTags: AsyncHook; + modifyRspackConfig: AsyncHook; + modifyBundlerChain: AsyncHook; + modifyWebpackChain: AsyncHook; + modifyWebpackConfig: AsyncHook; + modifyRsbuildConfig: AsyncHook; + modifyEnvironmentConfig: AsyncHook; +} { return { onExit: createAsyncHook(), onAfterBuild: createAsyncHook(), diff --git a/packages/core/src/initPlugins.ts b/packages/core/src/initPlugins.ts index 72fdfbf86f..dbf208f4ce 100644 --- a/packages/core/src/initPlugins.ts +++ b/packages/core/src/initPlugins.ts @@ -17,7 +17,7 @@ import type { InternalContext, NormalizedConfig } from './types'; export function getHTMLPathByEntry( entryName: string, config: NormalizedEnvironmentConfig, -) { +): string { const filename = config.html.outputStructure === 'flat' ? `${entryName}.html` @@ -37,7 +37,7 @@ function applyTransformPlugin( } class RsbuildTransformPlugin { - apply(compiler: Compiler) { + apply(compiler: Compiler): void { compiler.__rsbuildTransformer = transformer; compiler.hooks.thisCompilation.tap(name, (compilation) => { diff --git a/packages/core/src/loader/ignoreCssLoader.ts b/packages/core/src/loader/ignoreCssLoader.ts index 1dbe7cc587..8b054fcefc 100644 --- a/packages/core/src/loader/ignoreCssLoader.ts +++ b/packages/core/src/loader/ignoreCssLoader.ts @@ -1,6 +1,6 @@ import type { LoaderContext } from '@rspack/core'; -export default function (this: LoaderContext, source: string) { +export default function (this: LoaderContext, source: string): string { this?.cacheable(true); // if the source code include '___CSS_LOADER_EXPORT___' diff --git a/packages/core/src/loader/transformLoader.ts b/packages/core/src/loader/transformLoader.ts index 90270f2fef..2f2ea02ea2 100644 --- a/packages/core/src/loader/transformLoader.ts +++ b/packages/core/src/loader/transformLoader.ts @@ -5,7 +5,7 @@ export default async function transform( this: LoaderContext<{ id: string }>, source: string, map?: string | RspackSourceMap, -) { +): Promise { const callback = this.async(); const bypass = () => callback(null, source, map); diff --git a/packages/core/src/logger.ts b/packages/core/src/logger.ts index 23535b0c19..8b168c2627 100644 --- a/packages/core/src/logger.ts +++ b/packages/core/src/logger.ts @@ -1,7 +1,7 @@ import { color } from '@rsbuild/shared'; import { type Logger, logger } from 'rslog'; -export const isDebug = () => { +export const isDebug = (): boolean => { if (!process.env.DEBUG) { return false; } diff --git a/packages/core/src/pluginHelper.ts b/packages/core/src/pluginHelper.ts index 66cd47ca59..05ef862089 100644 --- a/packages/core/src/pluginHelper.ts +++ b/packages/core/src/pluginHelper.ts @@ -9,7 +9,7 @@ let htmlPlugin: typeof HtmlWebpackPlugin; /** * This method is used to override the Rsbuild default html-plugin (html-rspack-plugin). */ -export const setHTMLPlugin = (plugin: typeof HtmlWebpackPlugin) => { +export const setHTMLPlugin = (plugin: typeof HtmlWebpackPlugin): void => { if (plugin) { htmlPlugin = plugin; } @@ -24,11 +24,11 @@ export const getHTMLPlugin = (): typeof HtmlWebpackPlugin => { let cssExtractPlugin: unknown; -export const setCssExtractPlugin = (plugin: unknown) => { +export const setCssExtractPlugin = (plugin: unknown): void => { cssExtractPlugin = plugin; }; -export const getCssExtractPlugin = () => { +export const getCssExtractPlugin = (): typeof rspack.CssExtractRspackPlugin => { if (cssExtractPlugin) { return cssExtractPlugin as typeof rspack.CssExtractRspackPlugin; } diff --git a/packages/core/src/pluginManager.ts b/packages/core/src/pluginManager.ts index 56b16d6437..a41f8afeb0 100644 --- a/packages/core/src/pluginManager.ts +++ b/packages/core/src/pluginManager.ts @@ -174,7 +174,7 @@ export async function initPlugins({ }: { pluginAPI?: RsbuildPluginAPI; pluginManager: PluginManager; -}) { +}): Promise { logger.debug('init plugins'); const plugins = pluginDagSort(pluginManager.getPlugins()); diff --git a/packages/core/src/plugins/css.ts b/packages/core/src/plugins/css.ts index 63683a1e35..c603377361 100644 --- a/packages/core/src/plugins/css.ts +++ b/packages/core/src/plugins/css.ts @@ -22,7 +22,7 @@ import type { NormalizedEnvironmentConfig, RsbuildPlugin } from '../types'; export const isUseCssExtract = ( config: NormalizedEnvironmentConfig, target: RsbuildTarget, -) => +): boolean => !config.output.injectStyles && target !== 'node' && target !== 'web-worker'; const getCSSModulesLocalIdentName = ( @@ -42,7 +42,7 @@ const getCSSModulesLocalIdentName = ( export const normalizeCssLoaderOptions = ( options: CSSLoaderOptions, exportOnlyLocals: boolean, -) => { +): CSSLoaderOptions => { if (options.modules && exportOnlyLocals) { let { modules } = options; if (modules === true) { @@ -108,7 +108,7 @@ export const applyAutoprefixer = async ( plugins: unknown[], browserslist: string[], config: NormalizedEnvironmentConfig, -) => { +): Promise => { const pluginObjects: AcceptedPlugin[] = plugins.map((plugin) => isFunction(plugin) ? plugin({}) : plugin, ); diff --git a/packages/core/src/plugins/fileSize.ts b/packages/core/src/plugins/fileSize.ts index 57faf2d8af..b0e3e228f0 100644 --- a/packages/core/src/plugins/fileSize.ts +++ b/packages/core/src/plugins/fileSize.ts @@ -12,7 +12,7 @@ import { logger } from '../logger'; import type { RsbuildPlugin } from '../types'; /** Filter source map and license files */ -export const filterAsset = (asset: string) => +export const filterAsset = (asset: string): boolean => !/\.map$/.test(asset) && !/\.LICENSE\.txt$/.test(asset); const getAssetColor = (size: number) => { diff --git a/packages/core/src/plugins/html.ts b/packages/core/src/plugins/html.ts index 00831b279a..8404f6e2bf 100644 --- a/packages/core/src/plugins/html.ts +++ b/packages/core/src/plugins/html.ts @@ -71,7 +71,7 @@ function getTerserMinifyOptions(config: NormalizedEnvironmentConfig) { return finalOptions; } -export async function getHtmlMinifyOptions( +async function getHtmlMinifyOptions( isProd: boolean, config: NormalizedEnvironmentConfig, ) { @@ -105,10 +105,7 @@ export async function getHtmlMinifyOptions( : htmlMinifyDefaultOptions; } -export function getTitle( - entryName: string, - config: NormalizedEnvironmentConfig, -) { +function getTitle(entryName: string, config: NormalizedEnvironmentConfig) { return reduceConfigsMergeContext({ initial: '', config: config.html.title, @@ -116,10 +113,7 @@ export function getTitle( }); } -export function getInject( - entryName: string, - config: NormalizedEnvironmentConfig, -) { +function getInject(entryName: string, config: NormalizedEnvironmentConfig) { return reduceConfigsMergeContext({ initial: 'head', config: config.html.inject, @@ -172,7 +166,7 @@ export async function getTemplate( }; } -export function getFavicon( +function getFavicon( entryName: string, config: { html: HtmlConfig; @@ -185,7 +179,7 @@ export function getFavicon( }); } -export function getMetaTags( +function getMetaTags( entryName: string, config: { html: HtmlConfig }, templateContent?: string, diff --git a/packages/core/src/plugins/moduleFederation.ts b/packages/core/src/plugins/moduleFederation.ts index 4fbcf0d193..cbb1112a20 100644 --- a/packages/core/src/plugins/moduleFederation.ts +++ b/packages/core/src/plugins/moduleFederation.ts @@ -16,7 +16,7 @@ class PatchSplitChunksPlugin implements RspackPluginInstance { this.name = name; } - apply(compiler: Rspack.Compiler) { + apply(compiler: Rspack.Compiler): void { const { splitChunks } = compiler.options.optimization; if (!splitChunks) { diff --git a/packages/core/src/plugins/open.ts b/packages/core/src/plugins/open.ts index 2562a3e291..3a7e50966e 100644 --- a/packages/core/src/plugins/open.ts +++ b/packages/core/src/plugins/open.ts @@ -81,10 +81,10 @@ export async function openBrowser(url: string): Promise { } } -export const replacePlaceholder = (url: string, port: number) => +export const replacePlaceholder = (url: string, port: number): string => url.replace(//g, String(port)); -export function resolveUrl(str: string, base: string) { +export function resolveUrl(str: string, base: string): string { if (canParse(str)) { return str; } diff --git a/packages/core/src/plugins/rspackProfile.ts b/packages/core/src/plugins/rspackProfile.ts index 9cfb472e51..05a9179e8c 100644 --- a/packages/core/src/plugins/rspackProfile.ts +++ b/packages/core/src/plugins/rspackProfile.ts @@ -5,10 +5,7 @@ import { rspack } from '@rspack/core'; import { logger } from '../logger'; import type { RsbuildPlugin } from '../types'; -export const stopProfiler = ( - output: string, - profileSession?: inspector.Session, -) => { +const stopProfiler = (output: string, profileSession?: inspector.Session) => { if (!profileSession) { return; } diff --git a/packages/core/src/plugins/splitChunks.ts b/packages/core/src/plugins/splitChunks.ts index 42b30ca102..f44e8d26eb 100644 --- a/packages/core/src/plugins/splitChunks.ts +++ b/packages/core/src/plugins/splitChunks.ts @@ -107,10 +107,12 @@ function splitByExperience(ctx: SplitChunksContext): SplitChunks { }; } -export const MODULE_PATH_REGEX = +export const MODULE_PATH_REGEX: RegExp = /.*[\\/]node_modules[\\/](?!\.pnpm[\\/])(?:(@[^\\/]+)[\\/])?([^\\/]+)/; -export function getPackageNameFromModulePath(modulePath: string) { +export function getPackageNameFromModulePath( + modulePath: string, +): string | undefined { const handleModuleContext = modulePath?.match(MODULE_PATH_REGEX); if (!handleModuleContext) { diff --git a/packages/core/src/plugins/sri.ts b/packages/core/src/plugins/sri.ts index 091a386d86..4ee3f8f77a 100644 --- a/packages/core/src/plugins/sri.ts +++ b/packages/core/src/plugins/sri.ts @@ -147,7 +147,7 @@ export const pluginSri = (): RsbuildPlugin => ({ this.algorithm = algorithm; } - apply(compiler: Rspack.Compiler) { + apply(compiler: Rspack.Compiler): void { compiler.hooks.compilation.tap( 'SriReplaceIntegrityPlugin', (compilation) => { diff --git a/packages/core/src/plugins/swc.ts b/packages/core/src/plugins/swc.ts index 7672ce5037..bbf1c42d17 100644 --- a/packages/core/src/plugins/swc.ts +++ b/packages/core/src/plugins/swc.ts @@ -181,7 +181,7 @@ function applyTransformImport( export function applySwcDecoratorConfig( swcConfig: SwcLoaderOptions, config: NormalizedEnvironmentConfig, -) { +): void { swcConfig.jsc ||= {}; swcConfig.jsc.transform ||= {}; diff --git a/packages/core/src/provider/build.ts b/packages/core/src/provider/build.ts index 340a66f552..8d8375ee52 100644 --- a/packages/core/src/provider/build.ts +++ b/packages/core/src/provider/build.ts @@ -14,7 +14,7 @@ import { type InitConfigsOptions, initConfigs } from './initConfigs'; export const build = async ( initOptions: InitConfigsOptions, { mode = 'production', watch, compiler: customCompiler }: BuildOptions = {}, -) => { +): Promise => { if (!getNodeEnv()) { setNodeEnv(mode); } diff --git a/packages/core/src/provider/inspectConfig.ts b/packages/core/src/provider/inspectConfig.ts index 99600c6697..0eb50ff767 100644 --- a/packages/core/src/provider/inspectConfig.ts +++ b/packages/core/src/provider/inspectConfig.ts @@ -42,7 +42,7 @@ export async function inspectConfig({ pluginNames: pluginManager.getPlugins().map((p) => p.name), }; - const rawRsbuildConfig = await stringifyConfig( + const rawRsbuildConfig = stringifyConfig( rsbuildDebugConfig, inspectOptions.verbose, ); @@ -50,7 +50,7 @@ export async function inspectConfig({ const rawBundlerConfigs = await Promise.all( rspackConfigs.map(async (config, index) => ({ name: config.name || String(index), - content: await stringifyConfig(config, inspectOptions.verbose), + content: stringifyConfig(config, inspectOptions.verbose), })), ); diff --git a/packages/core/src/rspack/HtmlAppIconPlugin.ts b/packages/core/src/rspack/HtmlAppIconPlugin.ts index 97838a5896..20cb4337ba 100644 --- a/packages/core/src/rspack/HtmlAppIconPlugin.ts +++ b/packages/core/src/rspack/HtmlAppIconPlugin.ts @@ -22,7 +22,7 @@ export class HtmlAppIconPlugin { this.iconPath = options.iconPath; } - apply(compiler: Compiler) { + apply(compiler: Compiler): void { if (!fs.existsSync(this.iconPath)) { throw new Error( `[${this.name}] Can not find the app icon, please check if the '${this.iconPath}' file exists'.`, diff --git a/packages/core/src/rspack/HtmlBasicPlugin.ts b/packages/core/src/rspack/HtmlBasicPlugin.ts index 90c6aa10cc..02c6efbc8b 100644 --- a/packages/core/src/rspack/HtmlBasicPlugin.ts +++ b/packages/core/src/rspack/HtmlBasicPlugin.ts @@ -19,7 +19,7 @@ export type TagConfig = { }; /** @see {@link https://developer.mozilla.org/en-US/docs/Glossary/Void_element} */ -export const VOID_TAGS = [ +const VOID_TAGS = [ 'area', 'base', 'br', @@ -38,7 +38,7 @@ export const VOID_TAGS = [ ]; /** @see {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/head#see_also} */ -export const HEAD_TAGS = [ +const HEAD_TAGS = [ 'title', 'base', 'link', @@ -252,7 +252,7 @@ export class HtmlBasicPlugin { this.modifyTagsFn = modifyTagsFn; } - apply(compiler: Compiler) { + apply(compiler: Compiler): void { compiler.hooks.compilation.tap(this.name, (compilation: Compilation) => { getHTMLPlugin() .getHooks(compilation) diff --git a/packages/core/src/rspack/InlineChunkHtmlPlugin.ts b/packages/core/src/rspack/InlineChunkHtmlPlugin.ts index 8840fcbfd2..f6d57b12c1 100644 --- a/packages/core/src/rspack/InlineChunkHtmlPlugin.ts +++ b/packages/core/src/rspack/InlineChunkHtmlPlugin.ts @@ -53,7 +53,7 @@ export class InlineChunkHtmlPlugin { * because the relative path of source code has been changed. * @param source */ - updateSourceMappingURL({ + private updateSourceMappingURL({ source, compilation, publicPath, @@ -85,7 +85,7 @@ export class InlineChunkHtmlPlugin { return source; } - matchTests(name: string, source: string, tests: InlineChunkTest[]) { + private matchTests(name: string, source: string, tests: InlineChunkTest[]) { return tests.some((test) => { if (isFunction(test)) { const size = source.length; @@ -95,7 +95,7 @@ export class InlineChunkHtmlPlugin { }); } - getInlinedScriptTag( + private getInlinedScriptTag( publicPath: string, tag: HtmlTagObject, compilation: Compilation, @@ -142,7 +142,7 @@ export class InlineChunkHtmlPlugin { return ret; } - getInlinedCSSTag( + private getInlinedCSSTag( publicPath: string, tag: HtmlTagObject, compilation: Compilation, @@ -187,7 +187,7 @@ export class InlineChunkHtmlPlugin { return ret; } - getInlinedTag( + private getInlinedTag( publicPath: string, tag: HtmlTagObject, compilation: Compilation, @@ -215,7 +215,7 @@ export class InlineChunkHtmlPlugin { return tag; } - apply(compiler: Compiler) { + apply(compiler: Compiler): void { compiler.hooks.compilation.tap(this.name, (compilation: Compilation) => { const publicPath = getPublicPathFromCompiler(compiler); diff --git a/packages/core/src/server/compilerDevMiddleware.ts b/packages/core/src/server/compilerDevMiddleware.ts index 1f4555f095..4f9d701052 100644 --- a/packages/core/src/server/compilerDevMiddleware.ts +++ b/packages/core/src/server/compilerDevMiddleware.ts @@ -63,7 +63,7 @@ export class CompilerDevMiddleware { this.devMiddleware = devMiddleware; } - public async init() { + public async init(): Promise { // start compiling this.middleware = this.setupDevMiddleware( this.devMiddleware, @@ -73,11 +73,11 @@ export class CompilerDevMiddleware { await this.socketServer.prepare(); } - public upgrade(req: IncomingMessage, sock: Socket, head: any) { + public upgrade(req: IncomingMessage, sock: Socket, head: any): void { this.socketServer.upgrade(req, sock, head); } - public close() { + public close(): void { // socketServer close should before app close this.socketServer.close(); this.middleware?.close(noop); @@ -86,7 +86,7 @@ export class CompilerDevMiddleware { public sockWrite( type: string, data?: Record | string | boolean, - ) { + ): void { this.socketServer.sockWrite(type, data); } diff --git a/packages/core/src/server/devMiddleware.ts b/packages/core/src/server/devMiddleware.ts index 5ebb32804c..c0caa2ab98 100644 --- a/packages/core/src/server/devMiddleware.ts +++ b/packages/core/src/server/devMiddleware.ts @@ -13,7 +13,7 @@ export const isClientCompiler = (compiler: { options: { target?: Compiler['options']['target']; }; -}) => { +}): boolean => { const { target } = compiler.options; if (target) { @@ -23,7 +23,7 @@ export const isClientCompiler = (compiler: { return false; }; -export const isNodeCompiler = (compiler: { +const isNodeCompiler = (compiler: { options: { target?: Compiler['options']['target']; }; @@ -49,7 +49,7 @@ export const setupServerHooks = ( }; }, hookCallbacks: ServerCallbacks, -) => { +): void => { // TODO: node SSR HMR is not supported yet if (isNodeCompiler(compiler)) { return; diff --git a/packages/core/src/server/getDevMiddlewares.ts b/packages/core/src/server/getDevMiddlewares.ts index e8918a8367..7d037213ec 100644 --- a/packages/core/src/server/getDevMiddlewares.ts +++ b/packages/core/src/server/getDevMiddlewares.ts @@ -193,7 +193,13 @@ const applyDefaultMiddlewares = async ({ }; }; -export const getMiddlewares = async (options: RsbuildDevMiddlewareOptions) => { +export const getMiddlewares = async ( + options: RsbuildDevMiddlewareOptions, +): Promise<{ + close: () => Promise; + onUpgrade: UpgradeEvent; + middlewares: Middlewares; +}> => { const middlewares: Middlewares = []; const { compileMiddlewareAPI } = options; diff --git a/packages/core/src/server/helper.ts b/packages/core/src/server/helper.ts index 6ccd2a97fb..a03a7defc5 100644 --- a/packages/core/src/server/helper.ts +++ b/packages/core/src/server/helper.ts @@ -32,7 +32,8 @@ export type StartServerResult = { }; // remove repeat '/' -export const normalizeUrl = (url: string) => url.replace(/([^:]\/)\/+/g, '$1'); +export const normalizeUrl = (url: string): string => + url.replace(/([^:]\/)\/+/g, '$1'); /** * Make sure there is slash before and after prefix @@ -233,7 +234,11 @@ export const getServerConfig = async ({ }: { config: NormalizedConfig; getPortSilently?: boolean; -}) => { +}): Promise<{ + port: number; + host: string; + https: boolean; +}> => { const host = config.server.host || DEFAULT_DEV_HOST; const port = await getPort({ host, @@ -296,7 +301,7 @@ const concatUrl = ({ const LOCAL_LABEL = 'Local: '; const NETWORK_LABEL = 'Network: '; -export const getUrlLabel = (url: string) => { +const getUrlLabel = (url: string) => { try { const { host } = new URL(url); return isLoopbackHost(host) ? LOCAL_LABEL : NETWORK_LABEL; diff --git a/packages/core/src/server/httpServer.ts b/packages/core/src/server/httpServer.ts index fda142175b..6d32c1f619 100644 --- a/packages/core/src/server/httpServer.ts +++ b/packages/core/src/server/httpServer.ts @@ -1,3 +1,5 @@ +import type { Server } from 'node:http'; +import type { Http2SecureServer } from 'node:http2'; import type { ServerConfig } from '@rsbuild/shared'; import type Connect from 'connect'; @@ -7,7 +9,7 @@ export const createHttpServer = async ({ }: { serverConfig: ServerConfig; middlewares: Connect.Server; -}) => { +}): Promise => { if (serverConfig.https) { // http-proxy does not supports http2 if (serverConfig.proxy) { diff --git a/packages/core/src/server/prodServer.ts b/packages/core/src/server/prodServer.ts index 021793714d..e6fdf24656 100644 --- a/packages/core/src/server/prodServer.ts +++ b/packages/core/src/server/prodServer.ts @@ -44,7 +44,7 @@ export class RsbuildProdServer { } // Complete the preparation of services - public async onInit(app: Server | Http2SecureServer) { + public async onInit(app: Server | Http2SecureServer): Promise { this.app = app; await this.applyDefaultMiddlewares(); @@ -140,14 +140,14 @@ export class RsbuildProdServer { }); } - public close() {} + public close(): void {} } export async function startProdServer( context: InternalContext, config: NormalizedConfig, { getPortSilently }: PreviewServerOptions = {}, -) { +): Promise { if (!getNodeEnv()) { setNodeEnv('production'); } diff --git a/packages/core/src/server/proxy.ts b/packages/core/src/server/proxy.ts index f78b22950f..6e388b51b7 100644 --- a/packages/core/src/server/proxy.ts +++ b/packages/core/src/server/proxy.ts @@ -10,7 +10,7 @@ import { import { logger } from '../logger'; import type { UpgradeEvent } from './helper'; -export function formatProxyOptions(proxyOptions: ProxyOptions) { +function formatProxyOptions(proxyOptions: ProxyOptions) { const ret: ProxyDetail[] = []; if (Array.isArray(proxyOptions)) { @@ -42,7 +42,12 @@ export function formatProxyOptions(proxyOptions: ProxyOptions) { return ret; } -export const createProxyMiddleware = (proxyOptions: ProxyOptions) => { +export const createProxyMiddleware = ( + proxyOptions: ProxyOptions, +): { + middlewares: Middleware[]; + upgrade: UpgradeEvent; +} => { // If it is not an array, it may be an object that uses the context attribute // or an object in the form of { source: ProxyDetail } const formattedOptionsList = formatProxyOptions(proxyOptions); diff --git a/packages/core/src/server/restart.ts b/packages/core/src/server/restart.ts index 67f1dbd1cb..2ee3b1d02e 100644 --- a/packages/core/src/server/restart.ts +++ b/packages/core/src/server/restart.ts @@ -10,7 +10,7 @@ let cleaners: Cleaner[] = []; /** * Add a cleaner to handle side effects */ -export const onBeforeRestartServer = (cleaner: Cleaner) => { +export const onBeforeRestartServer = (cleaner: Cleaner): void => { cleaners.push(cleaner); }; @@ -20,7 +20,11 @@ const clearConsole = () => { } }; -export const restartDevServer = async ({ filePath }: { filePath: string }) => { +export const restartDevServer = async ({ + filePath, +}: { + filePath: string; +}): Promise => { clearConsole(); const filename = path.basename(filePath); diff --git a/packages/core/src/server/socketServer.ts b/packages/core/src/server/socketServer.ts index 2a941c4974..4a90fedf9f 100644 --- a/packages/core/src/server/socketServer.ts +++ b/packages/core/src/server/socketServer.ts @@ -24,7 +24,7 @@ export class SocketServer { this.options = options; } - public upgrade(req: IncomingMessage, sock: Socket, head: any) { + public upgrade(req: IncomingMessage, sock: Socket, head: any): void { // subscribe upgrade event to handle socket if (!this.wsServer.shouldHandle(req)) { @@ -37,7 +37,7 @@ export class SocketServer { } // create socket, install socket handler, bind socket event - public async prepare() { + public async prepare(): Promise { const { default: ws } = await import('ws'); this.wsServer = new ws.Server({ noServer: true, @@ -68,7 +68,7 @@ export class SocketServer { }); } - public updateStats(stats: Stats) { + public updateStats(stats: Stats): void { this.stats = stats; this.sendStats(); } @@ -77,13 +77,13 @@ export class SocketServer { public sockWrite( type: string, data?: Record | string | boolean, - ) { + ): void { for (const socket of this.sockets) { this.send(socket, JSON.stringify({ type, data })); } } - public singleWrite( + private singleWrite( socket: Ws, type: string, data?: Record | string | boolean, @@ -91,7 +91,7 @@ export class SocketServer { this.send(socket, JSON.stringify({ type, data })); } - public close() { + public close(): void { for (const socket of this.sockets) { socket.close(); } diff --git a/packages/core/src/server/watchFiles.ts b/packages/core/src/server/watchFiles.ts index f12d656aa9..ccddf1eb14 100644 --- a/packages/core/src/server/watchFiles.ts +++ b/packages/core/src/server/watchFiles.ts @@ -13,7 +13,12 @@ type WatchFilesOptions = { compileMiddlewareAPI?: CompileMiddlewareAPI; }; -export async function setupWatchFiles(options: WatchFilesOptions) { +export async function setupWatchFiles(options: WatchFilesOptions): Promise< + | { + close(): Promise; + } + | undefined +> { const { dev, server, compileMiddlewareAPI } = options; const { hmr, liveReload } = dev; diff --git a/packages/core/tests/config.test.ts b/packages/core/tests/config.test.ts index 7c1ef35b70..1f6e2eded8 100644 --- a/packages/core/tests/config.test.ts +++ b/packages/core/tests/config.test.ts @@ -9,7 +9,7 @@ describe('stringifyConfig', () => { plugins: [new DefinePlugin({ foo: 'bar' })], }; - expect(await stringifyConfig(config)).toMatchSnapshot(); + expect(stringifyConfig(config)).toMatchSnapshot(); }); it('should stringify Rspack config with verbose option correctly', async () => { @@ -29,7 +29,7 @@ describe('stringifyConfig', () => { ], }; - expect(await stringifyConfig(config, true)).toMatchSnapshot(); + expect(stringifyConfig(config, true)).toMatchSnapshot(); }); it('should stringify Rsbuild config correctly', async () => { @@ -41,6 +41,6 @@ describe('stringifyConfig', () => { }, }; - expect(await stringifyConfig(rsbuildConfig)).toMatchSnapshot(); + expect(stringifyConfig(rsbuildConfig)).toMatchSnapshot(); }); }); diff --git a/packages/core/tests/external.test.ts b/packages/core/tests/external.test.ts index 6b99498eee..9461ddf974 100644 --- a/packages/core/tests/external.test.ts +++ b/packages/core/tests/external.test.ts @@ -22,7 +22,7 @@ describe('plugin-external', () => { pluginExternals().setup(api); - const chain = await getBundlerChain(); + const chain = getBundlerChain(); await modifyBundlerChainCb(chain, { environment: 'client' }); diff --git a/packages/core/tsconfig.json b/packages/core/tsconfig.json index afdf2603c5..0d4933f86d 100644 --- a/packages/core/tsconfig.json +++ b/packages/core/tsconfig.json @@ -6,6 +6,7 @@ "rootDir": "src", "declarationDir": "./dist-types", "composite": true, + "isolatedDeclarations": true, "types": ["@rspack/core/module"], "paths": { "ws": ["./compiled/ws"], diff --git a/packages/plugin-assets-retry/src/AssetsRetryPlugin.ts b/packages/plugin-assets-retry/src/AssetsRetryPlugin.ts index ed370776ff..fc8578f6e9 100644 --- a/packages/plugin-assets-retry/src/AssetsRetryPlugin.ts +++ b/packages/plugin-assets-retry/src/AssetsRetryPlugin.ts @@ -41,7 +41,7 @@ export class AssetsRetryPlugin implements Rspack.RspackPluginInstance { this.minify = minify; } - async getRetryCode() { + async getRetryCode(): Promise { const { default: serialize } = await import('serialize-javascript'); const filename = 'initialChunkRetry'; const runtimeFilePath = path.join( @@ -55,7 +55,7 @@ export class AssetsRetryPlugin implements Rspack.RspackPluginInstance { )});})()`; } - async getScriptPath() { + async getScriptPath(): Promise { if (!this.scriptPath) { this.scriptPath = path.posix.join( this.distDir, diff --git a/packages/plugin-assets-retry/src/AsyncChunkRetryPlugin.ts b/packages/plugin-assets-retry/src/AsyncChunkRetryPlugin.ts index b1f19eab83..f938567a5c 100644 --- a/packages/plugin-assets-retry/src/AsyncChunkRetryPlugin.ts +++ b/packages/plugin-assets-retry/src/AsyncChunkRetryPlugin.ts @@ -58,7 +58,7 @@ class AsyncChunkRetryPlugin implements Rspack.RspackPluginInstance { ]); } - getRawRuntimeRetryCode() { + getRawRuntimeRetryCode(): string { const { RuntimeGlobals } = rspack; const filename = 'asyncChunkRetry'; const runtimeFilePath = path.join( @@ -83,7 +83,7 @@ class AsyncChunkRetryPlugin implements Rspack.RspackPluginInstance { .replaceAll('__RETRY_OPTIONS__', serialize(this.runtimeOptions)); } - apply(compiler: Rspack.Compiler) { + apply(compiler: Rspack.Compiler): void { compiler.hooks.thisCompilation.tap(this.name, (compilation) => { compilation.hooks.runtimeModule.tap(this.name, (module) => { const { isRspack } = this.options; diff --git a/packages/plugin-assets-retry/tsconfig.json b/packages/plugin-assets-retry/tsconfig.json index bd055d67fb..ab0cd0308f 100644 --- a/packages/plugin-assets-retry/tsconfig.json +++ b/packages/plugin-assets-retry/tsconfig.json @@ -4,7 +4,8 @@ "outDir": "./dist", "baseUrl": "./", "rootDir": "src", - "composite": true + "composite": true, + "isolatedDeclarations": true }, "references": [ { diff --git a/packages/plugin-babel/src/helper.ts b/packages/plugin-babel/src/helper.ts index ee016d2b15..4d8e1cb734 100644 --- a/packages/plugin-babel/src/helper.ts +++ b/packages/plugin-babel/src/helper.ts @@ -170,7 +170,9 @@ export const applyUserBabelConfig = ( return defaultOptions; }; -export const getUseBuiltIns = (config: NormalizedConfig) => { +export const getUseBuiltIns = ( + config: NormalizedConfig, +): false | 'usage' | 'entry' => { const { polyfill } = config.output; if (polyfill === 'off') { return false; @@ -186,7 +188,7 @@ export const modifyBabelLoaderOptions = ({ chain: RspackChain; CHAIN_ID: ChainIdentifier; modifier: (config: BabelTransformOptions) => BabelTransformOptions; -}) => { +}): void => { const ruleIds = [CHAIN_ID.RULE.JS, CHAIN_ID.RULE.JS_DATA_URI, BABEL_JS_RULE]; for (const ruleId of ruleIds) { diff --git a/packages/plugin-babel/tsconfig.json b/packages/plugin-babel/tsconfig.json index bd055d67fb..ab0cd0308f 100644 --- a/packages/plugin-babel/tsconfig.json +++ b/packages/plugin-babel/tsconfig.json @@ -4,7 +4,8 @@ "outDir": "./dist", "baseUrl": "./", "rootDir": "src", - "composite": true + "composite": true, + "isolatedDeclarations": true }, "references": [ { diff --git a/packages/plugin-basic-ssl/src/util.ts b/packages/plugin-basic-ssl/src/util.ts index fff51e5de0..cc1ce3c4c8 100644 --- a/packages/plugin-basic-ssl/src/util.ts +++ b/packages/plugin-basic-ssl/src/util.ts @@ -3,9 +3,20 @@ import path from 'node:path'; import type { ServerConfig } from '@rsbuild/core'; import selfsigned from 'selfsigned'; -export const resolveHttpsConfig = (config: ServerConfig['https']) => { +type HttpsConfig = ServerConfig['https']; + +export const resolveHttpsConfig = ( + config: HttpsConfig, +): { + key: NonNullable['key']; + cert: NonNullable['cert']; +} => { const { key, cert } = config ?? {}; - if (key && cert) return { key, cert }; + + if (key && cert) { + return { key, cert }; + } + const certPath = path.join(__dirname, 'fake-cert.pem'); if (fs.existsSync(certPath)) { const stats = fs.statSync(certPath); diff --git a/packages/plugin-basic-ssl/tsconfig.json b/packages/plugin-basic-ssl/tsconfig.json index 68290500b9..c695a9910b 100644 --- a/packages/plugin-basic-ssl/tsconfig.json +++ b/packages/plugin-basic-ssl/tsconfig.json @@ -4,7 +4,8 @@ "outDir": "./dist", "baseUrl": "./", "rootDir": "src", - "composite": true + "composite": true, + "isolatedDeclarations": true }, "references": [ { diff --git a/packages/plugin-check-syntax/src/CheckSyntaxPlugin.ts b/packages/plugin-check-syntax/src/CheckSyntaxPlugin.ts index 6b81ba739f..349262edb3 100644 --- a/packages/plugin-check-syntax/src/CheckSyntaxPlugin.ts +++ b/packages/plugin-check-syntax/src/CheckSyntaxPlugin.ts @@ -46,7 +46,7 @@ export class CheckSyntaxPlugin { options.ecmaVersion || browserslistToESVersion(this.targets); } - apply(compiler: Compiler) { + apply(compiler: Compiler): void { compiler.hooks.afterEmit.tapPromise( CheckSyntaxPlugin.name, async (compilation: Compilation) => { diff --git a/packages/plugin-check-syntax/src/helpers/generateError.ts b/packages/plugin-check-syntax/src/helpers/generateError.ts index a707100fcf..b224f67c8e 100644 --- a/packages/plugin-check-syntax/src/helpers/generateError.ts +++ b/packages/plugin-check-syntax/src/helpers/generateError.ts @@ -29,7 +29,7 @@ export async function generateError({ filepath: string; rootPath: string; exclude?: CheckSyntaxExclude; -}) { +}): Promise { let error = await tryGenerateErrorFromSourceMap({ err, filepath, diff --git a/packages/plugin-check-syntax/src/helpers/generateHtmlScripts.ts b/packages/plugin-check-syntax/src/helpers/generateHtmlScripts.ts index 7b23bdbf43..462af6d8d7 100644 --- a/packages/plugin-check-syntax/src/helpers/generateHtmlScripts.ts +++ b/packages/plugin-check-syntax/src/helpers/generateHtmlScripts.ts @@ -1,12 +1,12 @@ import fs from 'node:fs'; import { Parser } from 'htmlparser2'; -export async function generateHtmlScripts(filepath: string) { +export async function generateHtmlScripts(filepath: string): Promise { const html = await fs.promises.readFile(filepath, 'utf-8'); return getHtmlScripts(html); } -export function getHtmlScripts(html: string) { +export function getHtmlScripts(html: string): string[] { const inlineScripts: string[] = []; let currentScript: string | null = null; diff --git a/packages/plugin-check-syntax/src/helpers/printErrors.ts b/packages/plugin-check-syntax/src/helpers/printErrors.ts index f1cde15a8a..bba378c64a 100644 --- a/packages/plugin-check-syntax/src/helpers/printErrors.ts +++ b/packages/plugin-check-syntax/src/helpers/printErrors.ts @@ -12,7 +12,7 @@ type Error = { export function printErrors( errors: ECMASyntaxError[], ecmaVersion: EcmaVersion, -) { +): void { if (errors.length === 0) { logger.success('The syntax check success.'); return; diff --git a/packages/plugin-check-syntax/src/helpers/utils.ts b/packages/plugin-check-syntax/src/helpers/utils.ts index 3c20fe62fe..a874eecdc9 100644 --- a/packages/plugin-check-syntax/src/helpers/utils.ts +++ b/packages/plugin-check-syntax/src/helpers/utils.ts @@ -3,7 +3,7 @@ import type { CheckSyntaxExclude } from '../types'; export function checkIsExcludeSource( path: string, exclude?: CheckSyntaxExclude, -) { +): boolean { if (!exclude) { return false; } diff --git a/packages/plugin-check-syntax/tsconfig.json b/packages/plugin-check-syntax/tsconfig.json index bd055d67fb..ab0cd0308f 100644 --- a/packages/plugin-check-syntax/tsconfig.json +++ b/packages/plugin-check-syntax/tsconfig.json @@ -4,7 +4,8 @@ "outDir": "./dist", "baseUrl": "./", "rootDir": "src", - "composite": true + "composite": true, + "isolatedDeclarations": true }, "references": [ { diff --git a/packages/plugin-css-minimizer/src/index.ts b/packages/plugin-css-minimizer/src/index.ts index ce6cb32972..0d10ccc57e 100644 --- a/packages/plugin-css-minimizer/src/index.ts +++ b/packages/plugin-css-minimizer/src/index.ts @@ -41,7 +41,7 @@ export function applyCSSMinimizer( chain: RspackChain, CHAIN_ID: ChainIdentifier, options: PluginCssMinimizerOptions = {}, -) { +): void { const mergedOptions: CssMinimizerPluginOptions = reduceConfigs({ initial: { minify: CssMinimizerWebpackPlugin.cssnanoMinify, diff --git a/packages/plugin-css-minimizer/tsconfig.json b/packages/plugin-css-minimizer/tsconfig.json index 68290500b9..c695a9910b 100644 --- a/packages/plugin-css-minimizer/tsconfig.json +++ b/packages/plugin-css-minimizer/tsconfig.json @@ -4,7 +4,8 @@ "outDir": "./dist", "baseUrl": "./", "rootDir": "src", - "composite": true + "composite": true, + "isolatedDeclarations": true }, "references": [ { diff --git a/packages/plugin-eslint/tsconfig.json b/packages/plugin-eslint/tsconfig.json index 68290500b9..c695a9910b 100644 --- a/packages/plugin-eslint/tsconfig.json +++ b/packages/plugin-eslint/tsconfig.json @@ -4,7 +4,8 @@ "outDir": "./dist", "baseUrl": "./", "rootDir": "src", - "composite": true + "composite": true, + "isolatedDeclarations": true }, "references": [ { diff --git a/packages/plugin-image-compress/src/minimizer.ts b/packages/plugin-image-compress/src/minimizer.ts index cfb5a1fdda..c6a5f1c420 100644 --- a/packages/plugin-image-compress/src/minimizer.ts +++ b/packages/plugin-image-compress/src/minimizer.ts @@ -11,7 +11,7 @@ export interface MinimizedResult { } export class ImageMinimizerPlugin { - name = IMAGE_MINIMIZER_PLUGIN_NAME; + name: string = IMAGE_MINIMIZER_PLUGIN_NAME; options: FinalOptions; @@ -83,7 +83,7 @@ export class ImageMinimizerPlugin { await Promise.all(promises); } - apply(compiler: webpack.Compiler) { + apply(compiler: webpack.Compiler): void { const handleCompilation = (compilation: webpack.Compilation) => { compilation.hooks.processAssets.tapPromise( { diff --git a/packages/plugin-image-compress/tsconfig.json b/packages/plugin-image-compress/tsconfig.json index 68290500b9..c695a9910b 100644 --- a/packages/plugin-image-compress/tsconfig.json +++ b/packages/plugin-image-compress/tsconfig.json @@ -4,7 +4,8 @@ "outDir": "./dist", "baseUrl": "./", "rootDir": "src", - "composite": true + "composite": true, + "isolatedDeclarations": true }, "references": [ { diff --git a/packages/plugin-less/tsconfig.json b/packages/plugin-less/tsconfig.json index bd055d67fb..ab0cd0308f 100644 --- a/packages/plugin-less/tsconfig.json +++ b/packages/plugin-less/tsconfig.json @@ -4,7 +4,8 @@ "outDir": "./dist", "baseUrl": "./", "rootDir": "src", - "composite": true + "composite": true, + "isolatedDeclarations": true }, "references": [ { diff --git a/packages/plugin-lightningcss/src/minimizer.ts b/packages/plugin-lightningcss/src/minimizer.ts index 46687c1233..c4f84f19c3 100644 --- a/packages/plugin-lightningcss/src/minimizer.ts +++ b/packages/plugin-lightningcss/src/minimizer.ts @@ -23,7 +23,7 @@ export class LightningCSSMinifyPlugin { this.options = opts; } - apply(compiler: Rspack.Compiler) { + apply(compiler: Rspack.Compiler): void { compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { compilation.hooks.processAssets.tapPromise( { diff --git a/packages/plugin-lightningcss/tsconfig.json b/packages/plugin-lightningcss/tsconfig.json index bd055d67fb..ab0cd0308f 100644 --- a/packages/plugin-lightningcss/tsconfig.json +++ b/packages/plugin-lightningcss/tsconfig.json @@ -4,7 +4,8 @@ "outDir": "./dist", "baseUrl": "./", "rootDir": "src", - "composite": true + "composite": true, + "isolatedDeclarations": true }, "references": [ { diff --git a/packages/plugin-mdx/tsconfig.json b/packages/plugin-mdx/tsconfig.json index 68290500b9..c695a9910b 100644 --- a/packages/plugin-mdx/tsconfig.json +++ b/packages/plugin-mdx/tsconfig.json @@ -4,7 +4,8 @@ "outDir": "./dist", "baseUrl": "./", "rootDir": "src", - "composite": true + "composite": true, + "isolatedDeclarations": true }, "references": [ { diff --git a/packages/plugin-node-polyfill/src/ProtocolImportsPlugin.ts b/packages/plugin-node-polyfill/src/ProtocolImportsPlugin.ts index 3cae091ae7..830cc8750b 100644 --- a/packages/plugin-node-polyfill/src/ProtocolImportsPlugin.ts +++ b/packages/plugin-node-polyfill/src/ProtocolImportsPlugin.ts @@ -1,7 +1,7 @@ import type { Rspack } from '@rsbuild/core'; export class ProtocolImportsPlugin { - apply(compiler: Rspack.Compiler) { + apply(compiler: Rspack.Compiler): void { compiler.hooks.normalModuleFactory.tap( 'NormalModuleReplacementPlugin', (nmf) => { diff --git a/packages/plugin-node-polyfill/src/libs.ts b/packages/plugin-node-polyfill/src/libs.ts index bfc58aa49b..29e4593df0 100644 --- a/packages/plugin-node-polyfill/src/libs.ts +++ b/packages/plugin-node-polyfill/src/libs.ts @@ -1,48 +1,48 @@ -export const assert = require.resolve('assert/'); -export const buffer = require.resolve('buffer/'); +export const assert: string = require.resolve('assert/'); +export const buffer: string = require.resolve('buffer/'); export const child_process = null; export const cluster = null; -export const console = require.resolve('console-browserify'); -export const constants = require.resolve('constants-browserify'); -export const crypto = require.resolve('crypto-browserify'); +export const console: string = require.resolve('console-browserify'); +export const constants: string = require.resolve('constants-browserify'); +export const crypto: string = require.resolve('crypto-browserify'); export const dgram = null; export const dns = null; -export const domain = require.resolve('domain-browser'); -export const events = require.resolve('events/'); +export const domain: string = require.resolve('domain-browser'); +export const events: string = require.resolve('events/'); export const fs = null; -export const http = require.resolve('stream-http'); -export const https = require.resolve('https-browserify'); +export const http: string = require.resolve('stream-http'); +export const https: string = require.resolve('https-browserify'); export const module = null; export const net = null; -export const os = require.resolve('os-browserify/browser.js'); -export const path = require.resolve('path-browserify'); -export const punycode = require.resolve('punycode/'); -export const process = require.resolve('process/browser.js'); -export const querystring = require.resolve('querystring-es3/'); +export const os: string = require.resolve('os-browserify/browser.js'); +export const path: string = require.resolve('path-browserify'); +export const punycode: string = require.resolve('punycode/'); +export const process: string = require.resolve('process/browser.js'); +export const querystring: string = require.resolve('querystring-es3/'); export const readline = null; export const repl = null; -export const stream = require.resolve('stream-browserify'); -export const _stream_duplex = require.resolve( +export const stream: string = require.resolve('stream-browserify'); +export const _stream_duplex: string = require.resolve( 'readable-stream/lib/_stream_duplex.js', ); -export const _stream_passthrough = require.resolve( +export const _stream_passthrough: string = require.resolve( 'readable-stream/lib/_stream_passthrough.js', ); -export const _stream_readable = require.resolve( +export const _stream_readable: string = require.resolve( 'readable-stream/lib/_stream_readable.js', ); -export const _stream_transform = require.resolve( +export const _stream_transform: string = require.resolve( 'readable-stream/lib/_stream_transform.js', ); -export const _stream_writable = require.resolve( +export const _stream_writable: string = require.resolve( 'readable-stream/lib/_stream_writable.js', ); -export const string_decoder = require.resolve('string_decoder/'); -export const sys = require.resolve('util/util.js'); -export const timers = require.resolve('timers-browserify'); +export const string_decoder: string = require.resolve('string_decoder/'); +export const sys: string = require.resolve('util/util.js'); +export const timers: string = require.resolve('timers-browserify'); export const tls = null; -export const tty = require.resolve('tty-browserify'); -export const url = require.resolve('url/'); -export const util = require.resolve('util/util.js'); -export const vm = require.resolve('vm-browserify'); -export const zlib = require.resolve('browserify-zlib'); +export const tty: string = require.resolve('tty-browserify'); +export const url: string = require.resolve('url/'); +export const util: string = require.resolve('util/util.js'); +export const vm: string = require.resolve('vm-browserify'); +export const zlib: string = require.resolve('browserify-zlib'); diff --git a/packages/plugin-node-polyfill/tsconfig.json b/packages/plugin-node-polyfill/tsconfig.json index bd055d67fb..ab0cd0308f 100644 --- a/packages/plugin-node-polyfill/tsconfig.json +++ b/packages/plugin-node-polyfill/tsconfig.json @@ -4,7 +4,8 @@ "outDir": "./dist", "baseUrl": "./", "rootDir": "src", - "composite": true + "composite": true, + "isolatedDeclarations": true }, "references": [ { diff --git a/packages/plugin-preact/tsconfig.json b/packages/plugin-preact/tsconfig.json index 68290500b9..c695a9910b 100644 --- a/packages/plugin-preact/tsconfig.json +++ b/packages/plugin-preact/tsconfig.json @@ -4,7 +4,8 @@ "outDir": "./dist", "baseUrl": "./", "rootDir": "src", - "composite": true + "composite": true, + "isolatedDeclarations": true }, "references": [ { diff --git a/packages/plugin-pug/tsconfig.json b/packages/plugin-pug/tsconfig.json index 68290500b9..c695a9910b 100644 --- a/packages/plugin-pug/tsconfig.json +++ b/packages/plugin-pug/tsconfig.json @@ -4,7 +4,8 @@ "outDir": "./dist", "baseUrl": "./", "rootDir": "src", - "composite": true + "composite": true, + "isolatedDeclarations": true }, "references": [ { diff --git a/packages/plugin-react/src/react.ts b/packages/plugin-react/src/react.ts index 4a5119de4d..0baf534f24 100644 --- a/packages/plugin-react/src/react.ts +++ b/packages/plugin-react/src/react.ts @@ -33,7 +33,7 @@ const modifySwcLoaderOptions = ({ export const applyBasicReactSupport = ( api: RsbuildPluginAPI, options: PluginReactOptions, -) => { +): void => { const REACT_REFRESH_PATH = require.resolve('react-refresh'); api.modifyBundlerChain( @@ -93,7 +93,7 @@ export const applyBasicReactSupport = ( ); }; -export const applyReactProfiler = (api: RsbuildPluginAPI) => { +export const applyReactProfiler = (api: RsbuildPluginAPI): void => { api.modifyRsbuildConfig((config, { mergeRsbuildConfig }) => { const enableProfilerConfig: RsbuildConfig = { output: { diff --git a/packages/plugin-react/src/splitChunks.ts b/packages/plugin-react/src/splitChunks.ts index e81db7e4b1..2cd474c29c 100644 --- a/packages/plugin-react/src/splitChunks.ts +++ b/packages/plugin-react/src/splitChunks.ts @@ -13,7 +13,7 @@ export const applySplitChunksRule = ( react: true, router: true, }, -) => { +): void => { api.modifyBundlerChain((chain, { environment }) => { const config = api.getNormalizedConfig({ environment }); if (config.performance.chunkSplit.strategy !== 'split-by-experience') { diff --git a/packages/plugin-react/tsconfig.json b/packages/plugin-react/tsconfig.json index bd055d67fb..ab0cd0308f 100644 --- a/packages/plugin-react/tsconfig.json +++ b/packages/plugin-react/tsconfig.json @@ -4,7 +4,8 @@ "outDir": "./dist", "baseUrl": "./", "rootDir": "src", - "composite": true + "composite": true, + "isolatedDeclarations": true }, "references": [ { diff --git a/packages/plugin-rem/src/AutoSetRootFontSizePlugin.ts b/packages/plugin-rem/src/AutoSetRootFontSizePlugin.ts index 1bbe739442..7378baa253 100644 --- a/packages/plugin-rem/src/AutoSetRootFontSizePlugin.ts +++ b/packages/plugin-rem/src/AutoSetRootFontSizePlugin.ts @@ -19,7 +19,7 @@ type AutoSetRootFontSizeOptions = Omit< export async function getRootPixelCode( options: Required, isCompress = false, -) { +): Promise { const code = genJSTemplate(options); if (!isCompress) { @@ -80,7 +80,7 @@ export class AutoSetRootFontSizePlugin implements Rspack.RspackPluginInstance { this.scriptLoading = scriptLoading; } - async getScriptPath() { + async getScriptPath(): Promise { if (!this.scriptPath) { this.scriptPath = path.posix.join( this.distDir, @@ -91,7 +91,7 @@ export class AutoSetRootFontSizePlugin implements Rspack.RspackPluginInstance { return this.scriptPath; } - apply(compiler: Rspack.Compiler) { + apply(compiler: Rspack.Compiler): void { let runtimeCode: string | undefined; const getRuntimeCode = async () => { diff --git a/packages/plugin-rem/tsconfig.json b/packages/plugin-rem/tsconfig.json index bd055d67fb..ab0cd0308f 100644 --- a/packages/plugin-rem/tsconfig.json +++ b/packages/plugin-rem/tsconfig.json @@ -4,7 +4,8 @@ "outDir": "./dist", "baseUrl": "./", "rootDir": "src", - "composite": true + "composite": true, + "isolatedDeclarations": true }, "references": [ { diff --git a/packages/plugin-sass/src/helpers.ts b/packages/plugin-sass/src/helpers.ts index 6f537dbec2..49c0167f6d 100644 --- a/packages/plugin-sass/src/helpers.ts +++ b/packages/plugin-sass/src/helpers.ts @@ -33,7 +33,7 @@ export function patchCompilerGlobalLocation(compiler: { watchClose: CompilerTapFn; done: CompilerTapFn; }; -}) { +}): void { // https://github.com/webpack/webpack/blob/136b723023f8f26d71eabdd16badf04c1c8554e4/lib/MultiCompiler.js#L64 compiler.hooks.run.tap('PatchGlobalLocation', patchGlobalLocation); compiler.hooks.watchRun.tap('PatchGlobalLocation', patchGlobalLocation); @@ -46,7 +46,9 @@ export function patchCompilerGlobalLocation(compiler: { * * reference: https://github.com/bholloway/resolve-url-loader/blob/e2695cde68f325f617825e168173df92236efb93/packages/resolve-url-loader/docs/advanced-features.md */ -export const getResolveUrlJoinFn = async () => { +export const getResolveUrlJoinFn = async (): Promise< + (...args: unknown[]) => void +> => { const { createJoinFunction, asGenerator, diff --git a/packages/plugin-sass/tsconfig.json b/packages/plugin-sass/tsconfig.json index bd055d67fb..ab0cd0308f 100644 --- a/packages/plugin-sass/tsconfig.json +++ b/packages/plugin-sass/tsconfig.json @@ -4,7 +4,8 @@ "outDir": "./dist", "baseUrl": "./", "rootDir": "src", - "composite": true + "composite": true, + "isolatedDeclarations": true }, "references": [ { diff --git a/packages/plugin-solid/tsconfig.json b/packages/plugin-solid/tsconfig.json index 334a8faccc..755b6f1eee 100644 --- a/packages/plugin-solid/tsconfig.json +++ b/packages/plugin-solid/tsconfig.json @@ -4,7 +4,8 @@ "outDir": "./dist", "baseUrl": "./", "rootDir": "src", - "composite": true + "composite": true, + "isolatedDeclarations": true }, "references": [ { diff --git a/packages/plugin-source-build/src/common/getProjects.ts b/packages/plugin-source-build/src/common/getProjects.ts index f38b775bf1..1432ddadc1 100644 --- a/packages/plugin-source-build/src/common/getProjects.ts +++ b/packages/plugin-source-build/src/common/getProjects.ts @@ -1,4 +1,4 @@ -import type { Project } from '../project/project'; +import type { Project } from '../project'; import type { IMonorepoBaseData } from './getBaseData'; export type GetProjectsFunc = ( diff --git a/packages/plugin-source-build/src/common/pnpm.ts b/packages/plugin-source-build/src/common/pnpm.ts index c09a094f96..1eba2ca769 100644 --- a/packages/plugin-source-build/src/common/pnpm.ts +++ b/packages/plugin-source-build/src/common/pnpm.ts @@ -2,11 +2,11 @@ import fs from 'node:fs'; import path from 'node:path'; import glob, { type Options as GlobOptions } from 'fast-glob'; import { PACKAGE_JSON, PNPM_WORKSPACE_FILE } from '../constants'; -import { Project } from '../project/project'; +import { Project } from '../project'; import type { IPnpmWorkSpace } from '../types'; import { readPackageJson } from '../utils'; -export const getPatternsFromYaml = async (monorepoRoot: string) => { +const getPatternsFromYaml = async (monorepoRoot: string): Promise => { const { parse } = await import('yaml'); const workspaceYamlFilePath = path.join(monorepoRoot, PNPM_WORKSPACE_FILE); const yamlContent = await fs.promises.readFile(workspaceYamlFilePath, 'utf8'); @@ -14,7 +14,7 @@ export const getPatternsFromYaml = async (monorepoRoot: string) => { return pnpmWorkspace.packages || []; }; -export const normalize = (results: string[]) => +const normalize = (results: string[]) => results.map((fp: string) => path.normalize(fp)); const getGlobOpts = (rootPath: string, patterns: string[]): GlobOptions => { @@ -36,7 +36,7 @@ const getGlobOpts = (rootPath: string, patterns: string[]): GlobOptions => { return globOpts; }; -export const makeFileFinder = (rootPath: string, patterns: string[]) => { +const makeFileFinder = (rootPath: string, patterns: string[]) => { const globOpts = getGlobOpts(rootPath, patterns); return async ( @@ -57,10 +57,7 @@ export const makeFileFinder = (rootPath: string, patterns: string[]) => { }; }; -export const readPnpmProjects = async ( - monorepoRoot: string, - patterns: string[], -) => { +const readPnpmProjects = async (monorepoRoot: string, patterns: string[]) => { const finder = makeFileFinder(monorepoRoot, patterns); const mapper = async (pkgJsonFilePath: string) => { const pkgJson = await readPackageJson(pkgJsonFilePath); diff --git a/packages/plugin-source-build/src/common/rush.ts b/packages/plugin-source-build/src/common/rush.ts index 02b4a8af45..5000b8eacb 100644 --- a/packages/plugin-source-build/src/common/rush.ts +++ b/packages/plugin-source-build/src/common/rush.ts @@ -1,5 +1,5 @@ import path from 'node:path'; -import { Project } from '../project/project'; +import { Project } from '../project'; import { readRushJson } from '../utils'; export const getProjects = async (monorepoRoot: string): Promise => { diff --git a/packages/plugin-source-build/src/plugin.ts b/packages/plugin-source-build/src/plugin.ts index 45be7dd8f5..9378fb9af8 100644 --- a/packages/plugin-source-build/src/plugin.ts +++ b/packages/plugin-source-build/src/plugin.ts @@ -13,7 +13,7 @@ export const PLUGIN_SOURCE_BUILD_NAME = 'rsbuild:source-build'; export const getSourceInclude = async (options: { projects: Project[]; sourceField: string; -}) => { +}): Promise => { const { projects, sourceField } = options; const includes = []; diff --git a/packages/plugin-source-build/src/project-utils/filter.ts b/packages/plugin-source-build/src/project-utils/filter.ts index 66bf6ba01e..db82bfc8bb 100644 --- a/packages/plugin-source-build/src/project-utils/filter.ts +++ b/packages/plugin-source-build/src/project-utils/filter.ts @@ -1,4 +1,4 @@ -import type { Project } from '../project/project'; +import type { Project } from '../project'; import type { ExportsConfig } from '../types/packageJson'; export type Filter = FilterFunction; diff --git a/packages/plugin-source-build/src/project-utils/getDependentProjects.ts b/packages/plugin-source-build/src/project-utils/getDependentProjects.ts index a21e6b2b21..14e3a678e6 100644 --- a/packages/plugin-source-build/src/project-utils/getDependentProjects.ts +++ b/packages/plugin-source-build/src/project-utils/getDependentProjects.ts @@ -1,6 +1,7 @@ import fs from 'node:fs'; import path from 'node:path'; import { getMonorepoBaseData, getMonorepoSubProjects } from '../common'; +import type { Project } from '../project'; import type { MonorepoAnalyzer } from '../types'; import { readPackageJson } from '../utils'; import type { Filter } from './filter'; @@ -25,7 +26,7 @@ async function pathExists(path: string) { const getDependentProjects = async ( projectNameOrRootPath: string, options: GetDependentProjectsOptions, -) => { +): Promise => { const { cwd = process.cwd(), recursive, diff --git a/packages/plugin-source-build/src/project/project.ts b/packages/plugin-source-build/src/project.ts similarity index 92% rename from packages/plugin-source-build/src/project/project.ts rename to packages/plugin-source-build/src/project.ts index 4234f969ec..b0b2d62450 100644 --- a/packages/plugin-source-build/src/project/project.ts +++ b/packages/plugin-source-build/src/project.ts @@ -1,8 +1,8 @@ import fs from 'node:fs'; import path from 'node:path'; -import { PACKAGE_JSON } from '../constants'; -import type { ExportsConfig, INodePackageJson } from '../types/packageJson'; -import { readPackageJson } from '../utils'; +import { PACKAGE_JSON } from './constants'; +import type { ExportsConfig, INodePackageJson } from './types/packageJson'; +import { readPackageJson } from './utils'; export class Project { name: string; @@ -16,11 +16,11 @@ export class Project { this.dir = dir; } - async init() { + async init(): Promise { this.metaData = await readPackageJson(path.join(this.dir, PACKAGE_JSON)); } - getMetaData() { + getMetaData(): INodePackageJson { if (this.metaData === null) { throw new Error( 'The Project object needs to be initialized by executing the `init` function', @@ -89,7 +89,10 @@ export class Project { return projects; } - getSourceEntryPaths(options?: { field?: string; exports?: boolean }) { + getSourceEntryPaths(options?: { + field?: string; + exports?: boolean; + }): string[] { const { exports: checkExports = false, field: sourceField = 'source' } = options ?? {}; const pkgJson = this.getMetaData() as INodePackageJson & diff --git a/packages/plugin-source-build/src/project/index.ts b/packages/plugin-source-build/src/project/index.ts deleted file mode 100644 index 745ffa0005..0000000000 --- a/packages/plugin-source-build/src/project/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { Project } from './project'; diff --git a/packages/plugin-source-build/src/utils.ts b/packages/plugin-source-build/src/utils.ts index 5ad483810f..1680701cfc 100644 --- a/packages/plugin-source-build/src/utils.ts +++ b/packages/plugin-source-build/src/utils.ts @@ -4,11 +4,15 @@ import json5 from 'json5'; import { RUSH_JSON_FILE } from './constants'; import type { INodePackageJson, IRushConfig } from './types'; -export const readPackageJson = async (pkgJsonFilePath: string) => { +export const readPackageJson = async ( + pkgJsonFilePath: string, +): Promise => { return readJson(pkgJsonFilePath); }; -export const readRushJson = async (rushJsonFilePath: string) => { +export const readRushJson = async ( + rushJsonFilePath: string, +): Promise => { const rushJson = readJson( rushJsonFilePath.includes(RUSH_JSON_FILE) ? rushJsonFilePath @@ -24,7 +28,7 @@ async function pathExists(path: string) { .catch(() => false); } -export const readJson = async (jsonFileAbsPath: string) => { +export const readJson = async (jsonFileAbsPath: string): Promise => { if (!(await pathExists(jsonFileAbsPath))) { return {} as T; } diff --git a/packages/plugin-source-build/tsconfig.json b/packages/plugin-source-build/tsconfig.json index bd055d67fb..ab0cd0308f 100644 --- a/packages/plugin-source-build/tsconfig.json +++ b/packages/plugin-source-build/tsconfig.json @@ -4,7 +4,8 @@ "outDir": "./dist", "baseUrl": "./", "rootDir": "src", - "composite": true + "composite": true, + "isolatedDeclarations": true }, "references": [ { diff --git a/packages/plugin-styled-components/tsconfig.json b/packages/plugin-styled-components/tsconfig.json index bd055d67fb..ab0cd0308f 100644 --- a/packages/plugin-styled-components/tsconfig.json +++ b/packages/plugin-styled-components/tsconfig.json @@ -4,7 +4,8 @@ "outDir": "./dist", "baseUrl": "./", "rootDir": "src", - "composite": true + "composite": true, + "isolatedDeclarations": true }, "references": [ { diff --git a/packages/plugin-stylus/tsconfig.json b/packages/plugin-stylus/tsconfig.json index bd055d67fb..ab0cd0308f 100644 --- a/packages/plugin-stylus/tsconfig.json +++ b/packages/plugin-stylus/tsconfig.json @@ -4,7 +4,8 @@ "outDir": "./dist", "baseUrl": "./", "rootDir": "src", - "composite": true + "composite": true, + "isolatedDeclarations": true }, "references": [ { diff --git a/packages/plugin-svelte/tsconfig.json b/packages/plugin-svelte/tsconfig.json index bd055d67fb..ab0cd0308f 100644 --- a/packages/plugin-svelte/tsconfig.json +++ b/packages/plugin-svelte/tsconfig.json @@ -4,7 +4,8 @@ "outDir": "./dist", "baseUrl": "./", "rootDir": "src", - "composite": true + "composite": true, + "isolatedDeclarations": true }, "references": [ { diff --git a/packages/plugin-svgr/src/index.ts b/packages/plugin-svgr/src/index.ts index 7e1ae7f8c2..c0445853d5 100644 --- a/packages/plugin-svgr/src/index.ts +++ b/packages/plugin-svgr/src/index.ts @@ -6,7 +6,7 @@ import type { Config } from '@svgr/core'; export type SvgDefaultExport = 'component' | 'url'; -export const SVG_REGEX = /\.svg$/; +export const SVG_REGEX: RegExp = /\.svg$/; export type PluginSvgrOptions = { /** diff --git a/packages/plugin-svgr/tsconfig.json b/packages/plugin-svgr/tsconfig.json index d5ea9774d9..aa2ba97823 100644 --- a/packages/plugin-svgr/tsconfig.json +++ b/packages/plugin-svgr/tsconfig.json @@ -4,7 +4,8 @@ "outDir": "./dist", "baseUrl": "./", "rootDir": "src", - "composite": true + "composite": true, + "isolatedDeclarations": true }, "references": [ { diff --git a/packages/plugin-toml/tsconfig.json b/packages/plugin-toml/tsconfig.json index 68290500b9..c695a9910b 100644 --- a/packages/plugin-toml/tsconfig.json +++ b/packages/plugin-toml/tsconfig.json @@ -4,7 +4,8 @@ "outDir": "./dist", "baseUrl": "./", "rootDir": "src", - "composite": true + "composite": true, + "isolatedDeclarations": true }, "references": [ { diff --git a/packages/plugin-type-check/tsconfig.json b/packages/plugin-type-check/tsconfig.json index bd055d67fb..ab0cd0308f 100644 --- a/packages/plugin-type-check/tsconfig.json +++ b/packages/plugin-type-check/tsconfig.json @@ -4,7 +4,8 @@ "outDir": "./dist", "baseUrl": "./", "rootDir": "src", - "composite": true + "composite": true, + "isolatedDeclarations": true }, "references": [ { diff --git a/packages/plugin-typed-css-modules/src/loader.ts b/packages/plugin-typed-css-modules/src/loader.ts index 97a5150c75..95512f6f34 100644 --- a/packages/plugin-typed-css-modules/src/loader.ts +++ b/packages/plugin-typed-css-modules/src/loader.ts @@ -33,7 +33,10 @@ const getNoDeclarationFileError = ({ filename }: { filename: string }) => `Generated type declaration does not exist. Run Rsbuild and commit the type declaration for '${filename}'`, ); -export const isCSSModules = (filename: string, modules: CssLoaderModules) => { +export const isCSSModules = ( + filename: string, + modules: CssLoaderModules, +): boolean => { if (typeof modules === 'boolean') { return modules; } @@ -85,7 +88,7 @@ const getTypeMismatchError = ({ ); }; -export function wrapQuotes(key: string) { +export function wrapQuotes(key: string): string { // Check if key is a valid identifier const isValidIdentifier = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(key); if (isValidIdentifier) { @@ -135,7 +138,11 @@ const validModes = ['emit', 'verify']; const isFileNotFound = (err?: { code: string }) => err && err.code === 'ENOENT'; -const makeDoneHandlers = (callback: any, content: string, rest: any[]) => ({ +const makeDoneHandlers = ( + callback: (...args: any[]) => void, + content: string, + rest: any[], +) => ({ failed: (e: Error) => callback(e), success: () => callback(null, content, ...rest), }); @@ -203,18 +210,20 @@ export default function ( }>, content: string, ...rest: any[] -) { +): void { const { failed, success } = makeDoneHandlers(this.async(), content, rest); const filename = this.resourcePath; const { mode = 'emit', modules = true } = this.getOptions() || {}; if (!validModes.includes(mode)) { - return failed(new Error(`Invalid mode option: ${mode}`)); + failed(new Error(`Invalid mode option: ${mode}`)); + return; } if (!isCSSModules(filename, modules) || isInNodeModules(filename)) { - return success(); + success(); + return; } const cssModuleInterfaceFilename = filenameToTypingsFilename(filename); diff --git a/packages/plugin-typed-css-modules/tsconfig.json b/packages/plugin-typed-css-modules/tsconfig.json index bd055d67fb..ab0cd0308f 100644 --- a/packages/plugin-typed-css-modules/tsconfig.json +++ b/packages/plugin-typed-css-modules/tsconfig.json @@ -4,7 +4,8 @@ "outDir": "./dist", "baseUrl": "./", "rootDir": "src", - "composite": true + "composite": true, + "isolatedDeclarations": true }, "references": [ { diff --git a/packages/plugin-umd/tsconfig.json b/packages/plugin-umd/tsconfig.json index bd055d67fb..ab0cd0308f 100644 --- a/packages/plugin-umd/tsconfig.json +++ b/packages/plugin-umd/tsconfig.json @@ -4,7 +4,8 @@ "outDir": "./dist", "baseUrl": "./", "rootDir": "src", - "composite": true + "composite": true, + "isolatedDeclarations": true }, "references": [ { diff --git a/packages/plugin-vue-jsx/tsconfig.json b/packages/plugin-vue-jsx/tsconfig.json index 334a8faccc..755b6f1eee 100644 --- a/packages/plugin-vue-jsx/tsconfig.json +++ b/packages/plugin-vue-jsx/tsconfig.json @@ -4,7 +4,8 @@ "outDir": "./dist", "baseUrl": "./", "rootDir": "src", - "composite": true + "composite": true, + "isolatedDeclarations": true }, "references": [ { diff --git a/packages/plugin-vue/tsconfig.json b/packages/plugin-vue/tsconfig.json index bd055d67fb..ab0cd0308f 100644 --- a/packages/plugin-vue/tsconfig.json +++ b/packages/plugin-vue/tsconfig.json @@ -4,7 +4,8 @@ "outDir": "./dist", "baseUrl": "./", "rootDir": "src", - "composite": true + "composite": true, + "isolatedDeclarations": true }, "references": [ { diff --git a/packages/plugin-vue2-jsx/tsconfig.json b/packages/plugin-vue2-jsx/tsconfig.json index 334a8faccc..755b6f1eee 100644 --- a/packages/plugin-vue2-jsx/tsconfig.json +++ b/packages/plugin-vue2-jsx/tsconfig.json @@ -4,7 +4,8 @@ "outDir": "./dist", "baseUrl": "./", "rootDir": "src", - "composite": true + "composite": true, + "isolatedDeclarations": true }, "references": [ { diff --git a/packages/plugin-vue2/src/VueLoader15PitchFixPlugin.ts b/packages/plugin-vue2/src/VueLoader15PitchFixPlugin.ts index 25a6f66cde..6538742ce9 100644 --- a/packages/plugin-vue2/src/VueLoader15PitchFixPlugin.ts +++ b/packages/plugin-vue2/src/VueLoader15PitchFixPlugin.ts @@ -6,7 +6,7 @@ import type { Rspack } from '@rsbuild/core'; export class VueLoader15PitchFixPlugin implements Rspack.RspackPluginInstance { readonly name = 'VueLoader15PitchFixPlugin'; - apply(compiler: Rspack.Compiler) { + apply(compiler: Rspack.Compiler): void { const { NormalModule } = compiler.webpack; compiler.hooks.compilation.tap(this.name, (compilation) => { const isExpCssOn = compilation.compiler.options?.experiments?.css; diff --git a/packages/plugin-vue2/src/splitChunks.ts b/packages/plugin-vue2/src/splitChunks.ts index f83e81a527..1f44608afe 100644 --- a/packages/plugin-vue2/src/splitChunks.ts +++ b/packages/plugin-vue2/src/splitChunks.ts @@ -13,7 +13,7 @@ export const applySplitChunksRule = ( vue: true, router: true, }, -) => { +): void => { api.modifyBundlerChain((chain, { environment }) => { const config = api.getNormalizedConfig({ environment }); if (config.performance.chunkSplit.strategy !== 'split-by-experience') { diff --git a/packages/plugin-vue2/tsconfig.json b/packages/plugin-vue2/tsconfig.json index bd055d67fb..ab0cd0308f 100644 --- a/packages/plugin-vue2/tsconfig.json +++ b/packages/plugin-vue2/tsconfig.json @@ -4,7 +4,8 @@ "outDir": "./dist", "baseUrl": "./", "rootDir": "src", - "composite": true + "composite": true, + "isolatedDeclarations": true }, "references": [ { diff --git a/packages/plugin-yaml/tsconfig.json b/packages/plugin-yaml/tsconfig.json index 68290500b9..c695a9910b 100644 --- a/packages/plugin-yaml/tsconfig.json +++ b/packages/plugin-yaml/tsconfig.json @@ -4,7 +4,8 @@ "outDir": "./dist", "baseUrl": "./", "rootDir": "src", - "composite": true + "composite": true, + "isolatedDeclarations": true }, "references": [ { diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index f30bccf281..20e2f4b837 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -8,10 +8,10 @@ import type { NormalizedEnvironmentConfig, RsbuildContext } from './types'; export * from './types'; // RegExp -export const JS_REGEX = /\.(?:js|mjs|cjs|jsx)$/; -export const SCRIPT_REGEX = /\.(?:js|jsx|mjs|cjs|ts|tsx|mts|cts)$/; -export const TS_AND_JSX_REGEX = /\.(?:ts|tsx|jsx|mts|cts)$/; -export const NODE_MODULES_REGEX = /[\\/]node_modules[\\/]/; +export const JS_REGEX: RegExp = /\.(?:js|mjs|cjs|jsx)$/; +export const SCRIPT_REGEX: RegExp = /\.(?:js|jsx|mjs|cjs|ts|tsx|mts|cts)$/; +export const TS_AND_JSX_REGEX: RegExp = /\.(?:ts|tsx|jsx|mts|cts)$/; +export const NODE_MODULES_REGEX: RegExp = /[\\/]node_modules[\\/]/; enum ESVersion { es5 = 5, @@ -35,7 +35,7 @@ const renameBrowser = (name: string) => { return name === 'ios_saf' ? 'safari' : name; }; -export function browserslistToESVersion(browsers: string[]) { +export function browserslistToESVersion(browsers: string[]): ESVersion { const projectBrowsers = browserslist(browsers, { ignoreUnknownVersions: true, }); @@ -110,7 +110,7 @@ const DEP_MATCH_TEMPLATE = /[\\/]node_modules[\\/]()[\\/]/.source; /** Expect to match path just like "./node_modules/react-router/" */ export const createDependenciesRegExp = ( ...dependencies: (string | RegExp)[] -) => { +): RegExp => { const sources = dependencies.map((d) => typeof d === 'string' ? d : d.source, ); @@ -311,7 +311,7 @@ export function applyScriptCondition({ context: RsbuildContext; includes: (string | RegExp)[]; excludes: (string | RegExp)[]; -}) { +}): void { // compile all folders in app directory, exclude node_modules // which can be removed next version of rspack rule.include.add({ diff --git a/packages/shared/tsconfig.json b/packages/shared/tsconfig.json index 3a4fff4249..5c4c4406e1 100644 --- a/packages/shared/tsconfig.json +++ b/packages/shared/tsconfig.json @@ -5,7 +5,8 @@ "declarationDir": "./dist-types", "baseUrl": "./", "rootDir": "src", - "composite": true + "composite": true, + "isolatedDeclarations": true }, "include": ["src"] }