diff --git a/packages/webpack5/src/bin/index.ts b/packages/webpack5/src/bin/index.ts index 852d0cbd2..edcb91c94 100644 --- a/packages/webpack5/src/bin/index.ts +++ b/packages/webpack5/src/bin/index.ts @@ -63,7 +63,7 @@ program return path.resolve(options.config); } - return path.resolve(process.cwd(), 'webpack.config.js') + return path.resolve(process.cwd(), 'webpack.config.js'); })(); // todo: validate config exists @@ -82,7 +82,10 @@ program const compiler = webpack(configuration); - const webpackCompilationCallback = (err: webpack.WebpackError, stats: webpack.Stats) => { + const webpackCompilationCallback = ( + err: webpack.WebpackError, + stats: webpack.Stats + ) => { if (err) { // Do not keep cache anymore compiler.purgeInputFileSystem(); @@ -104,18 +107,16 @@ program }) ); } - } + }; if (options.watch) { - console.log('webpack is watching the files...') + console.log('webpack is watching the files...'); compiler.watch( configuration.watchOptions ?? {}, webpackCompilationCallback ); } else { - compiler.run( - webpackCompilationCallback - ); + compiler.run(webpackCompilationCallback); } }); diff --git a/packages/webpack5/src/configuration/javascript.ts b/packages/webpack5/src/configuration/javascript.ts index 7dccca1a1..ccc821c63 100644 --- a/packages/webpack5/src/configuration/javascript.ts +++ b/packages/webpack5/src/configuration/javascript.ts @@ -1,6 +1,6 @@ import Config from 'webpack-chain'; -import { getEntryPath, getEntryDirPath } from "../helpers/platform"; +import { getEntryPath, getEntryDirPath } from '../helpers/platform'; import { addVirtualEntry } from '../helpers/virtualModules'; import { env as _env, IWebpackEnv } from '../index'; import base from './base'; @@ -36,15 +36,14 @@ export default function (config: Config, env: IWebpackEnv = _env): Config { config.module .rule('hmr-core') .test(/\.js$/) - .exclude - .add(/node_modules/) + .exclude.add(/node_modules/) .add(entryPath) .end() .use('nativescript-hot-loader') .loader('nativescript-hot-loader') .options({ - appPath: getEntryDirPath() - }) + appPath: getEntryDirPath(), + }); return config; } diff --git a/packages/webpack5/src/configuration/svelte.ts b/packages/webpack5/src/configuration/svelte.ts index 5d77c405f..1f1dbba2a 100644 --- a/packages/webpack5/src/configuration/svelte.ts +++ b/packages/webpack5/src/configuration/svelte.ts @@ -53,14 +53,12 @@ function getSvelteConfigPreprocessor(): any { } interface ISvelteConfig { - preprocess: any + preprocess: any; } function getSvelteConfig(): ISvelteConfig | undefined { try { - return require( - getProjectFilePath('svelte.config.js') - ) as ISvelteConfig; + return require(getProjectFilePath('svelte.config.js')) as ISvelteConfig; } catch (err) { error('Could not find svelte.config.js.', err); } diff --git a/packages/webpack5/src/configuration/typescript.ts b/packages/webpack5/src/configuration/typescript.ts index 0e31692ad..e3b71de5e 100644 --- a/packages/webpack5/src/configuration/typescript.ts +++ b/packages/webpack5/src/configuration/typescript.ts @@ -1,6 +1,6 @@ import Config from 'webpack-chain'; -import { getEntryDirPath, getEntryPath } from "../helpers/platform"; +import { getEntryDirPath, getEntryPath } from '../helpers/platform'; import { addVirtualEntry } from '../helpers/virtualModules'; import { env as _env, IWebpackEnv } from '../index'; import base from './base'; @@ -36,15 +36,14 @@ export default function (config: Config, env: IWebpackEnv = _env): Config { config.module .rule('hmr-core') .test(/\.(js|ts)$/) - .exclude - .add(/node_modules/) + .exclude.add(/node_modules/) .add(entryPath) .end() .use('nativescript-hot-loader') .loader('nativescript-hot-loader') .options({ - appPath: getEntryDirPath() - }) + appPath: getEntryDirPath(), + }); return config; } diff --git a/packages/webpack5/src/configuration/vue.ts b/packages/webpack5/src/configuration/vue.ts index b522b6ace..4a78e91dc 100644 --- a/packages/webpack5/src/configuration/vue.ts +++ b/packages/webpack5/src/configuration/vue.ts @@ -3,10 +3,10 @@ import { merge } from 'webpack-merge'; import Config from 'webpack-chain'; import fs from 'fs'; -import { hasDependency } from "../helpers/dependencies"; +import { hasDependency } from '../helpers/dependencies'; import { getPlatformName } from '../helpers/platform'; import { env as _env, IWebpackEnv } from '../index'; -import { error } from "../helpers/log"; +import { error } from '../helpers/log'; import base from './base'; export default function (config: Config, env: IWebpackEnv = _env): Config { @@ -15,8 +15,8 @@ export default function (config: Config, env: IWebpackEnv = _env): Config { const platform = getPlatformName(); // we need to patch VueLoader if we want to enable hmr - if(env.hmr) { - patchVueLoaderForHMR() + if (env.hmr) { + patchVueLoaderForHMR(); } // resolve .vue files @@ -82,12 +82,15 @@ export default function (config: Config, env: IWebpackEnv = _env): Config { */ function patchVueLoaderForHMR() { try { - const vueLoaderPath = require.resolve('vue-loader/lib/index.js') + const vueLoaderPath = require.resolve('vue-loader/lib/index.js'); const source = fs.readFileSync(vueLoaderPath).toString(); - const patchedSource = source.replace(/(isServer\s=\s)(target\s===\s'node')/g, '$1false;') - fs.writeFileSync(vueLoaderPath, patchedSource) - delete require.cache[vueLoaderPath] + const patchedSource = source.replace( + /(isServer\s=\s)(target\s===\s'node')/g, + '$1false;' + ); + fs.writeFileSync(vueLoaderPath, patchedSource); + delete require.cache[vueLoaderPath]; } catch (err) { - error('Failed to patch VueLoader - HMR may not work properly!') + error('Failed to patch VueLoader - HMR may not work properly!'); } } diff --git a/packages/webpack5/src/helpers/copyRules.ts b/packages/webpack5/src/helpers/copyRules.ts index 23fd90a51..0f19d724e 100644 --- a/packages/webpack5/src/helpers/copyRules.ts +++ b/packages/webpack5/src/helpers/copyRules.ts @@ -14,7 +14,7 @@ export let copyRules = new Set([]); /** * @internal */ -export let additionalCopyRules = [] +export let additionalCopyRules = []; /** * Utility to add new copy rules. Accepts a glob or an object. For example @@ -30,11 +30,11 @@ export let additionalCopyRules = [] * @param {string|object} globOrObject */ export function addCopyRule(globOrObject: string | object) { - if(typeof globOrObject === 'string') { + if (typeof globOrObject === 'string') { return copyRules.add(globOrObject); } - additionalCopyRules.push(globOrObject) + additionalCopyRules.push(globOrObject); } /** @@ -72,12 +72,14 @@ export function applyCopyRules(config: Config) { config.plugin('CopyWebpackPlugin').use(CopyWebpackPlugin, [ { - patterns: Array.from(copyRules).map((glob) => ({ - from: glob, - context: entryDir, - noErrorOnMissing: true, - globOptions, - })).concat(additionalCopyRules), + patterns: Array.from(copyRules) + .map((glob) => ({ + from: glob, + context: entryDir, + noErrorOnMissing: true, + globOptions, + })) + .concat(additionalCopyRules), }, ]); } diff --git a/packages/webpack5/src/helpers/fileReplacements.ts b/packages/webpack5/src/helpers/fileReplacements.ts index d04931021..f61a38935 100644 --- a/packages/webpack5/src/helpers/fileReplacements.ts +++ b/packages/webpack5/src/helpers/fileReplacements.ts @@ -8,7 +8,9 @@ interface IReplacementMap { /** * @internal */ -export function getFileReplacementsFromEnv(env: IWebpackEnv = _env): IReplacementMap { +export function getFileReplacementsFromEnv( + env: IWebpackEnv = _env +): IReplacementMap { const fileReplacements: IReplacementMap = {}; const entries: string[] = (() => { @@ -17,10 +19,10 @@ export function getFileReplacementsFromEnv(env: IWebpackEnv = _env): IReplacemen } if (typeof env.replace === 'string') { - return [env.replace] + return [env.replace]; } - return [] + return []; })(); entries.forEach((replaceEntry) => { diff --git a/packages/webpack5/src/helpers/log.ts b/packages/webpack5/src/helpers/log.ts index fc95cd80a..725048848 100644 --- a/packages/webpack5/src/helpers/log.ts +++ b/packages/webpack5/src/helpers/log.ts @@ -1,5 +1,5 @@ import dedent from 'ts-dedent'; -import { env } from "@nativescript/webpack"; +import { env } from '@nativescript/webpack'; // de-indents strings so multi-line string literals can be used function cleanup(data: any[]) { @@ -29,7 +29,7 @@ export function warn(...data: any): void { } export function info(...data: any): void { - if(env.verbose) { + if (env.verbose) { console.log(`[@nativescript/webpack] Info: \n`, ...cleanup(data)); } } diff --git a/packages/webpack5/src/index.ts b/packages/webpack5/src/index.ts index 75427fb0b..0c76884e1 100644 --- a/packages/webpack5/src/index.ts +++ b/packages/webpack5/src/index.ts @@ -37,7 +37,7 @@ export interface IWebpackEnv { verbose?: boolean; // misc - replace?: string[] | string + replace?: string[] | string; } interface IChainEntry { diff --git a/packages/webpack5/src/loaders/nativescript-hot-loader/hmr.runtime.ts b/packages/webpack5/src/loaders/nativescript-hot-loader/hmr.runtime.ts index 5862d7f04..662ce8b47 100644 --- a/packages/webpack5/src/loaders/nativescript-hot-loader/hmr.runtime.ts +++ b/packages/webpack5/src/loaders/nativescript-hot-loader/hmr.runtime.ts @@ -6,92 +6,109 @@ if (module.hot) { let hash = __webpack_require__.h(); - const logVerbose = (title: string, ...info?: any) => { + const logVerbose = (title: string, ...info: any) => { if (__NS_ENV_VERBOSE__) { - console.log(`[HMR][Verbose] ${title}`) + console.log(`[HMR][Verbose] ${title}`); if (info?.length) { - console.log(...info) - console.log('---') + console.log(...info); + console.log('---'); } } - } + }; - const setStatus = (hash: string, status: 'success' | 'failure', message?: string, ...info?: any): boolean => { + const setStatus = ( + hash: string, + status: 'success' | 'failure', + message?: string, + ...info: any + ): boolean => { // format is important - CLI expects this exact format - console.log(`[HMR][${hash}] ${status} | ${message}`) + console.log(`[HMR][${hash}] ${status} | ${message}`); if (info?.length) { - logVerbose('Additional Info', info) + logVerbose('Additional Info', info); } // return true if operation was successful - return status === 'success' - } + return status === 'success'; + }; const applyOptions = { ignoreUnaccepted: false, ignoreDeclined: false, ignoreErrored: false, onDeclined(info) { - setStatus(hash, 'failure', 'A module has been declined.', info) + setStatus(hash, 'failure', 'A module has been declined.', info); }, onUnaccepted(info) { - setStatus(hash, 'failure', 'A module has not been accepted.', info) + setStatus(hash, 'failure', 'A module has not been accepted.', info); }, onAccepted(info) { // console.log('accepted', info) - logVerbose('Module Accepted', info) + logVerbose('Module Accepted', info); }, onDisposed(info) { // console.log('disposed', info) - logVerbose('Module Disposed', info) + logVerbose('Module Disposed', info); }, onErrored(info) { - setStatus(hash, 'failure', 'A module has errored.', info) - } - } + setStatus(hash, 'failure', 'A module has errored.', info); + }, + }; const checkAndApply = async () => { hash = __webpack_require__.h(); - const modules = await module.hot.check().catch(error => { - return setStatus(hash, 'failure', 'Failed to check.', error.message || error.stack) - }) + const modules = await module.hot.check().catch((error) => { + return setStatus( + hash, + 'failure', + 'Failed to check.', + error.message || error.stack + ); + }); if (!modules) { - logVerbose('No modules to apply.') + logVerbose('No modules to apply.'); return false; } - const appliedModules = await module.hot.apply(applyOptions).catch(error => { - return setStatus(hash, 'failure', 'Failed to apply.', error.message || error.stack) - }) + const appliedModules = await module.hot + .apply(applyOptions) + .catch((error) => { + return setStatus( + hash, + 'failure', + 'Failed to apply.', + error.message || error.stack + ); + }); if (!appliedModules) { - logVerbose('No modules applied.') + logVerbose('No modules applied.'); return false; } - return setStatus(hash, 'success', 'Successfully applied update.') - } + return setStatus(hash, 'success', 'Successfully applied update.'); + }; const hasUpdate = () => { try { - __non_webpack_require__(`~/bundle.${__webpack_hash__}.hot-update.json`) + __non_webpack_require__(`~/bundle.${__webpack_hash__}.hot-update.json`); return true; } catch (err) { return false; } - } + }; - const originalOnLiveSync = global.__onLiveSync + const originalOnLiveSync = global.__onLiveSync; global.__onLiveSync = async function () { - logVerbose('LiveSync') + logVerbose('LiveSync'); if (!hasUpdate()) { return; } - await checkAndApply() + await checkAndApply(); originalOnLiveSync(); }; } diff --git a/packages/webpack5/src/loaders/nativescript-hot-loader/index.ts b/packages/webpack5/src/loaders/nativescript-hot-loader/index.ts index f9307a3aa..6a91088f8 100644 --- a/packages/webpack5/src/loaders/nativescript-hot-loader/index.ts +++ b/packages/webpack5/src/loaders/nativescript-hot-loader/index.ts @@ -1,31 +1,33 @@ -import { relative, resolve } from "path"; -import dedent from "ts-dedent"; +import { relative, resolve } from 'path'; +import dedent from 'ts-dedent'; import fs from 'fs'; // note: this will bail even if module.hot appears in a comment -const MODULE_HOT_RE = /module\.hot/ +const MODULE_HOT_RE = /module\.hot/; export default function loader(content: string, map: any) { if (MODULE_HOT_RE.test(content)) { // Code already handles HMR - we don't need to do anything - return this.callback(null, content, map) + return this.callback(null, content, map); } const opts = this.getOptions(); // used to inject the HMR runtime into the entry file - if(opts.injectHMRRuntime) { - const hmrRuntimePath = resolve(__dirname, './hmr.runtime.js') - const hmrRuntime = fs.readFileSync(hmrRuntimePath).toString() + if (opts.injectHMRRuntime) { + const hmrRuntimePath = resolve(__dirname, './hmr.runtime.js'); + const hmrRuntime = fs + .readFileSync(hmrRuntimePath) + .toString() .split('// ---')[1] - .replace('//# sourceMappingURL=hmr.runtime.js.map', '') + .replace('//# sourceMappingURL=hmr.runtime.js.map', ''); - return this.callback(null, `${content}\n${hmrRuntime}`, map) + return this.callback(null, `${content}\n${hmrRuntime}`, map); } const relativePath = relative( opts.appPath ?? this.rootContext, this.resourcePath - ).replace(/\\/g, '/') + ).replace(/\\/g, '/'); const hmrCode = this.hot ? dedent` @@ -36,8 +38,7 @@ export default function loader(content: string, map: any) { ` : ``; - const source = `${content}\n${hmrCode}` + const source = `${content}\n${hmrCode}`; - this.callback(null, source, map) + this.callback(null, source, map); } - diff --git a/packages/webpack5/src/loaders/nativescript-worker-loader/index.ts b/packages/webpack5/src/loaders/nativescript-worker-loader/index.ts index ceddbc404..454d166bb 100644 --- a/packages/webpack5/src/loaders/nativescript-worker-loader/index.ts +++ b/packages/webpack5/src/loaders/nativescript-worker-loader/index.ts @@ -1,5 +1,5 @@ const WorkerDependency = require('webpack/lib/dependencies/WorkerDependency'); -const RuntimeGlobals = require("webpack/lib/RuntimeGlobals"); +const RuntimeGlobals = require('webpack/lib/RuntimeGlobals'); /** * Patch WorkerDependency to change: @@ -14,15 +14,19 @@ const RuntimeGlobals = require("webpack/lib/RuntimeGlobals"); * break when the dependency range changes, for example if this PR is merged: * - https://github.com/webpack/webpack/pull/12750 */ -WorkerDependency.Template.prototype.apply = function apply(dependency, source, templateContext) { +WorkerDependency.Template.prototype.apply = function apply( + dependency, + source, + templateContext +) { const { chunkGraph, moduleGraph, runtimeRequirements } = templateContext; - const dep = /** @type {WorkerDependency} */ (dependency); - const block = /** @type {AsyncDependenciesBlock} */ (moduleGraph.getParentBlock( + const dep = /** @type {WorkerDependency} */ dependency; + const block = /** @type {AsyncDependenciesBlock} */ moduleGraph.getParentBlock( dependency - )); - const entrypoint = /** @type {Entrypoint} */ (chunkGraph.getBlockChunkGroup( + ); + const entrypoint = /** @type {Entrypoint} */ chunkGraph.getBlockChunkGroup( block - )); + ); const chunk = entrypoint.getEntrypointChunk(); // runtimeRequirements.add(RuntimeGlobals.publicPath); @@ -40,9 +44,9 @@ WorkerDependency.Template.prototype.apply = function apply(dependency, source, t RuntimeGlobals.getChunkScriptFilename }(${JSON.stringify(chunk.id)})` ); -} +}; -const NEW_WORKER_WITH_STRING_RE = /new\s+Worker\((['"`].+['"`])\)/ +const NEW_WORKER_WITH_STRING_RE = /new\s+Worker\((['"`].+['"`])\)/; /** * Replaces @@ -51,7 +55,9 @@ const NEW_WORKER_WITH_STRING_RE = /new\s+Worker\((['"`].+['"`])\)/ * new Worker(new URL('./somePath', import.meta.url)) */ export default function loader(content: string, map: any) { - const source = content.replace(NEW_WORKER_WITH_STRING_RE, 'new Worker(new URL($1, import.meta.url))') - this.callback(null, source, map) + const source = content.replace( + NEW_WORKER_WITH_STRING_RE, + 'new Worker(new URL($1, import.meta.url))' + ); + this.callback(null, source, map); } - diff --git a/packages/webpack5/src/plugins/WatchStatePlugin.ts b/packages/webpack5/src/plugins/WatchStatePlugin.ts index bff43878d..329333cd1 100644 --- a/packages/webpack5/src/plugins/WatchStatePlugin.ts +++ b/packages/webpack5/src/plugins/WatchStatePlugin.ts @@ -1,4 +1,4 @@ -import { env } from "../"; +import { env } from '../'; const id = 'WatchStatePlugin'; const version = 1; @@ -26,15 +26,15 @@ export class WatchStatePlugin { if (env.verbose) { if (compiler.modifiedFiles) { - Array.from(compiler.modifiedFiles).forEach(file => { - console.log(`MODIFIED: ${file}`) - }) + Array.from(compiler.modifiedFiles).forEach((file) => { + console.log(`MODIFIED: ${file}`); + }); } if (compiler.removedFiles) { - Array.from(compiler.removedFiles).forEach(file => { - console.log(`REMOVED: ${file}`) - }) + Array.from(compiler.removedFiles).forEach((file) => { + console.log(`REMOVED: ${file}`); + }); } } } @@ -74,7 +74,7 @@ export class WatchStatePlugin { data: { emittedAssets, staleAssets, - } + }, }); }); }