style: run prettier on webpack5 files

This commit is contained in:
Igor Randjelovic
2021-03-29 01:24:23 +02:00
parent c55782bfaf
commit c922e77129
13 changed files with 138 additions and 110 deletions

View File

@ -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);
}
});

View File

@ -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;
}

View File

@ -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);
}

View File

@ -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;
}

View File

@ -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!');
}
}

View File

@ -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) => ({
patterns: Array.from(copyRules)
.map((glob) => ({
from: glob,
context: entryDir,
noErrorOnMissing: true,
globOptions,
})).concat(additionalCopyRules),
}))
.concat(additionalCopyRules),
},
]);
}

View File

@ -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) => {

View File

@ -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));
}
}

View File

@ -37,7 +37,7 @@ export interface IWebpackEnv {
verbose?: boolean;
// misc
replace?: string[] | string
replace?: string[] | string;
}
interface IChainEntry {

View File

@ -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();
};
}

View File

@ -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);
}

View File

@ -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);
}

View File

@ -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,
}
},
});
});
}