Skip to content

Commit

Permalink
refactor: generators (#2350)
Browse files Browse the repository at this point in the history
  • Loading branch information
alexander-akait committed Jan 13, 2021
1 parent 7314d6c commit 56569a7
Show file tree
Hide file tree
Showing 26 changed files with 144 additions and 231 deletions.
Expand Up @@ -20,7 +20,7 @@ Object {
},
"plugins": Array [
"new webpack.ProgressPlugin()",
"new workboxPlugin.GenerateSW({
"new WorkboxWebpackPlugin.GenerateSW({
swDest: 'sw.js',
clientsClaim: true,
skipWaiting: false,
Expand Down Expand Up @@ -53,7 +53,7 @@ Object {
},
"plugins": Array [
"new webpack.ProgressPlugin()",
"new workboxPlugin.GenerateSW({
"new WorkboxWebpackPlugin.GenerateSW({
swDest: 'sw.js',
clientsClaim: true,
skipWaiting: false,
Expand Down Expand Up @@ -112,7 +112,7 @@ Object {
"plugins": Array [
"new webpack.ProgressPlugin()",
"new MiniCssExtractPlugin({ filename:'main.[contenthash].css' })",
"new workboxPlugin.GenerateSW({
"new WorkboxWebpackPlugin.GenerateSW({
swDest: 'sw.js',
clientsClaim: true,
skipWaiting: false,
Expand Down Expand Up @@ -148,7 +148,7 @@ Object {
},
"plugins": Array [
"new webpack.ProgressPlugin()",
"new workboxPlugin.GenerateSW({
"new WorkboxWebpackPlugin.GenerateSW({
swDest: 'sw.js',
clientsClaim: true,
skipWaiting: false,
Expand All @@ -173,7 +173,7 @@ Object {
},
"plugins": Array [
"new webpack.ProgressPlugin()",
"new workboxPlugin.GenerateSW({
"new WorkboxWebpackPlugin.GenerateSW({
swDest: 'sw.js',
clientsClaim: true,
skipWaiting: false,
Expand All @@ -194,7 +194,7 @@ Object {
},
"plugins": Array [
"new webpack.ProgressPlugin()",
"new workboxPlugin.GenerateSW({
"new WorkboxWebpackPlugin.GenerateSW({
swDest: 'sw.js',
clientsClaim: true,
skipWaiting: false,
Expand All @@ -219,7 +219,7 @@ Object {
},
"plugins": Array [
"new webpack.ProgressPlugin()",
"new workboxPlugin.GenerateSW({
"new WorkboxWebpackPlugin.GenerateSW({
swDest: 'sw.js',
clientsClaim: true,
skipWaiting: false,
Expand All @@ -243,7 +243,7 @@ Object {
"new HtmlWebpackPlugin({
template: 'index.html'
})",
"new workboxPlugin.GenerateSW({
"new WorkboxWebpackPlugin.GenerateSW({
swDest: 'sw.js',
clientsClaim: true,
skipWaiting: false,
Expand Down
4 changes: 2 additions & 2 deletions packages/generators/__tests__/init-generator.test.ts
Expand Up @@ -39,7 +39,7 @@ describe('init generator', () => {
open: true,
});
expect(config.plugins.length).toBe(2);
expect(config.plugins[1]).toContain('workboxPlugin');
expect(config.plugins[1]).toContain('WorkboxWebpackPlugin');

// match config snapshot
expect(config).toMatchSnapshot();
Expand Down Expand Up @@ -245,7 +245,7 @@ describe('init generator', () => {
});
expect(config.plugins.length).toBe(3);
expect(config.plugins[1]).toContain('HtmlWebpackPlugin');
expect(config.plugins[2]).toContain('workboxPlugin');
expect(config.plugins[2]).toContain('WorkboxWebpackPlugin');

// match config snapshot
expect(config).toMatchSnapshot();
Expand Down
30 changes: 0 additions & 30 deletions packages/generators/__tests__/utils/plugins.test.ts

This file was deleted.

1 change: 0 additions & 1 deletion packages/generators/src/index.ts
Expand Up @@ -58,7 +58,6 @@ export { addonGenerator, initGenerator };
export * from './utils/ast-utils';
export * from './utils/copy-utils';
export * from './utils/modify-config-helper';
export * from './utils/npm-exists';
export * from './utils/npm-packages-exists';
export * from './utils/recursive-parser';
export * from './utils/resolve-packages';
Expand Down
14 changes: 7 additions & 7 deletions packages/generators/src/init-generator.ts
Expand Up @@ -4,7 +4,7 @@ import logSymbols from 'log-symbols';
import path from 'path';
import { Confirm, Input, List } from './utils/scaffold-utils';

import { LangType, langQuestionHandler, tooltip, generatePluginName, StylingType, styleQuestionHandler, entryQuestions } from './utils';
import { LangType, langQuestionHandler, tooltip, StylingType, styleQuestionHandler, entryQuestions } from './utils';
import { CustomGenerator } from './types';

const { logger, getPackageManager } = utils;
Expand Down Expand Up @@ -59,7 +59,7 @@ export default class InitGenerator extends CustomGenerator {
const self: this = this;

logger.log(
`\n${logSymbols.info}${blue(' INFO ')} ` +
`${logSymbols.info}${blue(' INFO ')} ` +
'For more information and a detailed description of each question, have a look at: ' +
`${bold(green('https://github.com/webpack/webpack-cli/blob/master/INIT.md'))}`,
);
Expand Down Expand Up @@ -195,17 +195,17 @@ export default class InitGenerator extends CustomGenerator {
false,
this.autoGenerateConfig,
);

if (useHTMLPlugin) {
// Html webpack Plugin
this.dependencies.push('html-webpack-plugin');
const htmlWebpackDependency = 'html-webpack-plugin';
const htmlwebpackPlugin = generatePluginName(htmlWebpackDependency);
(this.configuration.config.topScope as string[]).push(
`const ${htmlwebpackPlugin} = require('${htmlWebpackDependency}')`,
`const HtmlWebpackPlugin = require('${htmlWebpackDependency}')`,
'\n',
tooltip.html(),
);
(this.configuration.config.webpackOptions.plugins as string[]).push(`new ${htmlwebpackPlugin}({
(this.configuration.config.webpackOptions.plugins as string[]).push(`new HtmlWebpackPlugin({
template: 'index.html'
})`);
}
Expand All @@ -219,9 +219,9 @@ export default class InitGenerator extends CustomGenerator {
);
// webpack Dev Server
if (useWorkboxPlugin) {
this.configuration.config.topScope.push("const workboxPlugin = require('workbox-webpack-plugin');", '\n');
this.configuration.config.topScope.push("const WorkboxWebpackPlugin = require('workbox-webpack-plugin');", '\n');
this.dependencies.push('workbox-webpack-plugin');
(this.configuration.config.webpackOptions.plugins as string[]).push(`new workboxPlugin.GenerateSW({
(this.configuration.config.webpackOptions.plugins as string[]).push(`new WorkboxWebpackPlugin.GenerateSW({
swDest: 'sw.js',
clientsClaim: true,
skipWaiting: false,
Expand Down
16 changes: 0 additions & 16 deletions packages/generators/src/utils/__tests__/npm-exists.test.ts

This file was deleted.

@@ -1,7 +1,6 @@
import { npmPackagesExists } from '../npm-packages-exists';
import { resolvePackages } from '../resolve-packages';

jest.mock('../npm-exists');
jest.mock('../resolve-packages');

// TS is not aware that jest changes the type of resolvePackages
Expand All @@ -10,6 +9,7 @@ const mockResolvePackages = resolvePackages as jest.Mock<typeof resolvePackages>
describe('npmPackagesExists', () => {
test('resolves packages when they are available on the local filesystem', () => {
npmPackagesExists(['./testpkg']);

expect(mockResolvePackages.mock.calls[mockResolvePackages.mock.calls.length - 1][0]).toEqual(['./testpkg']);
});

Expand Down
9 changes: 6 additions & 3 deletions packages/generators/src/utils/__tests__/run-prettier.test.ts
Expand Up @@ -2,7 +2,6 @@

import fs from 'fs';
import path from 'path';
//eslint-disable-next-line node/no-extraneous-import
import rimraf from 'rimraf';
import { runPrettier } from '../run-prettier';

Expand All @@ -22,19 +21,23 @@ describe('runPrettier', () => {

it('should run prettier on JS string and write file', () => {
runPrettier(outputFile, 'console.log("1");console.log("2");');

expect(fs.existsSync(outputFile)).toBeTruthy();

const data = fs.readFileSync(outputFile, 'utf8');
expect(data).toContain("console.log('1');\n");

expect(data).toContain('console.log("1");');
expect(consoleSpy).toHaveBeenCalledTimes(0);
});

it('prettier should fail on invalid JS, with file still written', () => {
runPrettier(outputFile, '"');

expect(fs.existsSync(outputFile)).toBeTruthy();

const data = fs.readFileSync(outputFile, 'utf8');
expect(data).toContain('"');

expect(data).toContain('"');
expect(consoleSpy).toHaveBeenCalledTimes(1);
expect(consoleSpy.mock.calls[0][0]).toContain('WARNING: Could not apply prettier');
});
Expand Down
6 changes: 6 additions & 0 deletions packages/generators/src/utils/copy-utils.ts
Expand Up @@ -10,8 +10,11 @@ import path from 'path';
*/
export const generatorCopy = (generator, templateDir: string): ((filePath: string) => void) => (filePath: string): void => {
const sourceParts = templateDir.split(path.delimiter);

sourceParts.push(...filePath.split('/'));

const targetParts = path.dirname(filePath).split('/');

targetParts.push(path.basename(filePath, '.tpl'));

generator.fs.copy(path.join(...sourceParts), generator.destinationPath(path.join.apply(null, targetParts)));
Expand All @@ -32,8 +35,11 @@ export const generatorCopyTpl = (generator, templateDir: string, templateData: o
filePath: string,
): void => {
const sourceParts = templateDir.split(path.delimiter);

sourceParts.push(...filePath.split('/'));

const targetParts = path.dirname(filePath).split('/');

targetParts.push(path.basename(filePath, '.tpl').slice(1));

generator.fs.copyTpl(path.join(...sourceParts), generator.destinationPath(path.join.apply(null, targetParts)), templateData);
Expand Down
10 changes: 8 additions & 2 deletions packages/generators/src/utils/entry.ts
Expand Up @@ -15,19 +15,22 @@ import validate from './validate';
export default async function entry(self: Generator, multiEntries: boolean, autoGenerateDefaults = false): Promise<string | object> {
const fixEntry = (entry: string): string => {
entry = entry.trim().replace(/"|'/g, '');

if (!entry.startsWith('./')) {
entry = `./${entry}`;
}

if (!entry.endsWith('.js')) {
entry = entry.concat('.js');
}

entry = `'${entry}'`;

return entry;
};

if (multiEntries) {
const webpackEntryPoint: object = {};

const multipleEntriesAnswer = await InputValidate(
self,
'multipleEntries',
Expand All @@ -36,7 +39,6 @@ export default async function entry(self: Generator, multiEntries: boolean, auto
'pageOne, pageTwo',
autoGenerateDefaults,
);

const entryIdentifiers: string[] = multipleEntriesAnswer.multipleEntries.split(',');

for (let i = 0; i < entryIdentifiers.length; i++) {
Expand All @@ -50,11 +52,13 @@ export default async function entry(self: Generator, multiEntries: boolean, auto
autoGenerateDefaults,
);
const entry = fixEntry(entryResult[entryProp]);

webpackEntryPoint[entryProp] = entry;
}

return webpackEntryPoint;
}

const singleEntryResult = await Input(
self,
'singularEntry',
Expand All @@ -63,8 +67,10 @@ export default async function entry(self: Generator, multiEntries: boolean, auto
autoGenerateDefaults,
);
let { singularEntry } = singleEntryResult;

if (singularEntry.length > 0) {
singularEntry = fixEntry(singularEntry);
}

return singularEntry;
}
2 changes: 2 additions & 0 deletions packages/generators/src/utils/global-packages-path.ts
Expand Up @@ -14,9 +14,11 @@ const { getPackageManager } = utils;
*/
export function getPathToGlobalPackages(): string {
const manager: string = getPackageManager();

if (manager === 'yarn') {
try {
const yarnDir = sync('yarn', ['global', 'dir']).stdout;

return path.join(yarnDir, 'node_modules');
} catch (e) {
// Default to the global npm path below
Expand Down
4 changes: 0 additions & 4 deletions packages/generators/src/utils/index.ts
@@ -1,6 +1,5 @@
import entryQuestions from './entry';
import langQuestionHandler, { LangType, getBabelLoader, getTypescriptLoader } from './languageSupport';
import plugins, { replaceAt, generatePluginName } from './plugins';
import styleQuestionHandler, { StylingType, LoaderName, StyleRegex, Loader } from './styleSupport';
import tooltip from './tooltip';
import validate from './validate';
Expand All @@ -11,9 +10,6 @@ export {
LangType,
getBabelLoader,
getTypescriptLoader,
plugins,
replaceAt,
generatePluginName,
styleQuestionHandler,
StylingType,
LoaderName,
Expand Down
3 changes: 0 additions & 3 deletions packages/generators/src/utils/isWebpack5.ts

This file was deleted.

0 comments on commit 56569a7

Please sign in to comment.