Skip to content

Commit

Permalink
feat: adds suffix templating
Browse files Browse the repository at this point in the history
  • Loading branch information
IKatsuba committed Jul 13, 2021
1 parent cb0b555 commit ae38c4b
Show file tree
Hide file tree
Showing 4 changed files with 71 additions and 47 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,12 @@ describe('SharedLibraryWebpackPlugin', () => {
describe('Конфигурация libs', () => {
it('Если в libs передать строку, то на выходе получим массив конфигов с одним элементом', function () {
expect(new SharedLibraryWebpackPlugin({ libs: 'lib' }).libs).toEqual([
{ deps: [], pattern: 'lib', separator: '-' },
{
deps: [],
pattern: 'lib',
separator: '-',
suffix: "${major}.${minor}${prerelease ? '-' + prerelease : ''}",
},
]);
});

Expand All @@ -115,9 +120,24 @@ describe('SharedLibraryWebpackPlugin', () => {
],
}).libs
).toEqual([
{ deps: [], pattern: 'lib', separator: '-' },
{ deps: [], name: 'lib2', separator: '-' },
{ deps: ['lib3'], pattern: 'lib/*', separator: '.' },
{
deps: [],
pattern: 'lib',
separator: '-',
suffix: "${major}.${minor}${prerelease ? '-' + prerelease : ''}",
},
{
deps: [],
name: 'lib2',
separator: '-',
suffix: "${major}.${minor}${prerelease ? '-' + prerelease : ''}",
},
{
deps: ['lib3'],
pattern: 'lib/*',
separator: '.',
suffix: "${major}.${minor}${prerelease ? '-' + prerelease : ''}",
},
]);
});
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,13 @@ import { parse } from 'path';
import { v4 as uuidV4 } from 'uuid';

import {
compileSuffix,
createUniqueHash,
enforceSourceToString,
findClosestPackageJsonWithVersion,
getPackageVersion,
getTapFor,
isFnWithName,
suffixFromVersion,
} from './utils';
import { createHash } from 'crypto';

Expand Down Expand Up @@ -127,15 +128,17 @@ export interface SharedLibraryWebpackPluginOptions {
* Плагин для шаринга библиотек между приложениями
*/
export class SharedLibraryWebpackPlugin implements Plugin {
public static readonly defaultSharedLibraryNamespace = '__shared_libs_b8__';
private static readonly defaultSharedLibrarySearch: SharedLibrarySearchConfig = {
separator: '-',
deps: [],
suffix: "${major}.${minor}${prerelease ? '-' + prerelease : ''}",
};

public static readonly defaultSharedLibraryNamespace = '__shared_libs_b8__';

private static readonly moduleSeparator = '___module_separator___';

/**
* {@see SharedLibraryWebpackPluginOptions#libs}
*/
public readonly libs: ReadonlyArray<SharedLibrarySearchConfig>;
/**
* Список чанков с модулями для шаринга и соответсвующие им entry
*/
Expand All @@ -147,10 +150,6 @@ export class SharedLibraryWebpackPlugin implements Plugin {
* {@see SharedLibraryWebpackPluginOptions#namespace}
*/
private readonly namespace: string;
/**
* {@see SharedLibraryWebpackPluginOptions#libs}
*/
public readonly libs: ReadonlyArray<SharedLibrarySearchConfig>;
private compilation: compilation.Compilation & { addChunk: AddChunk };
private readonly patchRequireFnCache = new Map<string, string>();
private readonly disableDefaultJsonpFunctionChange: boolean;
Expand Down Expand Up @@ -746,7 +745,10 @@ if(installedChunks[depId] !== 0){
return [
...result,
camelCase(name),
suffixFromVersion(require(`${name}/package.json`).version),
compileSuffix(
SharedLibraryWebpackPlugin.defaultSharedLibrarySearch.suffix,
getPackageVersion(require(`${name}/package.json`).version)
),
];
}, []);
}
Expand All @@ -763,22 +765,20 @@ if(installedChunks[depId] !== 0){
librarySearchConfig: SharedLibrarySearchConfig,
module: { userRequest: string; rawRequest?: string }
): string | null {
let { suffix } = librarySearchConfig;

if (isNil(suffix)) {
const { version } =
findClosestPackageJsonWithVersion(parse(module.userRequest).dir) || {};
const { suffix } = librarySearchConfig;

if (!version) {
this.logger.warn(`Не найдена версия для пакета '${module.rawRequest}'`);
const { version } =
findClosestPackageJsonWithVersion(parse(module.userRequest).dir) || {};

return null;
}
let templateData = {};

suffix = suffixFromVersion(version);
if (!version) {
this.logger.warn(`Не найдена версия для пакета '${module.rawRequest}'`);
} else {
templateData = { ...templateData, ...getPackageVersion(version) };
}

return suffix;
return compileSuffix(suffix, templateData);
}

/**
Expand Down
10 changes: 0 additions & 10 deletions libs/shared-library-webpack-plugin/src/lib/utils.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import {
getTapFor,
goUpFolders,
isFnWithName,
suffixFromVersion,
} from './utils';
import * as jscodeshift from 'jscodeshift';
import { ConcatSource } from 'webpack-sources';
Expand Down Expand Up @@ -108,15 +107,6 @@ describe('findClosestPackageJsonWithVersion', () => {
});
});

describe('suffixFromVersion', () => {
it('Если версия не содержит пререлизного тега, то возвращается минор и мажор', function () {
expect(suffixFromVersion('1.2.3')).toEqual('1.2');
});
it('Если версия содержит пререлизный тег, то возвращается минор, мажор и тег', function () {
expect(suffixFromVersion('1.2.3-next.0')).toEqual('1.2-next.0');
});
});

describe('createUniqueHash', () => {
it('Если', () => {
const hash1 = createUniqueHash('string');
Expand Down
38 changes: 26 additions & 12 deletions libs/shared-library-webpack-plugin/src/lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { existsSync, readFileSync } from 'fs';
import { FunctionDeclaration } from 'jscodeshift';
import * as semver from 'semver';
import { createHash } from 'crypto';
import { template } from 'lodash';

/**
* [Конфиг хука]{@see Tap} с приоритетом
Expand Down Expand Up @@ -77,18 +78,31 @@ export function findClosestPackageJsonWithVersion(
return null;
}

/**
* Вырезает patch из версии
* @param version
*/
export function suffixFromVersion(version: string): string {
const { major, minor, prerelease } = semver.parse(version);

// Убираем из версии patch, делая предположение что большинство библиотек
// придерживаются semantic release, но оставляем пререлизные теги
return (
`${major}.${minor}` + (prerelease.length ? `-${prerelease.join('.')}` : '')
);
export interface PackageVersion {
major: string;
minor: string;
patch: string;
prerelease?: string;
}

export function getPackageVersion(version: string): PackageVersion {
const { major, minor, prerelease, patch } = semver.parse(version);

return {
major,
minor,
prerelease: prerelease.length ? `-${prerelease.join('.')}` : '',
patch,
};
}

export function compileSuffix(
suffix: string,
data: Partial<PackageVersion> & Record<string, any>
): string {
const compiled = template(suffix);

return compiled(data);
}

const usedIds = new Set<string>();
Expand Down

0 comments on commit ae38c4b

Please sign in to comment.