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(options.config);
} }
return path.resolve(process.cwd(), 'webpack.config.js') return path.resolve(process.cwd(), 'webpack.config.js');
})(); })();
// todo: validate config exists // todo: validate config exists
@ -82,7 +82,10 @@ program
const compiler = webpack(configuration); const compiler = webpack(configuration);
const webpackCompilationCallback = (err: webpack.WebpackError, stats: webpack.Stats) => { const webpackCompilationCallback = (
err: webpack.WebpackError,
stats: webpack.Stats
) => {
if (err) { if (err) {
// Do not keep cache anymore // Do not keep cache anymore
compiler.purgeInputFileSystem(); compiler.purgeInputFileSystem();
@ -104,18 +107,16 @@ program
}) })
); );
} }
} };
if (options.watch) { if (options.watch) {
console.log('webpack is watching the files...') console.log('webpack is watching the files...');
compiler.watch( compiler.watch(
configuration.watchOptions ?? {}, configuration.watchOptions ?? {},
webpackCompilationCallback webpackCompilationCallback
); );
} else { } else {
compiler.run( compiler.run(webpackCompilationCallback);
webpackCompilationCallback
);
} }
}); });

View File

@ -1,6 +1,6 @@
import Config from 'webpack-chain'; import Config from 'webpack-chain';
import { getEntryPath, getEntryDirPath } from "../helpers/platform"; import { getEntryPath, getEntryDirPath } from '../helpers/platform';
import { addVirtualEntry } from '../helpers/virtualModules'; import { addVirtualEntry } from '../helpers/virtualModules';
import { env as _env, IWebpackEnv } from '../index'; import { env as _env, IWebpackEnv } from '../index';
import base from './base'; import base from './base';
@ -36,15 +36,14 @@ export default function (config: Config, env: IWebpackEnv = _env): Config {
config.module config.module
.rule('hmr-core') .rule('hmr-core')
.test(/\.js$/) .test(/\.js$/)
.exclude .exclude.add(/node_modules/)
.add(/node_modules/)
.add(entryPath) .add(entryPath)
.end() .end()
.use('nativescript-hot-loader') .use('nativescript-hot-loader')
.loader('nativescript-hot-loader') .loader('nativescript-hot-loader')
.options({ .options({
appPath: getEntryDirPath() appPath: getEntryDirPath(),
}) });
return config; return config;
} }

View File

@ -53,14 +53,12 @@ function getSvelteConfigPreprocessor(): any {
} }
interface ISvelteConfig { interface ISvelteConfig {
preprocess: any preprocess: any;
} }
function getSvelteConfig(): ISvelteConfig | undefined { function getSvelteConfig(): ISvelteConfig | undefined {
try { try {
return require( return require(getProjectFilePath('svelte.config.js')) as ISvelteConfig;
getProjectFilePath('svelte.config.js')
) as ISvelteConfig;
} catch (err) { } catch (err) {
error('Could not find svelte.config.js.', err); error('Could not find svelte.config.js.', err);
} }

View File

@ -1,6 +1,6 @@
import Config from 'webpack-chain'; import Config from 'webpack-chain';
import { getEntryDirPath, getEntryPath } from "../helpers/platform"; import { getEntryDirPath, getEntryPath } from '../helpers/platform';
import { addVirtualEntry } from '../helpers/virtualModules'; import { addVirtualEntry } from '../helpers/virtualModules';
import { env as _env, IWebpackEnv } from '../index'; import { env as _env, IWebpackEnv } from '../index';
import base from './base'; import base from './base';
@ -36,15 +36,14 @@ export default function (config: Config, env: IWebpackEnv = _env): Config {
config.module config.module
.rule('hmr-core') .rule('hmr-core')
.test(/\.(js|ts)$/) .test(/\.(js|ts)$/)
.exclude .exclude.add(/node_modules/)
.add(/node_modules/)
.add(entryPath) .add(entryPath)
.end() .end()
.use('nativescript-hot-loader') .use('nativescript-hot-loader')
.loader('nativescript-hot-loader') .loader('nativescript-hot-loader')
.options({ .options({
appPath: getEntryDirPath() appPath: getEntryDirPath(),
}) });
return config; return config;
} }

View File

@ -3,10 +3,10 @@ import { merge } from 'webpack-merge';
import Config from 'webpack-chain'; import Config from 'webpack-chain';
import fs from 'fs'; import fs from 'fs';
import { hasDependency } from "../helpers/dependencies"; import { hasDependency } from '../helpers/dependencies';
import { getPlatformName } from '../helpers/platform'; import { getPlatformName } from '../helpers/platform';
import { env as _env, IWebpackEnv } from '../index'; import { env as _env, IWebpackEnv } from '../index';
import { error } from "../helpers/log"; import { error } from '../helpers/log';
import base from './base'; import base from './base';
export default function (config: Config, env: IWebpackEnv = _env): Config { 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(); const platform = getPlatformName();
// we need to patch VueLoader if we want to enable hmr // we need to patch VueLoader if we want to enable hmr
if(env.hmr) { if (env.hmr) {
patchVueLoaderForHMR() patchVueLoaderForHMR();
} }
// resolve .vue files // resolve .vue files
@ -82,12 +82,15 @@ export default function (config: Config, env: IWebpackEnv = _env): Config {
*/ */
function patchVueLoaderForHMR() { function patchVueLoaderForHMR() {
try { 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 source = fs.readFileSync(vueLoaderPath).toString();
const patchedSource = source.replace(/(isServer\s=\s)(target\s===\s'node')/g, '$1false;') const patchedSource = source.replace(
fs.writeFileSync(vueLoaderPath, patchedSource) /(isServer\s=\s)(target\s===\s'node')/g,
delete require.cache[vueLoaderPath] '$1false;'
);
fs.writeFileSync(vueLoaderPath, patchedSource);
delete require.cache[vueLoaderPath];
} catch (err) { } 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 * @internal
*/ */
export let additionalCopyRules = [] export let additionalCopyRules = [];
/** /**
* Utility to add new copy rules. Accepts a glob or an object. For example * 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 * @param {string|object} globOrObject
*/ */
export function addCopyRule(globOrObject: string | object) { export function addCopyRule(globOrObject: string | object) {
if(typeof globOrObject === 'string') { if (typeof globOrObject === 'string') {
return copyRules.add(globOrObject); return copyRules.add(globOrObject);
} }
additionalCopyRules.push(globOrObject) additionalCopyRules.push(globOrObject);
} }
/** /**
@ -72,12 +72,14 @@ export function applyCopyRules(config: Config) {
config.plugin('CopyWebpackPlugin').use(CopyWebpackPlugin, [ config.plugin('CopyWebpackPlugin').use(CopyWebpackPlugin, [
{ {
patterns: Array.from(copyRules).map((glob) => ({ patterns: Array.from(copyRules)
from: glob, .map((glob) => ({
context: entryDir, from: glob,
noErrorOnMissing: true, context: entryDir,
globOptions, noErrorOnMissing: true,
})).concat(additionalCopyRules), globOptions,
}))
.concat(additionalCopyRules),
}, },
]); ]);
} }

View File

@ -8,7 +8,9 @@ interface IReplacementMap {
/** /**
* @internal * @internal
*/ */
export function getFileReplacementsFromEnv(env: IWebpackEnv = _env): IReplacementMap { export function getFileReplacementsFromEnv(
env: IWebpackEnv = _env
): IReplacementMap {
const fileReplacements: IReplacementMap = {}; const fileReplacements: IReplacementMap = {};
const entries: string[] = (() => { const entries: string[] = (() => {
@ -17,10 +19,10 @@ export function getFileReplacementsFromEnv(env: IWebpackEnv = _env): IReplacemen
} }
if (typeof env.replace === 'string') { if (typeof env.replace === 'string') {
return [env.replace] return [env.replace];
} }
return [] return [];
})(); })();
entries.forEach((replaceEntry) => { entries.forEach((replaceEntry) => {

View File

@ -1,5 +1,5 @@
import dedent from 'ts-dedent'; 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 // de-indents strings so multi-line string literals can be used
function cleanup(data: any[]) { function cleanup(data: any[]) {
@ -29,7 +29,7 @@ export function warn(...data: any): void {
} }
export function info(...data: any): void { export function info(...data: any): void {
if(env.verbose) { if (env.verbose) {
console.log(`[@nativescript/webpack] Info: \n`, ...cleanup(data)); console.log(`[@nativescript/webpack] Info: \n`, ...cleanup(data));
} }
} }

View File

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

View File

@ -6,92 +6,109 @@
if (module.hot) { if (module.hot) {
let hash = __webpack_require__.h(); let hash = __webpack_require__.h();
const logVerbose = (title: string, ...info?: any) => { const logVerbose = (title: string, ...info: any) => {
if (__NS_ENV_VERBOSE__) { if (__NS_ENV_VERBOSE__) {
console.log(`[HMR][Verbose] ${title}`) console.log(`[HMR][Verbose] ${title}`);
if (info?.length) { if (info?.length) {
console.log(...info) console.log(...info);
console.log('---') 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 // format is important - CLI expects this exact format
console.log(`[HMR][${hash}] ${status} | ${message}`) console.log(`[HMR][${hash}] ${status} | ${message}`);
if (info?.length) { if (info?.length) {
logVerbose('Additional Info', info) logVerbose('Additional Info', info);
} }
// return true if operation was successful // return true if operation was successful
return status === 'success' return status === 'success';
} };
const applyOptions = { const applyOptions = {
ignoreUnaccepted: false, ignoreUnaccepted: false,
ignoreDeclined: false, ignoreDeclined: false,
ignoreErrored: false, ignoreErrored: false,
onDeclined(info) { onDeclined(info) {
setStatus(hash, 'failure', 'A module has been declined.', info) setStatus(hash, 'failure', 'A module has been declined.', info);
}, },
onUnaccepted(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) { onAccepted(info) {
// console.log('accepted', info) // console.log('accepted', info)
logVerbose('Module Accepted', info) logVerbose('Module Accepted', info);
}, },
onDisposed(info) { onDisposed(info) {
// console.log('disposed', info) // console.log('disposed', info)
logVerbose('Module Disposed', info) logVerbose('Module Disposed', info);
}, },
onErrored(info) { onErrored(info) {
setStatus(hash, 'failure', 'A module has errored.', info) setStatus(hash, 'failure', 'A module has errored.', info);
} },
} };
const checkAndApply = async () => { const checkAndApply = async () => {
hash = __webpack_require__.h(); hash = __webpack_require__.h();
const modules = await module.hot.check().catch(error => { const modules = await module.hot.check().catch((error) => {
return setStatus(hash, 'failure', 'Failed to check.', error.message || error.stack) return setStatus(
}) hash,
'failure',
'Failed to check.',
error.message || error.stack
);
});
if (!modules) { if (!modules) {
logVerbose('No modules to apply.') logVerbose('No modules to apply.');
return false; return false;
} }
const appliedModules = await module.hot.apply(applyOptions).catch(error => { const appliedModules = await module.hot
return setStatus(hash, 'failure', 'Failed to apply.', error.message || error.stack) .apply(applyOptions)
}) .catch((error) => {
return setStatus(
hash,
'failure',
'Failed to apply.',
error.message || error.stack
);
});
if (!appliedModules) { if (!appliedModules) {
logVerbose('No modules applied.') logVerbose('No modules applied.');
return false; return false;
} }
return setStatus(hash, 'success', 'Successfully applied update.') return setStatus(hash, 'success', 'Successfully applied update.');
} };
const hasUpdate = () => { const hasUpdate = () => {
try { try {
__non_webpack_require__(`~/bundle.${__webpack_hash__}.hot-update.json`) __non_webpack_require__(`~/bundle.${__webpack_hash__}.hot-update.json`);
return true; return true;
} catch (err) { } catch (err) {
return false; return false;
} }
} };
const originalOnLiveSync = global.__onLiveSync const originalOnLiveSync = global.__onLiveSync;
global.__onLiveSync = async function () { global.__onLiveSync = async function () {
logVerbose('LiveSync') logVerbose('LiveSync');
if (!hasUpdate()) { if (!hasUpdate()) {
return; return;
} }
await checkAndApply() await checkAndApply();
originalOnLiveSync(); originalOnLiveSync();
}; };
} }

View File

@ -1,31 +1,33 @@
import { relative, resolve } from "path"; import { relative, resolve } from 'path';
import dedent from "ts-dedent"; import dedent from 'ts-dedent';
import fs from 'fs'; import fs from 'fs';
// note: this will bail even if module.hot appears in a comment // 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) { export default function loader(content: string, map: any) {
if (MODULE_HOT_RE.test(content)) { if (MODULE_HOT_RE.test(content)) {
// Code already handles HMR - we don't need to do anything // 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(); const opts = this.getOptions();
// used to inject the HMR runtime into the entry file // used to inject the HMR runtime into the entry file
if(opts.injectHMRRuntime) { if (opts.injectHMRRuntime) {
const hmrRuntimePath = resolve(__dirname, './hmr.runtime.js') const hmrRuntimePath = resolve(__dirname, './hmr.runtime.js');
const hmrRuntime = fs.readFileSync(hmrRuntimePath).toString() const hmrRuntime = fs
.readFileSync(hmrRuntimePath)
.toString()
.split('// ---')[1] .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( const relativePath = relative(
opts.appPath ?? this.rootContext, opts.appPath ?? this.rootContext,
this.resourcePath this.resourcePath
).replace(/\\/g, '/') ).replace(/\\/g, '/');
const hmrCode = this.hot const hmrCode = this.hot
? dedent` ? 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 WorkerDependency = require('webpack/lib/dependencies/WorkerDependency');
const RuntimeGlobals = require("webpack/lib/RuntimeGlobals"); const RuntimeGlobals = require('webpack/lib/RuntimeGlobals');
/** /**
* Patch WorkerDependency to change: * 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: * break when the dependency range changes, for example if this PR is merged:
* - https://github.com/webpack/webpack/pull/12750 * - 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 { chunkGraph, moduleGraph, runtimeRequirements } = templateContext;
const dep = /** @type {WorkerDependency} */ (dependency); const dep = /** @type {WorkerDependency} */ dependency;
const block = /** @type {AsyncDependenciesBlock} */ (moduleGraph.getParentBlock( const block = /** @type {AsyncDependenciesBlock} */ moduleGraph.getParentBlock(
dependency dependency
)); );
const entrypoint = /** @type {Entrypoint} */ (chunkGraph.getBlockChunkGroup( const entrypoint = /** @type {Entrypoint} */ chunkGraph.getBlockChunkGroup(
block block
)); );
const chunk = entrypoint.getEntrypointChunk(); const chunk = entrypoint.getEntrypointChunk();
// runtimeRequirements.add(RuntimeGlobals.publicPath); // runtimeRequirements.add(RuntimeGlobals.publicPath);
@ -40,9 +44,9 @@ WorkerDependency.Template.prototype.apply = function apply(dependency, source, t
RuntimeGlobals.getChunkScriptFilename RuntimeGlobals.getChunkScriptFilename
}(${JSON.stringify(chunk.id)})` }(${JSON.stringify(chunk.id)})`
); );
} };
const NEW_WORKER_WITH_STRING_RE = /new\s+Worker\((['"`].+['"`])\)/ const NEW_WORKER_WITH_STRING_RE = /new\s+Worker\((['"`].+['"`])\)/;
/** /**
* Replaces * Replaces
@ -51,7 +55,9 @@ const NEW_WORKER_WITH_STRING_RE = /new\s+Worker\((['"`].+['"`])\)/
* new Worker(new URL('./somePath', import.meta.url)) * new Worker(new URL('./somePath', import.meta.url))
*/ */
export default function loader(content: string, map: any) { 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))') const source = content.replace(
this.callback(null, source, map) 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 id = 'WatchStatePlugin';
const version = 1; const version = 1;
@ -26,15 +26,15 @@ export class WatchStatePlugin {
if (env.verbose) { if (env.verbose) {
if (compiler.modifiedFiles) { if (compiler.modifiedFiles) {
Array.from(compiler.modifiedFiles).forEach(file => { Array.from(compiler.modifiedFiles).forEach((file) => {
console.log(`MODIFIED: ${file}`) console.log(`MODIFIED: ${file}`);
}) });
} }
if (compiler.removedFiles) { if (compiler.removedFiles) {
Array.from(compiler.removedFiles).forEach(file => { Array.from(compiler.removedFiles).forEach((file) => {
console.log(`REMOVED: ${file}`) console.log(`REMOVED: ${file}`);
}) });
} }
} }
} }
@ -74,7 +74,7 @@ export class WatchStatePlugin {
data: { data: {
emittedAssets, emittedAssets,
staleAssets, staleAssets,
} },
}); });
}); });
} }