diff --git a/lib/bootstrap.ts b/lib/bootstrap.ts index ca8fe39888..ad181a1062 100644 --- a/lib/bootstrap.ts +++ b/lib/bootstrap.ts @@ -414,8 +414,8 @@ injector.require( injector.requirePublic("cleanupService", "./services/cleanup-service"); injector.require( - "webpackCompilerService", - "./services/webpack/webpack-compiler-service", + "bundlerCompilerService", + "./services/bundler/bundler-compiler-service", ); injector.require( diff --git a/lib/constants.ts b/lib/constants.ts index 0ac436ec77..b9dc247d83 100644 --- a/lib/constants.ts +++ b/lib/constants.ts @@ -16,6 +16,7 @@ export const SCOPED_TNS_CORE_MODULES = "@nativescript/core"; export const TNS_CORE_THEME_NAME = "nativescript-theme-core"; export const SCOPED_TNS_CORE_THEME_NAME = "@nativescript/theme"; export const WEBPACK_PLUGIN_NAME = "@nativescript/webpack"; +export const RSPACK_PLUGIN_NAME = "@nativescript/rspack"; export const TNS_CORE_MODULES_WIDGETS_NAME = "tns-core-modules-widgets"; export const UI_MOBILE_BASE_NAME = "@nativescript/ui-mobile-base"; export const TNS_ANDROID_RUNTIME_NAME = "tns-android"; @@ -36,6 +37,7 @@ export const XML_FILE_EXTENSION = ".xml"; export const PLATFORMS_DIR_NAME = "platforms"; export const HOOKS_DIR_NAME = "hooks"; export const WEBPACK_CONFIG_NAME = "webpack.config.js"; +export const RSPACK_CONFIG_NAME = "rspack.config.js"; export const TSCCONFIG_TNS_JSON_NAME = "tsconfig.tns.json"; export const KARMA_CONFIG_NAME = "karma.conf.js"; export const LIB_DIR_NAME = "lib"; @@ -223,6 +225,7 @@ export const FILES_CHANGE_EVENT_NAME = "filesChangeEvent"; export const INITIAL_SYNC_EVENT_NAME = "initialSyncEvent"; export const PREPARE_READY_EVENT_NAME = "prepareReadyEvent"; export const WEBPACK_COMPILATION_COMPLETE = "webpackCompilationComplete"; +export const BUNDLER_COMPILATION_COMPLETE = "bundlerCompilationComplete"; export class DebugCommandErrors { public static UNABLE_TO_USE_FOR_DEVICE_AND_EMULATOR = diff --git a/lib/controllers/prepare-controller.ts b/lib/controllers/prepare-controller.ts index 8ba3550b86..7b21219f63 100644 --- a/lib/controllers/prepare-controller.ts +++ b/lib/controllers/prepare-controller.ts @@ -67,7 +67,7 @@ export class PrepareController extends EventEmitter { private $prepareNativePlatformService: IPrepareNativePlatformService, private $projectChangesService: IProjectChangesService, private $projectDataService: IProjectDataService, - private $webpackCompilerService: IWebpackCompilerService, + private $bundlerCompilerService: IBundlerCompilerService, private $watchIgnoreListService: IWatchIgnoreListService, private $analyticsService: IAnalyticsService, private $markingModeService: IMarkingModeService, @@ -117,8 +117,8 @@ export class PrepareController extends EventEmitter { this.watchersData[projectDir][platformLowerCase] && this.watchersData[projectDir][platformLowerCase].hasWebpackCompilerProcess ) { - await this.$webpackCompilerService.stopWebpackCompiler(platformLowerCase); - this.$webpackCompilerService.removeListener( + await this.$bundlerCompilerService.stopBundlerCompiler(platformLowerCase); + this.$bundlerCompilerService.removeListener( WEBPACK_COMPILATION_COMPLETE, this.webpackCompilerHandler, ); @@ -177,7 +177,7 @@ export class PrepareController extends EventEmitter { prepareData, ); } else { - await this.$webpackCompilerService.compileWithoutWatch( + await this.$bundlerCompilerService.compileWithoutWatch( platformData, projectData, prepareData, @@ -296,7 +296,7 @@ export class PrepareController extends EventEmitter { }; this.webpackCompilerHandler = handler.bind(this); - this.$webpackCompilerService.on( + this.$bundlerCompilerService.on( WEBPACK_COMPILATION_COMPLETE, this.webpackCompilerHandler, ); @@ -304,7 +304,7 @@ export class PrepareController extends EventEmitter { this.watchersData[projectData.projectDir][ platformData.platformNameLowerCase ].hasWebpackCompilerProcess = true; - await this.$webpackCompilerService.compileWithWatch( + await this.$bundlerCompilerService.compileWithWatch( platformData, projectData, prepareData, @@ -560,7 +560,7 @@ export class PrepareController extends EventEmitter { if (this.pausedFileWatch) { for (const watcher of watchers) { for (const platform in watcher) { - await this.$webpackCompilerService.stopWebpackCompiler(platform); + await this.$bundlerCompilerService.stopBundlerCompiler(platform); watcher[platform].hasWebpackCompilerProcess = false; } } @@ -569,7 +569,7 @@ export class PrepareController extends EventEmitter { for (const platform in watcher) { const args = watcher[platform].prepareArguments; watcher[platform].hasWebpackCompilerProcess = true; - await this.$webpackCompilerService.compileWithWatch( + await this.$bundlerCompilerService.compileWithWatch( args.platformData, args.projectData, args.prepareData, diff --git a/lib/definitions/project.d.ts b/lib/definitions/project.d.ts index e99e204691..c8046b2ed4 100644 --- a/lib/definitions/project.d.ts +++ b/lib/definitions/project.d.ts @@ -121,6 +121,7 @@ export interface IOSLocalSPMPackage extends IOSSPMPackageBase { } export type IOSSPMPackage = IOSRemoteSPMPackage | IOSLocalSPMPackage; +export type BundlerType = "webpack" | "rspack" | "vite"; interface INsConfigIOS extends INsConfigPlaform { discardUncaughtJsExceptions?: boolean; @@ -182,6 +183,8 @@ interface INsConfig { shared?: boolean; overridePods?: string; webpackConfigPath?: string; + bundlerConfigPath?: string; + bundler?: BundlerType; ios?: INsConfigIOS; android?: INsConfigAndroid; visionos?: INSConfigVisionOS; @@ -215,13 +218,28 @@ interface IProjectData extends ICreateProjectData { * Value is true when project has nativescript.config and it has `shared: true` in it. */ isShared: boolean; - /** + * Specifies the bundler used to build the application. + * + * - `"webpack"`: Uses Webpack for traditional bundling. + * - `"rspack"`: Uses Rspack for fast bundling. + * - `"vite"`: Uses Vite for fast bundling. + * + * @default "webpack" + */ + bundler: BundlerType; + /** + * @deprecated Use bundlerConfigPath * Defines the path to the configuration file passed to webpack process. * By default this is the webpack.config.js at the root of the application. * The value can be changed by setting `webpackConfigPath` in nativescript.config. */ webpackConfigPath: string; + /** + * Defines the path to the bundler configuration file passed to the compiler. + * The value can be changed by setting `bundlerConfigPath` in nativescript.config. + */ + bundlerConfigPath: string; projectName: string; /** diff --git a/lib/project-data.ts b/lib/project-data.ts index 3e36c374b5..277dbf32d1 100644 --- a/lib/project-data.ts +++ b/lib/project-data.ts @@ -5,6 +5,7 @@ import { parseJson } from "./common/helpers"; import { EOL } from "os"; import { cache } from "./common/decorators"; import { + BundlerType, INsConfig, IProjectConfigService, IProjectData, @@ -99,6 +100,8 @@ export class ProjectData implements IProjectData { public podfilePath: string; public isShared: boolean; public webpackConfigPath: string; + public bundlerConfigPath: string; + public bundler: BundlerType; public initialized: boolean; constructor( @@ -110,7 +113,7 @@ export class ProjectData implements IProjectData { private $logger: ILogger, private $injector: IInjector, private $androidResourcesMigrationService: IAndroidResourcesMigrationService, - private $devicePlatformsConstants: Mobile.IDevicePlatformsConstants + private $devicePlatformsConstants: Mobile.IDevicePlatformsConstants, ) {} get projectConfig(): IProjectConfigService { @@ -142,7 +145,7 @@ export class ProjectData implements IProjectData { public initializeProjectDataFromContent( packageJsonContent: string, - projectDir?: string + projectDir?: string, ): void { projectDir = projectDir || this.$projectHelper.projectDir || ""; this.projectDir = projectDir; @@ -157,7 +160,7 @@ export class ProjectData implements IProjectData { this.$errors.fail( `The project file ${this.projectFilePath} is corrupted. ${EOL}` + `Consider restoring an earlier version from your source control or backup.${EOL}` + - `Additional technical info: ${err.toString()}` + `Additional technical info: ${err.toString()}`, ); } @@ -178,36 +181,43 @@ export class ProjectData implements IProjectData { this.appDirectoryPath = this.getAppDirectoryPath(); this.appResourcesDirectoryPath = this.getAppResourcesDirectoryPath(); this.androidManifestPath = this.getPathToAndroidManifest( - this.appResourcesDirectoryPath + this.appResourcesDirectoryPath, ); this.gradleFilesDirectoryPath = path.join( this.appResourcesDirectoryPath, - this.$devicePlatformsConstants.Android + this.$devicePlatformsConstants.Android, ); this.appGradlePath = path.join( this.gradleFilesDirectoryPath, - constants.APP_GRADLE_FILE_NAME + constants.APP_GRADLE_FILE_NAME, ); this.infoPlistPath = path.join( this.appResourcesDirectoryPath, this.$devicePlatformsConstants.iOS, - constants.INFO_PLIST_FILE_NAME + constants.INFO_PLIST_FILE_NAME, ); this.buildXcconfigPath = path.join( this.appResourcesDirectoryPath, this.$devicePlatformsConstants.iOS, - constants.BUILD_XCCONFIG_FILE_NAME + constants.BUILD_XCCONFIG_FILE_NAME, ); this.podfilePath = path.join( this.appResourcesDirectoryPath, this.$devicePlatformsConstants.iOS, - constants.PODFILE_NAME + constants.PODFILE_NAME, ); this.isShared = !!(this.nsConfig && this.nsConfig.shared); - this.webpackConfigPath = + + const webpackConfigPath = this.nsConfig && this.nsConfig.webpackConfigPath ? path.resolve(this.projectDir, this.nsConfig.webpackConfigPath) : path.join(this.projectDir, "webpack.config.js"); + this.webpackConfigPath = webpackConfigPath; + this.bundlerConfigPath = + this.nsConfig && this.nsConfig.bundlerConfigPath + ? path.resolve(this.projectDir, this.nsConfig.bundlerConfigPath) + : webpackConfigPath; + this.bundler = this?.nsConfig?.bundler ?? "webpack"; return; } @@ -217,7 +227,7 @@ export class ProjectData implements IProjectData { private getPathToAndroidManifest(appResourcesDir: string): string { const androidDirPath = path.join( appResourcesDir, - this.$devicePlatformsConstants.Android + this.$devicePlatformsConstants.Android, ); const androidManifestDir = this.$androidResourcesMigrationService.hasMigrated(appResourcesDir) @@ -230,13 +240,13 @@ export class ProjectData implements IProjectData { private errorInvalidProject(projectDir: string): void { const currentDir = path.resolve("."); this.$logger.trace( - `Unable to find project. projectDir: ${projectDir}, options.path: ${this.$options.path}, ${currentDir}` + `Unable to find project. projectDir: ${projectDir}, options.path: ${this.$options.path}, ${currentDir}`, ); // This is the case when no project file found this.$errors.fail( "No project found at or above '%s' and neither was a --path specified.", - projectDir || this.$options.path || currentDir + projectDir || this.$options.path || currentDir, ); } @@ -291,7 +301,7 @@ export class ProjectData implements IProjectData { private resolveToProjectDir( pathToResolve: string, - projectDir?: string + projectDir?: string, ): string { if (!projectDir) { projectDir = this.projectDir; @@ -306,7 +316,7 @@ export class ProjectData implements IProjectData { @cache() private initializeProjectIdentifiers( - config: INsConfig + config: INsConfig, ): Mobile.IProjectIdentifier { this.$logger.trace(`Initializing project identifiers. Config: `, config); @@ -341,18 +351,18 @@ export class ProjectData implements IProjectData { private getProjectType(): string { let detectedProjectType = _.find( ProjectData.PROJECT_TYPES, - (projectType) => projectType.isDefaultProjectType + (projectType) => projectType.isDefaultProjectType, ).type; const deps: string[] = _.keys(this.dependencies).concat( - _.keys(this.devDependencies) + _.keys(this.devDependencies), ); _.each(ProjectData.PROJECT_TYPES, (projectType) => { if ( _.some( projectType.requiredDependencies, - (requiredDependency) => deps.indexOf(requiredDependency) !== -1 + (requiredDependency) => deps.indexOf(requiredDependency) !== -1, ) ) { detectedProjectType = projectType.type; @@ -366,7 +376,7 @@ export class ProjectData implements IProjectData { @cache() private warnProjectId(): void { this.$logger.warn( - "[WARNING]: IProjectData.projectId is deprecated. Please use IProjectData.projectIdentifiers[platform]." + "[WARNING]: IProjectData.projectId is deprecated. Please use IProjectData.projectIdentifiers[platform].", ); } } diff --git a/lib/services/webpack/webpack-compiler-service.ts b/lib/services/bundler/bundler-compiler-service.ts similarity index 69% rename from lib/services/webpack/webpack-compiler-service.ts rename to lib/services/bundler/bundler-compiler-service.ts index 323899793a..65b496a2b3 100644 --- a/lib/services/webpack/webpack-compiler-service.ts +++ b/lib/services/bundler/bundler-compiler-service.ts @@ -5,8 +5,8 @@ import * as _ from "lodash"; import { EventEmitter } from "events"; import { performanceLog } from "../../common/decorators"; import { - WEBPACK_COMPILATION_COMPLETE, WEBPACK_PLUGIN_NAME, + BUNDLER_COMPILATION_COMPLETE, PackageManagers, CONFIG_FILE_NAME_DISPLAY, } from "../../constants"; @@ -16,7 +16,11 @@ import { IOptions, } from "../../declarations"; import { IPlatformData } from "../../definitions/platform"; -import { IProjectData } from "../../definitions/project"; +import { + BundlerType, + IProjectConfigService, + IProjectData, +} from "../../definitions/project"; import { IDictionary, IErrors, @@ -34,23 +38,23 @@ import { } from "../../helpers/package-path-helper"; // todo: move out of here -interface IWebpackMessage { +interface IBundlerMessage { type: "compilation" | "hmr-status"; version?: number; hash?: string; data?: T; } -interface IWebpackCompilation { +interface IBundlerCompilation { emittedAssets: string[]; staleAssets: string[]; } -export class WebpackCompilerService +export class BundlerCompilerService extends EventEmitter - implements IWebpackCompilerService + implements IBundlerCompilerService { - private webpackProcesses: IDictionary = {}; + private bundlerProcesses: IDictionary = {}; private expectedHashes: IStringDictionary = {}; constructor( @@ -64,7 +68,8 @@ export class WebpackCompilerService private $mobileHelper: Mobile.IMobileHelper, private $cleanupService: ICleanupService, private $packageManager: IPackageManager, - private $packageInstallationManager: IPackageInstallationManager // private $sharedEventBus: ISharedEventBus + private $packageInstallationManager: IPackageInstallationManager, + private $projectConfigService: IProjectConfigService, ) { super(); } @@ -72,21 +77,21 @@ export class WebpackCompilerService public async compileWithWatch( platformData: IPlatformData, projectData: IProjectData, - prepareData: IPrepareData + prepareData: IPrepareData, ): Promise { return new Promise(async (resolve, reject) => { - if (this.webpackProcesses[platformData.platformNameLowerCase]) { + if (this.bundlerProcesses[platformData.platformNameLowerCase]) { resolve(void 0); return; } - let isFirstWebpackWatchCompilation = true; + let isFirstBundlerWatchCompilation = true; prepareData.watch = true; try { - const childProcess = await this.startWebpackProcess( + const childProcess = await this.startBundleProcess( platformData, projectData, - prepareData + prepareData, ); childProcess.stdout.on("data", function (data) { @@ -97,8 +102,8 @@ export class WebpackCompilerService process.stderr.write(data); }); - childProcess.on("message", (message: string | IWebpackEmitMessage) => { - this.$logger.trace("Message from webpack", message); + childProcess.on("message", (message: string | IBundlerEmitMessage) => { + this.$logger.trace(`Message from ${projectData.bundler}`, message); // if we are on webpack5 - we handle HMR in a slightly different way if ( @@ -108,8 +113,8 @@ export class WebpackCompilerService ) { // first compilation can be ignored because it will be synced regardless // handling it here would trigger 2 syncs - if (isFirstWebpackWatchCompilation) { - isFirstWebpackWatchCompilation = false; + if (isFirstBundlerWatchCompilation) { + isFirstBundlerWatchCompilation = false; resolve(childProcess); return; } @@ -122,22 +127,27 @@ export class WebpackCompilerService // } return this.handleHMRMessage( - message as IWebpackMessage, + message as IBundlerMessage, platformData, projectData, - prepareData + prepareData, ); } - if (message === "Webpack compilation complete.") { - this.$logger.info("Webpack build done!"); + if ( + message === + `${capitalizeFirstLetter(projectData.bundler)} compilation complete.` + ) { + this.$logger.info( + `${capitalizeFirstLetter(projectData.bundler)} build done!`, + ); resolve(childProcess); } - message = message as IWebpackEmitMessage; + message = message as IBundlerEmitMessage; if (message.emittedFiles) { - if (isFirstWebpackWatchCompilation) { - isFirstWebpackWatchCompilation = false; + if (isFirstBundlerWatchCompilation) { + isFirstBundlerWatchCompilation = false; this.expectedHashes[platformData.platformNameLowerCase] = prepareData.hmr ? message.hash : ""; return; @@ -153,7 +163,7 @@ export class WebpackCompilerService message.emittedFiles, message.chunkFiles, message.hash, - platformData.platformNameLowerCase + platformData.platformNameLowerCase, ); } else { result = { @@ -166,21 +176,21 @@ export class WebpackCompilerService path.join( platformData.appDestinationDirectoryPath, this.$options.hostProjectModuleName, - file - ) + file, + ), ); const fallbackFiles = result.fallbackFiles.map((file: string) => path.join( platformData.appDestinationDirectoryPath, this.$options.hostProjectModuleName, - file - ) + file, + ), ); const data = { files, hasOnlyHotUpdateFiles: files.every( - (f) => f.indexOf("hot-update") > -1 + (f) => f.indexOf("hot-update") > -1, ), hmrData: { hash: result.hash, @@ -189,7 +199,10 @@ export class WebpackCompilerService platform: platformData.platformNameLowerCase, }; - this.$logger.trace("Generated data from webpack message:", data); + this.$logger.trace( + `Generated data from ${projectData.bundler} message:`, + data, + ); // the hash of the compilation is the same as the previous one and there are only hot updates produced if (data.hasOnlyHotUpdateFiles && previousHash === message.hash) { @@ -197,33 +210,33 @@ export class WebpackCompilerService } if (data.files.length) { - this.emit(WEBPACK_COMPILATION_COMPLETE, data); + this.emit(BUNDLER_COMPILATION_COMPLETE, data); } } }); childProcess.on("error", (err) => { this.$logger.trace( - `Unable to start webpack process in watch mode. Error is: ${err}` + `Unable to start ${projectData.bundler} process in watch mode. Error is: ${err}`, ); - delete this.webpackProcesses[platformData.platformNameLowerCase]; + delete this.bundlerProcesses[platformData.platformNameLowerCase]; reject(err); }); childProcess.on("close", async (arg: any) => { await this.$cleanupService.removeKillProcess( - childProcess.pid.toString() + childProcess.pid.toString(), ); const exitCode = typeof arg === "number" ? arg : arg && arg.code; this.$logger.trace( - `Webpack process exited with code ${exitCode} when we expected it to be long living with watch.` + `${capitalizeFirstLetter(projectData.bundler)} process exited with code ${exitCode} when we expected it to be long living with watch.`, ); const error: any = new Error( - `Executing webpack failed with exit code ${exitCode}.` + `Executing ${projectData.bundler} failed with exit code ${exitCode}.`, ); error.code = exitCode; - delete this.webpackProcesses[platformData.platformNameLowerCase]; + delete this.bundlerProcesses[platformData.platformNameLowerCase]; reject(error); }); } catch (err) { @@ -235,41 +248,41 @@ export class WebpackCompilerService public async compileWithoutWatch( platformData: IPlatformData, projectData: IProjectData, - prepareData: IPrepareData + prepareData: IPrepareData, ): Promise { return new Promise(async (resolve, reject) => { - if (this.webpackProcesses[platformData.platformNameLowerCase]) { + if (this.bundlerProcesses[platformData.platformNameLowerCase]) { resolve(); return; } try { - const childProcess = await this.startWebpackProcess( + const childProcess = await this.startBundleProcess( platformData, projectData, - prepareData + prepareData, ); childProcess.on("error", (err) => { this.$logger.trace( - `Unable to start webpack process in non-watch mode. Error is: ${err}` + `Unable to start ${projectData.bundler} process in non-watch mode. Error is: ${err}`, ); - delete this.webpackProcesses[platformData.platformNameLowerCase]; + delete this.bundlerProcesses[platformData.platformNameLowerCase]; reject(err); }); childProcess.on("close", async (arg: any) => { await this.$cleanupService.removeKillProcess( - childProcess.pid.toString() + childProcess.pid.toString(), ); - delete this.webpackProcesses[platformData.platformNameLowerCase]; + delete this.bundlerProcesses[platformData.platformNameLowerCase]; const exitCode = typeof arg === "number" ? arg : arg && arg.code; if (exitCode === 0) { resolve(); } else { const error: any = new Error( - `Executing webpack failed with exit code ${exitCode}.` + `Executing ${projectData.bundler} failed with exit code ${exitCode}.`, ); error.code = exitCode; reject(error); @@ -281,14 +294,14 @@ export class WebpackCompilerService }); } - public async stopWebpackCompiler(platform: string): Promise { + public async stopBundlerCompiler(platform: string): Promise { if (platform) { - await this.stopWebpackForPlatform(platform); + await this.stopBundlerForPlatform(platform); } else { - const webpackedPlatforms = Object.keys(this.webpackProcesses); + const bundlerPlatforms = Object.keys(this.bundlerProcesses); - for (let i = 0; i < webpackedPlatforms.length; i++) { - await this.stopWebpackForPlatform(webpackedPlatforms[i]); + for (let i = 0; i < bundlerPlatforms.length; i++) { + await this.stopBundlerForPlatform(bundlerPlatforms[i]); } } } @@ -304,27 +317,35 @@ export class WebpackCompilerService } @performanceLog() - private async startWebpackProcess( + private async startBundleProcess( platformData: IPlatformData, projectData: IProjectData, - prepareData: IPrepareData + prepareData: IPrepareData, ): Promise { - if (!this.$fs.exists(projectData.webpackConfigPath)) { - this.$errors.fail( - `The webpack configuration file ${projectData.webpackConfigPath} does not exist. Ensure the file exists, or update the path in ${CONFIG_FILE_NAME_DISPLAY}.` - ); + if (projectData.bundlerConfigPath) { + if (!this.$fs.exists(projectData.bundlerConfigPath)) { + this.$errors.fail( + `The bundler configuration file ${projectData.bundlerConfigPath} does not exist. Ensure the file exists, or update the path in ${CONFIG_FILE_NAME_DISPLAY}.`, + ); + } + } else { + if (!this.$fs.exists(projectData.bundlerConfigPath)) { + this.$errors.fail( + `The ${projectData.bundler} configuration file ${projectData.bundlerConfigPath} does not exist. Ensure the file exists, or update the path in ${CONFIG_FILE_NAME_DISPLAY}.`, + ); + } } const envData = this.buildEnvData( platformData.platformNameLowerCase, projectData, - prepareData + prepareData, ); const envParams = await this.buildEnvCommandLineParams( envData, platformData, projectData, - prepareData + prepareData, ); const additionalNodeArgs = semver.major(process.version) <= 8 ? ["--harmony"] : []; @@ -339,9 +360,9 @@ export class WebpackCompilerService const args = [ ...additionalNodeArgs, - this.getWebpackExecutablePath(projectData), - this.isWebpack5(projectData) ? `build` : null, - `--config=${projectData.webpackConfigPath}`, + this.getBundlerExecutablePath(projectData), + this.isModernBundler(projectData) ? `build` : null, + `--config=${projectData.bundlerConfigPath}`, ...envParams, ].filter(Boolean); @@ -356,6 +377,7 @@ export class WebpackCompilerService }; options.env = { NATIVESCRIPT_WEBPACK_ENV: JSON.stringify(envData), + NATIVESCRIPT_BUNDLER_ENV: JSON.stringify(envData), }; if (this.$hostInfo.isWindows) { Object.assign(options.env, { APPDATA: process.env.appData }); @@ -372,10 +394,10 @@ export class WebpackCompilerService const childProcess = this.$childProcess.spawn( process.execPath, args, - options + options, ); - this.webpackProcesses[platformData.platformNameLowerCase] = childProcess; + this.bundlerProcesses[platformData.platformNameLowerCase] = childProcess; await this.$cleanupService.addKillProcess(childProcess.pid.toString()); return childProcess; @@ -384,7 +406,7 @@ export class WebpackCompilerService private buildEnvData( platform: string, projectData: IProjectData, - prepareData: IPrepareData + prepareData: IPrepareData, ) { const { env } = prepareData; const envData = Object.assign({}, env, { [platform.toLowerCase()]: true }); @@ -403,9 +425,9 @@ export class WebpackCompilerService __dirname, "..", "..", - "nativescript-cli-lib.js" + "nativescript-cli-lib.js", ), - } + }, ); envData.verbose = envData.verbose || this.$logger.isVerbose(); @@ -452,7 +474,7 @@ export class WebpackCompilerService envData: any, platformData: IPlatformData, projectData: IProjectData, - prepareData: IPrepareData + prepareData: IPrepareData, ) { const envFlagNames = Object.keys(envData); const canSnapshot = @@ -462,27 +484,30 @@ export class WebpackCompilerService if (!canSnapshot) { this.$logger.warn( "Stripping the snapshot flag. " + - "Bear in mind that snapshot is only available in Android release builds." + "Bear in mind that snapshot is only available in Android release builds.", ); envFlagNames.splice(envFlagNames.indexOf("snapshot"), 1); } else if (this.$hostInfo.isWindows) { - const minWebpackPluginWithWinSnapshotsVersion = "1.3.0"; - const installedWebpackPluginVersion = - await this.$packageInstallationManager.getInstalledDependencyVersion( - WEBPACK_PLUGIN_NAME, - projectData.projectDir - ); - const hasWebpackPluginWithWinSnapshotsSupport = - !!installedWebpackPluginVersion - ? semver.gte( - semver.coerce(installedWebpackPluginVersion), - minWebpackPluginWithWinSnapshotsVersion - ) - : true; - if (!hasWebpackPluginWithWinSnapshotsSupport) { - this.$errors.fail( - `In order to generate Snapshots on Windows, please upgrade your Webpack plugin version (npm i ${WEBPACK_PLUGIN_NAME}@latest).` - ); + if (projectData.bundler === "webpack") { + //TODO: check this use case for webpack5 WEBPACK_PLUGIN_NAME + const minWebpackPluginWithWinSnapshotsVersion = "1.3.0"; + const installedWebpackPluginVersion = + await this.$packageInstallationManager.getInstalledDependencyVersion( + WEBPACK_PLUGIN_NAME, + projectData.projectDir, + ); + const hasWebpackPluginWithWinSnapshotsSupport = + !!installedWebpackPluginVersion + ? semver.gte( + semver.coerce(installedWebpackPluginVersion), + minWebpackPluginWithWinSnapshotsVersion, + ) + : true; + if (!hasWebpackPluginWithWinSnapshotsSupport) { + this.$errors.fail( + `In order to generate Snapshots on Windows, please upgrade your Webpack plugin version (npm i ${WEBPACK_PLUGIN_NAME}@latest).`, + ); + } } } } @@ -513,7 +538,7 @@ export class WebpackCompilerService allEmittedFiles: string[], chunkFiles: string[], nextHash: string, - platform: string + platform: string, ) { const currentHash = this.getCurrentHotUpdateHash(allEmittedFiles); @@ -535,7 +560,7 @@ export class WebpackCompilerService ? _.difference(allEmittedFiles, chunkFiles) : allEmittedFiles; const fallbackFiles = chunkFiles.concat( - emittedHotUpdatesAndAssets.filter((f) => f.indexOf("hot-update") === -1) + emittedHotUpdatesAndAssets.filter((f) => f.indexOf("hot-update") === -1), ); return { @@ -548,7 +573,7 @@ export class WebpackCompilerService private getCurrentHotUpdateHash(emittedFiles: string[]) { let hotHash; const hotUpdateScripts = emittedFiles.filter((x) => - x.endsWith(".hot-update.js") + x.endsWith(".hot-update.js"), ); if (hotUpdateScripts && hotUpdateScripts.length) { // the hash is the same for each hot update in the current compilation @@ -561,50 +586,57 @@ export class WebpackCompilerService return hotHash || ""; } - private async stopWebpackForPlatform(platform: string) { - this.$logger.trace(`Stopping webpack watch for platform ${platform}.`); - const webpackProcess = this.webpackProcesses[platform]; - await this.$cleanupService.removeKillProcess(webpackProcess.pid.toString()); - if (webpackProcess) { - webpackProcess.kill("SIGINT"); - delete this.webpackProcesses[platform]; + private async stopBundlerForPlatform(platform: string) { + this.$logger.trace( + `Stopping ${this.getBundler()} watch for platform ${platform}.`, + ); + const bundlerProcess = this.bundlerProcesses[platform]; + await this.$cleanupService.removeKillProcess(bundlerProcess.pid.toString()); + if (bundlerProcess) { + bundlerProcess.kill("SIGINT"); + delete this.bundlerProcesses[platform]; } } private handleHMRMessage( - message: IWebpackMessage, + message: IBundlerMessage, platformData: IPlatformData, projectData: IProjectData, - prepareData: IPrepareData + prepareData: IPrepareData, ) { - // handle new webpack hmr packets - this.$logger.trace("Received message from webpack process:", message); + // handle new bundler hmr packets + this.$logger.trace( + `Received message from ${projectData.bundler} process:`, + message, + ); if (message.type !== "compilation") { return; } - this.$logger.trace("Webpack build done!"); + this.$logger.trace( + `${capitalizeFirstLetter(projectData.bundler)} build done!`, + ); const files = message.data.emittedAssets.map((asset: string) => path.join( platformData.appDestinationDirectoryPath, this.$options.hostProjectModuleName, - asset - ) + asset, + ), ); const staleFiles = message.data.staleAssets.map((asset: string) => path.join( platformData.appDestinationDirectoryPath, this.$options.hostProjectModuleName, - asset - ) + asset, + ), ); // extract last hash from emitted filenames const lastHash = (() => { const absoluteFileNameWithLastHash = files.find((fileName: string) => - fileName.endsWith("hot-update.js") + fileName.endsWith("hot-update.js"), ); if (!absoluteFileNameWithLastHash) { @@ -623,7 +655,7 @@ export class WebpackCompilerService return; } - this.emit(WEBPACK_COMPILATION_COMPLETE, { + this.emit(BUNDLER_COMPILATION_COMPLETE, { files, staleFiles, hasOnlyHotUpdateFiles: prepareData.hmr, @@ -635,9 +667,11 @@ export class WebpackCompilerService }); } - private getWebpackExecutablePath(projectData: IProjectData): string { - if (this.isWebpack5(projectData)) { - const packagePath = resolvePackagePath("@nativescript/webpack", { + private getBundlerExecutablePath(projectData: IProjectData): string { + const bundler = this.getBundler(); + + if (this.isModernBundler(projectData)) { + const packagePath = resolvePackagePath(`@nativescript/${bundler}`, { paths: [projectData.projectDir], }); @@ -657,22 +691,37 @@ export class WebpackCompilerService return path.resolve(packagePath, "bin", "webpack.js"); } - private isWebpack5(projectData: IProjectData): boolean { - const packageJSONPath = resolvePackageJSONPath("@nativescript/webpack", { - paths: [projectData.projectDir], - }); + private isModernBundler(projectData: IProjectData): boolean { + const bundler = this.getBundler(); + switch (bundler) { + case "rspack": + return true; + default: + const packageJSONPath = resolvePackageJSONPath(WEBPACK_PLUGIN_NAME, { + paths: [projectData.projectDir], + }); - if (packageJSONPath) { - const packageData = this.$fs.readJson(packageJSONPath); - const ver = semver.coerce(packageData.version); + if (packageJSONPath) { + const packageData = this.$fs.readJson(packageJSONPath); + const ver = semver.coerce(packageData.version); - if (semver.satisfies(ver, ">= 5.0.0")) { - return true; - } + if (semver.satisfies(ver, ">= 5.0.0")) { + return true; + } + } + break; } return false; } + + public getBundler(): BundlerType { + return this.$projectConfigService.getValue(`bundler`, "webpack"); + } +} + +function capitalizeFirstLetter(val: string) { + return String(val).charAt(0).toUpperCase() + String(val).slice(1); } -injector.register("webpackCompilerService", WebpackCompilerService); +injector.register("bundlerCompilerService", BundlerCompilerService); diff --git a/lib/services/webpack/webpack.d.ts b/lib/services/bundler/bundler.ts similarity index 90% rename from lib/services/webpack/webpack.d.ts rename to lib/services/bundler/bundler.ts index e3a8dddd8b..691d45f8c5 100644 --- a/lib/services/webpack/webpack.d.ts +++ b/lib/services/bundler/bundler.ts @@ -18,21 +18,21 @@ import { import { INotConfiguredEnvOptions } from "../../common/definitions/commands"; declare global { - interface IWebpackCompilerService extends EventEmitter { + interface IBundlerCompilerService extends EventEmitter { compileWithWatch( platformData: IPlatformData, projectData: IProjectData, - prepareData: IPrepareData + prepareData: IPrepareData, ): Promise; compileWithoutWatch( platformData: IPlatformData, projectData: IProjectData, - prepareData: IPrepareData + prepareData: IPrepareData, ): Promise; - stopWebpackCompiler(platform: string): Promise; + stopBundlerCompiler(platform: string): Promise; } - interface IWebpackEnvOptions { + interface IBundlerEnvOptions { sourceMap?: boolean; uglify?: boolean; production?: boolean; @@ -42,19 +42,19 @@ declare global { checkForChanges( platformData: IPlatformData, projectData: IProjectData, - prepareData: IPrepareData + prepareData: IPrepareData, ): Promise; getPrepareInfoFilePath(platformData: IPlatformData): string; getPrepareInfo(platformData: IPlatformData): IPrepareInfo; savePrepareInfo( platformData: IPlatformData, projectData: IProjectData, - prepareData: IPrepareData + prepareData: IPrepareData, ): Promise; setNativePlatformStatus( platformData: IPlatformData, projectData: IProjectData, - addedPlatform: IAddedNativePlatform + addedPlatform: IAddedNativePlatform, ): void; currentChanges: IProjectChangesInfo; } @@ -68,7 +68,7 @@ declare global { hasNativeChanges: boolean; } - interface IWebpackEmitMessage { + interface IBundlerEmitMessage { emittedFiles: string[]; chunkFiles: string[]; hash: string; @@ -81,12 +81,12 @@ declare global { validate( projectData: IProjectData, options: IOptions, - notConfiguredEnvOptions?: INotConfiguredEnvOptions + notConfiguredEnvOptions?: INotConfiguredEnvOptions, ): Promise; createProject( frameworkDir: string, frameworkVersion: string, - projectData: IProjectData + projectData: IProjectData, ): Promise; interpolateData(projectData: IProjectData): Promise; interpolateConfigurationFile(projectData: IProjectData): void; @@ -108,13 +108,13 @@ declare global { validateOptions( projectId?: string, provision?: true | string, - teamId?: true | string + teamId?: true | string, ): Promise; buildProject( projectRoot: string, projectData: IProjectData, - buildConfig: T + buildConfig: T, ): Promise; /** @@ -125,7 +125,7 @@ declare global { */ prepareProject( projectData: IProjectData, - prepareData: T + prepareData: T, ): Promise; /** @@ -146,7 +146,7 @@ declare global { preparePluginNativeCode( pluginData: IPluginData, - options?: any + options?: any, ): Promise; /** @@ -157,17 +157,17 @@ declare global { */ removePluginNativeCode( pluginData: IPluginData, - projectData: IProjectData + projectData: IProjectData, ): Promise; beforePrepareAllPlugins( projectData: IProjectData, - dependencies?: IDependencyData[] + dependencies?: IDependencyData[], ): Promise; handleNativeDependenciesChange( projectData: IProjectData, - opts: IRelease + opts: IRelease, ): Promise; /** @@ -178,11 +178,11 @@ declare global { cleanDeviceTempFolder( deviceIdentifier: string, - projectData: IProjectData + projectData: IProjectData, ): Promise; processConfigurationFilesFromAppResources( projectData: IProjectData, - opts: { release: boolean } + opts: { release: boolean }, ): Promise; /** @@ -214,7 +214,7 @@ declare global { checkForChanges( changeset: IProjectChangesInfo, prepareData: T, - projectData: IProjectData + projectData: IProjectData, ): Promise; /** diff --git a/test/controllers/prepare-controller.ts b/test/controllers/prepare-controller.ts index a8bf78ad3b..e3982de1e4 100644 --- a/test/controllers/prepare-controller.ts +++ b/test/controllers/prepare-controller.ts @@ -38,7 +38,7 @@ function createTestInjector(data: { hasNativeChanges: boolean }): IInjector { }, }); - injector.register("webpackCompilerService", { + injector.register("bundlerCompilerService", { on: () => ({}), emit: () => ({}), compileWithWatch: async () => { @@ -119,7 +119,7 @@ describe("prepareController", () => { injector.resolve("prepareController"); const prepareNativePlatformService = injector.resolve( - "prepareNativePlatformService" + "prepareNativePlatformService", ); prepareNativePlatformService.prepareNativePlatform = async () => { const nativeFilesWatcher = (prepareController).watchersData[ @@ -128,7 +128,7 @@ describe("prepareController", () => { nativeFilesWatcher.emit( "all", "change", - "my/project/App_Resources/some/file" + "my/project/App_Resources/some/file", ); isNativePrepareCalled = true; return false; diff --git a/test/project-data.ts b/test/project-data.ts index 7ce33a1320..5b8c747bd1 100644 --- a/test/project-data.ts +++ b/test/project-data.ts @@ -56,14 +56,16 @@ describe("projectData", () => { configData?: { shared?: boolean; webpackConfigPath?: string; + bundlerConfigPath?: string; projectName?: string; + bundler?: string; }; }): IProjectData => { const testInjector = createTestInjector(); const fs = testInjector.resolve("fs"); testInjector.register( "projectConfigService", - stubs.ProjectConfigServiceStub.initWithConfig(opts?.configData) + stubs.ProjectConfigServiceStub.initWithConfig(opts?.configData), ); fs.exists = (filePath: string) => { @@ -98,7 +100,7 @@ describe("projectData", () => { const assertProjectType = ( dependencies: any, devDependencies: any, - expectedProjecType: string + expectedProjecType: string, ) => { const projectData = prepareTest({ packageJsonData: { @@ -125,7 +127,7 @@ describe("projectData", () => { assertProjectType( { "nativescript-vue": "*" }, { typescript: "*" }, - "Vue.js" + "Vue.js", ); }); @@ -141,7 +143,7 @@ describe("projectData", () => { assertProjectType( null, { "nativescript-dev-typescript": "*" }, - "Pure TypeScript" + "Pure TypeScript", ); }); @@ -195,13 +197,13 @@ describe("projectData", () => { const projectData = prepareTest(); assert.equal( projectData.webpackConfigPath, - path.join(projectDir, "webpack.config.js") + path.join(projectDir, "webpack.config.js"), ); }); it("returns correct path when full path is set in nsconfig.json", () => { const pathToConfig = path.resolve( - path.join("/testDir", "innerDir", "mywebpack.config.js") + path.join("/testDir", "innerDir", "mywebpack.config.js"), ); const projectData = prepareTest({ configData: { webpackConfigPath: pathToConfig }, @@ -211,7 +213,7 @@ describe("projectData", () => { it("returns correct path when relative path is set in nsconfig.json", () => { const pathToConfig = path.resolve( - path.join("projectDir", "innerDir", "mywebpack.config.js") + path.join("projectDir", "innerDir", "mywebpack.config.js"), ); const projectData = prepareTest({ configData: { @@ -221,4 +223,81 @@ describe("projectData", () => { assert.equal(projectData.webpackConfigPath, pathToConfig); }); }); + + describe("bundlerConfigPath", () => { + it("default path to webpack.config.js is set when nsconfig.json does not set value", () => { + const projectData = prepareTest(); + assert.equal( + projectData.bundlerConfigPath, + path.join(projectDir, "webpack.config.js"), + ); + }); + + it("should use webpackConfigPath property when bundlerConfigPath is not defined", () => { + const pathToConfig = path.resolve( + path.join("/testDir", "innerDir", "mywebpack.config.js"), + ); + const projectData = prepareTest({ + configData: { webpackConfigPath: pathToConfig }, + }); + assert.equal(projectData.bundlerConfigPath, pathToConfig); + }); + + it("returns correct path when full path is set in nsconfig.json", () => { + const pathToConfig = path.resolve( + path.join("/testDir", "innerDir", "mywebpack.config.js"), + ); + const projectData = prepareTest({ + configData: { bundlerConfigPath: pathToConfig }, + }); + assert.equal(projectData.bundlerConfigPath, pathToConfig); + }); + + it("returns correct path when relative path is set in nsconfig.json", () => { + const pathToConfig = path.resolve( + path.join("projectDir", "innerDir", "mywebpack.config.js"), + ); + const projectData = prepareTest({ + configData: { + bundlerConfigPath: path.join("./innerDir", "mywebpack.config.js"), + }, + }); + assert.equal(projectData.bundlerConfigPath, pathToConfig); + }); + + it("should use bundlerConfigPath instead of webpackConfigPath if both are defined.", () => { + const pathToConfig = path.resolve( + path.join("projectDir", "innerDir", "myrspack.config.js"), + ); + const projectData = prepareTest({ + configData: { + webpackConfigPath: path.join("./innerDir", "mywebpack.config.js"), + bundlerConfigPath: path.join("./innerDir", "myrspack.config.js"), + }, + }); + assert.equal(projectData.bundlerConfigPath, pathToConfig); + }); + }); + + describe("bundler", () => { + it("sets bundler to 'webpack' by default when nsconfig.json does not specify a bundler", () => { + const projectData = prepareTest(); + assert.equal(projectData.bundler, "webpack"); + }); + + it("sets bundler to 'webpack' when explicitly defined in nsconfig.json", () => { + const projectData = prepareTest({ configData: { bundler: "webpack" } }); + assert.equal(projectData.bundler, "webpack"); + }); + + it("sets bundler to 'rspack' when explicitly defined in nsconfig.json", () => { + const projectData = prepareTest({ configData: { bundler: "rspack" } }); + assert.equal(projectData.bundler, "rspack"); + }); + + it("sets bundler to 'vite' when explicitly defined in nsconfig.json", () => { + const projectData = prepareTest({ configData: { bundler: "vite" } }); + assert.equal(projectData.bundler, "vite"); + }); + }); }); diff --git a/test/services/webpack/webpack-compiler-service.ts b/test/services/bundler/bundler-compiler-service.ts similarity index 62% rename from test/services/webpack/webpack-compiler-service.ts rename to test/services/bundler/bundler-compiler-service.ts index d15cccc430..49d69a55f4 100644 --- a/test/services/webpack/webpack-compiler-service.ts +++ b/test/services/bundler/bundler-compiler-service.ts @@ -1,5 +1,5 @@ import { Yok } from "../../../lib/common/yok"; -import { WebpackCompilerService } from "../../../lib/services/webpack/webpack-compiler-service"; +import { BundlerCompilerService } from "../../../lib/services/bundler/bundler-compiler-service"; import { assert } from "chai"; import { ErrorsStub } from "../../stubs"; import { IInjector } from "../../../lib/common/definitions/yok"; @@ -23,7 +23,7 @@ function createTestInjector(): IInjector { testInjector.register("packageManager", { getPackageManagerName: async () => "npm", }); - testInjector.register("webpackCompilerService", WebpackCompilerService); + testInjector.register("bundlerCompilerService", BundlerCompilerService); testInjector.register("childProcess", {}); testInjector.register("hooksService", {}); testInjector.register("hostInfo", {}); @@ -33,6 +33,9 @@ function createTestInjector(): IInjector { testInjector.register("packageInstallationManager", {}); testInjector.register("mobileHelper", {}); testInjector.register("cleanupService", {}); + testInjector.register("projectConfigService", { + getValue: (key: string, defaultValue?: string) => defaultValue, + }); testInjector.register("fs", { exists: (filePath: string) => true, }); @@ -40,23 +43,23 @@ function createTestInjector(): IInjector { return testInjector; } -describe("WebpackCompilerService", () => { +describe("BundlerCompilerService", () => { let testInjector: IInjector = null; - let webpackCompilerService: WebpackCompilerService = null; + let bundlerCompilerService: BundlerCompilerService = null; beforeEach(() => { testInjector = createTestInjector(); - webpackCompilerService = testInjector.resolve(WebpackCompilerService); + bundlerCompilerService = testInjector.resolve(BundlerCompilerService); }); describe("getUpdatedEmittedFiles", () => { // backwards compatibility with old versions of nativescript-dev-webpack it("should return only hot updates when nextHash is not provided", async () => { - const result = webpackCompilerService.getUpdatedEmittedFiles( + const result = bundlerCompilerService.getUpdatedEmittedFiles( getAllEmittedFiles("hash1"), chunkFiles, null, - iOSPlatformName + iOSPlatformName, ); const expectedEmittedFiles = [ "bundle.hash1.hot-update.js", @@ -65,19 +68,19 @@ describe("WebpackCompilerService", () => { assert.deepStrictEqual(result.emittedFiles, expectedEmittedFiles); }); - // 2 successful webpack compilations + // 2 successful bundler compilations it("should return only hot updates when nextHash is provided", async () => { - webpackCompilerService.getUpdatedEmittedFiles( + bundlerCompilerService.getUpdatedEmittedFiles( getAllEmittedFiles("hash1"), chunkFiles, "hash2", - iOSPlatformName + iOSPlatformName, ); - const result = webpackCompilerService.getUpdatedEmittedFiles( + const result = bundlerCompilerService.getUpdatedEmittedFiles( getAllEmittedFiles("hash2"), chunkFiles, "hash3", - iOSPlatformName + iOSPlatformName, ); assert.deepStrictEqual(result.emittedFiles, [ @@ -85,19 +88,19 @@ describe("WebpackCompilerService", () => { "hash2.hot-update.json", ]); }); - // 1 successful webpack compilation, n compilations with no emitted files - it("should return all files when there is a webpack compilation with no emitted files", () => { - webpackCompilerService.getUpdatedEmittedFiles( + // 1 successful bundler compilation, n compilations with no emitted files + it("should return all files when there is a bundler compilation with no emitted files", () => { + bundlerCompilerService.getUpdatedEmittedFiles( getAllEmittedFiles("hash1"), chunkFiles, "hash2", - iOSPlatformName + iOSPlatformName, ); - const result = webpackCompilerService.getUpdatedEmittedFiles( + const result = bundlerCompilerService.getUpdatedEmittedFiles( getAllEmittedFiles("hash4"), chunkFiles, "hash5", - iOSPlatformName + iOSPlatformName, ); assert.deepStrictEqual(result.emittedFiles, [ @@ -107,25 +110,25 @@ describe("WebpackCompilerService", () => { "hash4.hot-update.json", ]); }); - // 1 successful webpack compilation, n compilations with no emitted files, 1 successful webpack compilation + // 1 successful bundler compilation, n compilations with no emitted files, 1 successful bundler compilation it("should return only hot updates after fixing the compilation error", () => { - webpackCompilerService.getUpdatedEmittedFiles( + bundlerCompilerService.getUpdatedEmittedFiles( getAllEmittedFiles("hash1"), chunkFiles, "hash2", - iOSPlatformName + iOSPlatformName, ); - webpackCompilerService.getUpdatedEmittedFiles( + bundlerCompilerService.getUpdatedEmittedFiles( getAllEmittedFiles("hash5"), chunkFiles, "hash6", - iOSPlatformName + iOSPlatformName, ); - const result = webpackCompilerService.getUpdatedEmittedFiles( + const result = bundlerCompilerService.getUpdatedEmittedFiles( getAllEmittedFiles("hash6"), chunkFiles, "hash7", - iOSPlatformName + iOSPlatformName, ); assert.deepStrictEqual(result.emittedFiles, [ @@ -133,16 +136,16 @@ describe("WebpackCompilerService", () => { "hash6.hot-update.json", ]); }); - // 1 webpack compilation with no emitted files + // 1 bundler compilation with no emitted files it("should return all files when first compilation on livesync change is not successful", () => { - (webpackCompilerService).expectedHashes = { + (bundlerCompilerService).expectedHashes = { ios: "hash1", }; - const result = webpackCompilerService.getUpdatedEmittedFiles( + const result = bundlerCompilerService.getUpdatedEmittedFiles( getAllEmittedFiles("hash1"), chunkFiles, "hash2", - iOSPlatformName + iOSPlatformName, ); assert.deepStrictEqual(result.emittedFiles, [ @@ -151,48 +154,48 @@ describe("WebpackCompilerService", () => { ]); }); it("should return correct hashes when there are more than one platform", () => { - webpackCompilerService.getUpdatedEmittedFiles( + bundlerCompilerService.getUpdatedEmittedFiles( getAllEmittedFiles("hash1"), chunkFiles, "hash2", - iOSPlatformName + iOSPlatformName, ); - webpackCompilerService.getUpdatedEmittedFiles( + bundlerCompilerService.getUpdatedEmittedFiles( getAllEmittedFiles("hash3"), chunkFiles, "hash4", - androidPlatformName + androidPlatformName, ); - webpackCompilerService.getUpdatedEmittedFiles( + bundlerCompilerService.getUpdatedEmittedFiles( getAllEmittedFiles("hash2"), chunkFiles, "hash5", - iOSPlatformName + iOSPlatformName, ); - webpackCompilerService.getUpdatedEmittedFiles( + bundlerCompilerService.getUpdatedEmittedFiles( getAllEmittedFiles("hash4"), chunkFiles, "hash6", - androidPlatformName + androidPlatformName, ); - const iOSResult = webpackCompilerService.getUpdatedEmittedFiles( + const iOSResult = bundlerCompilerService.getUpdatedEmittedFiles( getAllEmittedFiles("hash5"), chunkFiles, "hash7", - iOSPlatformName + iOSPlatformName, ); assert.deepStrictEqual(iOSResult.emittedFiles, [ "bundle.hash5.hot-update.js", "hash5.hot-update.json", ]); - const androidResult = webpackCompilerService.getUpdatedEmittedFiles( + const androidResult = bundlerCompilerService.getUpdatedEmittedFiles( getAllEmittedFiles("hash6"), chunkFiles, "hash8", - androidPlatformName + androidPlatformName, ); assert.deepStrictEqual(androidResult.emittedFiles, [ "bundle.hash6.hot-update.js", @@ -202,33 +205,33 @@ describe("WebpackCompilerService", () => { }); describe("compileWithWatch", () => { - it("fails when the value set for webpackConfigPath is not existant file", async () => { - const webpackConfigPath = "some path.js"; + it("fails when the value set for bundlerConfigPath is not existant file", async () => { + const bundlerConfigPath = "some path.js"; testInjector.resolve("fs").exists = (filePath: string) => - filePath !== webpackConfigPath; + filePath !== bundlerConfigPath; await assert.isRejected( - webpackCompilerService.compileWithWatch( + bundlerCompilerService.compileWithWatch( { platformNameLowerCase: "android" }, - { webpackConfigPath }, - {} + { bundlerConfigPath: bundlerConfigPath }, + {}, ), - `The webpack configuration file ${webpackConfigPath} does not exist. Ensure the file exists, or update the path in ${CONFIG_FILE_NAME_DISPLAY}` + `The bundler configuration file ${bundlerConfigPath} does not exist. Ensure the file exists, or update the path in ${CONFIG_FILE_NAME_DISPLAY}`, ); }); }); describe("compileWithoutWatch", () => { - it("fails when the value set for webpackConfigPath is not existant file", async () => { - const webpackConfigPath = "some path.js"; + it("fails when the value set for bundlerConfigPath is not existant file", async () => { + const bundlerConfigPath = "some path.js"; testInjector.resolve("fs").exists = (filePath: string) => - filePath !== webpackConfigPath; + filePath !== bundlerConfigPath; await assert.isRejected( - webpackCompilerService.compileWithoutWatch( + bundlerCompilerService.compileWithoutWatch( { platformNameLowerCase: "android" }, - { webpackConfigPath }, - {} + { bundlerConfigPath: bundlerConfigPath }, + {}, ), - `The webpack configuration file ${webpackConfigPath} does not exist. Ensure the file exists, or update the path in ${CONFIG_FILE_NAME_DISPLAY}` + `The bundler configuration file ${bundlerConfigPath} does not exist. Ensure the file exists, or update the path in ${CONFIG_FILE_NAME_DISPLAY}`, ); }); }); diff --git a/test/stubs.ts b/test/stubs.ts index fc4d687c15..7ec3580891 100644 --- a/test/stubs.ts +++ b/test/stubs.ts @@ -38,6 +38,7 @@ import { IProjectConfigInformation, IProjectBackupService, IBackup, + BundlerType, } from "../lib/definitions/project"; import { IPlatformData, @@ -658,6 +659,8 @@ export class ProjectDataStub implements IProjectData { projectDir: string; projectName: string; webpackConfigPath: string; + bundlerConfigPath: string; + bundler: BundlerType; get platformsDir(): string { return (