arui-scripts 15.4.0 → 15.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- PASS src/configs/app-configs/__tests__/update-with-presets.tests.ts (12.976 s)
1
+ PASS src/configs/app-configs/__tests__/update-with-presets.tests.ts (14.006 s)
2
2
  PASS src/configs/util/__tests__/get-polyfills.tests.ts
3
3
  PASS src/configs/util/__tests__/apply-overrides.tests.ts
4
4
  PASS src/configs/app-configs/__tests__/update-with-env.tests.ts
@@ -87,5 +87,5 @@ PASS src/configs/app-configs/__tests__/validate-settings-keys.tests.ts
87
87
  Test Suites: 6 passed, 6 total
88
88
  Tests: 17 passed, 17 total
89
89
  Snapshots: 0 total
90
- Time: 15.742 s
90
+ Time: 15.427 s
91
91
  Ran all test suites.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # [15.3.0](https://github.com/core-ds/arui-scripts/compare/v15.2.0...v15.3.0) (2023-06-30)
2
2
 
3
+ ## 15.5.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#56](https://github.com/core-ds/arui-scripts/pull/56) [`1c64198`](https://github.com/core-ds/arui-scripts/commit/1c641989791c4ff1e7a20d05c115f8a1d7817e30) Thanks [@heymdall-legal](https://github.com/heymdall-legal)! - Add modules support and various tools to work with them correctly.
8
+
9
+ Modules provides a way to define reusable piece of code to consume from different applications.
10
+ Additional tooling provides a convenient way to consume this modules in applications.
11
+ Full documentation is available in [separate doc](https://github.com/core-ds/arui-scripts/blob/master/packages/arui-scripts/docs/modules.md).
12
+
13
+ ## 15.4.1
14
+
15
+ ### Patch Changes
16
+
17
+ - [#57](https://github.com/core-ds/arui-scripts/pull/57) [`3d35ddc`](https://github.com/core-ds/arui-scripts/commit/3d35ddc84a97a5324bdf8172be972826838148a8) Thanks [@vaagnavanesyan](https://github.com/vaagnavanesyan)! - move imagemin plugins to peer deps
18
+
19
+ - [#60](https://github.com/core-ds/arui-scripts/pull/60) [`2b38d23`](https://github.com/core-ds/arui-scripts/commit/2b38d230032dd8f7b1f1adba805d1dc238c74243) Thanks [@heymdall-legal](https://github.com/heymdall-legal)! - Fix presets loading
20
+
3
21
  ## 15.4.0
4
22
 
5
23
  ### Minor Changes
package/README.md CHANGED
@@ -80,7 +80,10 @@ npm install arui-scripts --save-dev
80
80
  - `keepCssVars` - отключает `postcss-custom-properties`, css переменные будут оставаться в бандле.
81
81
  - `removeDevDependenciesDuringDockerBuild` - отключает удаление devDependencies из node_modules при сборке докер образа. Используется когда вам не нужно удалять devDependencies, т.к. в своём Dockerfile вы не переносите node_modules в докер-контейнер.
82
82
  - `dataUrlMaxSize` - ресурсы, не превышающие данный размер (в байтах), будут включены в исходники `inline`, иначе вынесены в отдельный файл. По умолчанию `1536`.
83
- - `imageMinimizer` - раздел настроек, связанных с оптимизацией графики.
83
+ - `imageMinimizer` - раздел настроек, связанных с оптимизацией графики.<br/><br/>
84
+ :warning: **Внимание!** Если вы планируете использовать любые `imagemin`-плагины, кроме `svgo`, необходимо установить их дополнительно. <br/>
85
+ Так как после установки плагинам необходим прямой доступ в сеть для скачивания утилит (`cjpeg` и пр.), они указаны в `peerDependencies` `arui-scripts`, чтобы не приводить к ошибкам в закрытых контурах.<br/><br/>
86
+
84
87
  - `imageMinimizer.svg.enabled` - включает/отключает оптимизацию `svg`. По умолчанию `true`.
85
88
  - `imageMinimizer.gif.enabled` - включает/отключает оптимизацию `gif`. По умолчанию `false`.
86
89
  - `imageMinimizer.gif.optimizationLevel` - уровень сжатия `gif`. От `1` до `3`. По умолчанию `1`.
@@ -92,6 +95,8 @@ npm install arui-scripts --save-dev
92
95
  - `imageMinimizer.png.colorTypeReduction` - допускает изменение представления изображения (оттенки серого / прозрачность / пр.). По умолчанию `false`. [Подробнее](https://github.com/imagemin/imagemin-optipng#colortypereduction)
93
96
  - `imageMinimizer.png.paletteReduction` - допускает уменьшение палитры изображения. По умолчанию `false`. [Подробнее](https://github.com/imagemin/imagemin-optipng#palettereduction)
94
97
  - `imageMinimizer.png.interlaced` - потоковый порядок передачи изображение. По умолчанию этот параметр идентичен значению из входного изображения. [Подробнее](https://github.com/imagemin/imagemin-optipng#interlaced)
98
+ - `devServerCors` - включает добавление cors-заголовков в dev-server. Может быть полезным при локальном тестировании модулей.
99
+ - `modules`, `compatModules` - позволяет настраивать работу с модулями, подробнее в разделе [Модули](./docs/modules.md).
95
100
 
96
101
  В целях отладки все эти настройки можно переопределить не изменяя package.json
97
102
  Просто передайте необходимые настройки в environment переменной ARUI_SCRIPTS_CONFIG
@@ -16,19 +16,20 @@ const webpack_1 = __importDefault(require("webpack"));
16
16
  const webpack_bundle_analyzer_1 = require("webpack-bundle-analyzer");
17
17
  const make_tmp_dir_1 = __importDefault(require("../util/make-tmp-dir"));
18
18
  const webpack_client_prod_1 = __importDefault(require("../../configs/webpack.client.prod"));
19
+ const app_configs_1 = __importDefault(require("../../configs/app-configs"));
19
20
  (() => __awaiter(void 0, void 0, void 0, function* () {
20
21
  let clientWebpackConfigs = Array.isArray(webpack_client_prod_1.default) ? webpack_client_prod_1.default : [webpack_client_prod_1.default];
21
- const promises = clientWebpackConfigs.map((config, i) => __awaiter(void 0, void 0, void 0, function* () {
22
+ const promises = clientWebpackConfigs.map((webpackConfig, i) => __awaiter(void 0, void 0, void 0, function* () {
22
23
  const tmpDir = yield (0, make_tmp_dir_1.default)(i.toString());
23
- config.plugins = [
24
- ...config.plugins,
24
+ webpackConfig.plugins = [
25
+ ...(webpackConfig.plugins || []),
25
26
  new webpack_bundle_analyzer_1.BundleAnalyzerPlugin({
26
27
  generateStatsFile: true,
27
- statsFilename: config.statsOutputPath,
28
+ statsFilename: app_configs_1.default.statsOutputPath,
28
29
  analyzerPort: 'auto',
29
30
  }),
30
31
  ];
31
- config.output = Object.assign(Object.assign({}, config.output), { path: tmpDir });
32
+ webpackConfig.output = Object.assign(Object.assign({}, webpackConfig.output), { path: tmpDir });
32
33
  }));
33
34
  yield Promise.all(promises);
34
35
  (0, webpack_1.default)(clientWebpackConfigs).run(() => { });
@@ -52,6 +52,23 @@ export declare function calculateDependentConfig(config: AppConfigs): {
52
52
  } | undefined;
53
53
  componentsTheme: string | null;
54
54
  keepCssVars: boolean;
55
+ compatModules: {
56
+ shared?: {
57
+ [libraryName: string]: string;
58
+ } | undefined;
59
+ exposes?: {
60
+ [moduleId: string]: {
61
+ entry: string;
62
+ externals?: Record<string, string> | undefined;
63
+ cssPrefix?: string | false | undefined;
64
+ };
65
+ } | undefined;
66
+ } | null;
67
+ modules: {
68
+ name?: string | undefined;
69
+ shared: any;
70
+ exposes?: Record<string, string> | undefined;
71
+ } | null;
55
72
  };
56
73
  /**
57
74
  * Обновление контекста в зависимости от ключей конфига
@@ -10,6 +10,8 @@ const resolve_1 = require("../util/resolve");
10
10
  const CWD = process.cwd();
11
11
  const absoluteSrcPath = path_1.default.resolve(CWD, 'src');
12
12
  function getDefaultAppConfig() {
13
+ var _a;
14
+ const appPackage = getPackageJson();
13
15
  return {
14
16
  /// general settings
15
17
  clientServerPort: 8080,
@@ -18,7 +20,7 @@ function getDefaultAppConfig() {
18
20
  devSourceMaps: 'eval',
19
21
  devServerCors: false,
20
22
  useServerHMR: false,
21
- presets: null,
23
+ presets: ((_a = appPackage.aruiScripts) === null || _a === void 0 ? void 0 : _a.presets) || null,
22
24
  // paths
23
25
  buildPath: '.build',
24
26
  assetsPath: 'assets',
@@ -66,14 +68,21 @@ function getDefaultAppConfig() {
66
68
  // CSS
67
69
  componentsTheme: null,
68
70
  keepCssVars: false,
71
+ // Modules
72
+ compatModules: null,
73
+ modules: null,
69
74
  };
70
75
  }
71
76
  exports.getDefaultAppConfig = getDefaultAppConfig;
72
- function getDefaultAppContext() {
77
+ function getPackageJson() {
73
78
  const appPackage = JSON.parse(fs_1.default.readFileSync(path_1.default.join(CWD, 'package.json'), 'utf8'));
74
79
  if (appPackage['arui-scripts']) {
75
80
  throw Error('arui-scripts in package.json is not supported. Use aruiScripts instead.');
76
81
  }
82
+ return appPackage;
83
+ }
84
+ function getDefaultAppContext() {
85
+ const appPackage = getPackageJson();
77
86
  const absoluteNodeModulesPath = path_1.default.resolve(CWD, 'node_modules');
78
87
  const absoluteNodeModulesBinPath = path_1.default.resolve(absoluteNodeModulesPath, '.bin');
79
88
  const projectTsConfigPath = path_1.default.join(CWD, 'tsconfig.json');
@@ -51,6 +51,27 @@ export type AppConfigs = {
51
51
  };
52
52
  componentsTheme: string | null;
53
53
  keepCssVars: boolean;
54
+ compatModules: {
55
+ shared?: {
56
+ [libraryName: string]: string;
57
+ };
58
+ exposes?: {
59
+ [moduleId: string]: CompatModuleConfigBase;
60
+ };
61
+ } | null;
62
+ modules: {
63
+ name?: string;
64
+ shared: any;
65
+ exposes?: Record<string, string>;
66
+ } | null;
67
+ };
68
+ type CompatModuleConfigBase = {
69
+ entry: string;
70
+ externals?: Record<string, string>;
71
+ cssPrefix?: false | string;
72
+ };
73
+ export type CompatModuleConfig = CompatModuleConfigBase & {
74
+ name: string;
54
75
  };
55
76
  /**
56
77
  * Внутренний контекст arui-scripts
@@ -84,3 +105,4 @@ export type AppContext = {
84
105
  };
85
106
  export type AppContextWithConfigs = AppContext & AppConfigs;
86
107
  export type PackageSettings = Partial<AppConfigs>;
108
+ export {};
@@ -1,16 +1,2 @@
1
- declare const devServerConfig: {
2
- port: number;
3
- liveReload: boolean;
4
- client: {
5
- overlay: {
6
- errors: boolean;
7
- warnings: boolean;
8
- };
9
- };
10
- devMiddleware: {
11
- publicPath: string;
12
- };
13
- static: string[];
14
- proxy: any;
15
- };
1
+ declare const devServerConfig: import("webpack-dev-server").Configuration;
16
2
  export default devServerConfig;
@@ -32,10 +32,17 @@ const devServerConfig = (0, apply_overrides_1.default)('devServer', {
32
32
  const cspHeader = proxyRes.headers['content-security-policy'];
33
33
  if (typeof cspHeader === 'string' && !cspHeader.includes('unsafe-eval')) {
34
34
  proxyRes.headers['content-security-policy'] = cspHeader
35
- .replace(/script-src/, "script-src 'unsafe-eval'");
35
+ .replace(/script-src/, 'script-src \'unsafe-eval\'');
36
36
  }
37
- }
38
- } : {}))
39
- })
37
+ },
38
+ } : {})),
39
+ }),
40
+ headers: app_configs_1.default.devServerCors
41
+ ? {
42
+ 'Access-Control-Allow-Origin': '*',
43
+ 'Access-Control-Allow-Headers': '*',
44
+ 'Access-Control-Allow-Methods': '*',
45
+ }
46
+ : {},
40
47
  });
41
48
  exports.default = devServerConfig;
@@ -0,0 +1,16 @@
1
+ import webpack from 'webpack';
2
+ import { CompatModuleConfig } from './app-configs/types';
3
+ export declare function haveExposedDefaultModules(): Record<string, string> | undefined;
4
+ export declare const MODULES_ENTRY_NAME = "remoteEntry.js";
5
+ export declare function patchMainWebpackConfigForModules(webpackConf: webpack.Configuration): webpack.Configuration;
6
+ export declare function getCssPrefixForModule(module: CompatModuleConfig): string | undefined;
7
+ export declare function getExposeLoadersFormCompatModules(): {
8
+ test: string;
9
+ use: {
10
+ loader: string;
11
+ options: {
12
+ exposes: string[];
13
+ };
14
+ }[];
15
+ }[];
16
+ export declare function patchWebpackConfigForCompat(module: CompatModuleConfig, webpackConf: webpack.Configuration): webpack.Configuration;
@@ -0,0 +1,101 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.patchWebpackConfigForCompat = exports.getExposeLoadersFormCompatModules = exports.getCssPrefixForModule = exports.patchMainWebpackConfigForModules = exports.MODULES_ENTRY_NAME = exports.haveExposedDefaultModules = void 0;
7
+ const webpack_1 = __importDefault(require("webpack"));
8
+ const postcss_prefix_selector_1 = __importDefault(require("postcss-prefix-selector"));
9
+ const app_configs_1 = __importDefault(require("./app-configs"));
10
+ const find_loader_1 = require("./util/find-loader");
11
+ function haveExposedDefaultModules() {
12
+ var _a;
13
+ return (_a = app_configs_1.default.modules) === null || _a === void 0 ? void 0 : _a.exposes;
14
+ }
15
+ exports.haveExposedDefaultModules = haveExposedDefaultModules;
16
+ exports.MODULES_ENTRY_NAME = 'remoteEntry.js';
17
+ function patchMainWebpackConfigForModules(webpackConf) {
18
+ // Добавляем expose loader для библиотек, которые мы хотим вынести в глобальную область видимости
19
+ webpackConf.module.rules.unshift(...getExposeLoadersFormCompatModules());
20
+ if (!app_configs_1.default.modules || !webpackConf.output || !webpackConf.plugins) {
21
+ return webpackConf;
22
+ }
23
+ webpackConf.output.publicPath = haveExposedDefaultModules()
24
+ ? 'auto' // Для того чтобы модули могли подключаться из разных мест, нам необходимо использовать auto. Для корректной работы в IE надо подключaть https://github.com/amiller-gh/currentScript-polyfill
25
+ : app_configs_1.default.publicPath;
26
+ webpackConf.plugins.push(new webpack_1.default.container.ModuleFederationPlugin({
27
+ name: app_configs_1.default.modules.name || app_configs_1.default.normalizedName,
28
+ filename: app_configs_1.default.modules.exposes ? exports.MODULES_ENTRY_NAME : undefined,
29
+ shared: app_configs_1.default.modules.shared,
30
+ exposes: app_configs_1.default.modules.exposes,
31
+ }));
32
+ return webpackConf;
33
+ }
34
+ exports.patchMainWebpackConfigForModules = patchMainWebpackConfigForModules;
35
+ function getCssPrefixForModule(module) {
36
+ if (module.cssPrefix) {
37
+ return module.cssPrefix;
38
+ }
39
+ if (module.cssPrefix === false) {
40
+ return undefined;
41
+ }
42
+ return `.module-${module.name}`;
43
+ }
44
+ exports.getCssPrefixForModule = getCssPrefixForModule;
45
+ function getExposeLoadersFormCompatModules() {
46
+ var _a;
47
+ const shared = (_a = app_configs_1.default.compatModules) === null || _a === void 0 ? void 0 : _a.shared;
48
+ if (!shared) {
49
+ return [];
50
+ }
51
+ return Object.keys(shared).map((libraryName) => {
52
+ const globalVarName = shared[libraryName];
53
+ return {
54
+ test: require.resolve(libraryName),
55
+ use: [
56
+ {
57
+ loader: require.resolve('expose-loader'),
58
+ options: {
59
+ exposes: [globalVarName],
60
+ },
61
+ },
62
+ ],
63
+ };
64
+ });
65
+ }
66
+ exports.getExposeLoadersFormCompatModules = getExposeLoadersFormCompatModules;
67
+ function addPrefixCssRule(rule, prefix) {
68
+ if (!rule || !rule.use || !Array.isArray(rule.use)) {
69
+ return;
70
+ }
71
+ const postCssLoader = rule.use.find((loaderConfig) => {
72
+ var _a;
73
+ if (typeof loaderConfig === 'string' || typeof loaderConfig === 'function' || !loaderConfig) {
74
+ return false;
75
+ }
76
+ return ((_a = loaderConfig.loader) === null || _a === void 0 ? void 0 : _a.indexOf('postcss-loader')) !== -1;
77
+ });
78
+ if (!postCssLoader || typeof postCssLoader !== 'object' || !postCssLoader.options || typeof postCssLoader.options !== 'object') {
79
+ return;
80
+ }
81
+ postCssLoader.options.postcssOptions.plugins = [
82
+ ...postCssLoader.options.postcssOptions.plugins,
83
+ (0, postcss_prefix_selector_1.default)({ prefix }),
84
+ ];
85
+ }
86
+ function patchWebpackConfigForCompat(module, webpackConf) {
87
+ webpackConf.externals = Object.assign(Object.assign({}, (webpackConf.externals || {})), (module.externals || {}));
88
+ // Название переменной вебпака, которую он будет использовать для загрузки чанков. Важно чтобы для разных модулей они отличались,
89
+ // иначе несколько модулей из одного приложения будут конфликтовать между собой
90
+ webpackConf.output.uniqueName = module.name;
91
+ const cssPrefix = getCssPrefixForModule(module);
92
+ if (cssPrefix) {
93
+ // Добавляем префикс для css-классов, чтобы изолировать стили модуля от стилей основного приложения
94
+ const cssRule = (0, find_loader_1.findLoader)(webpackConf, '/\\.css$/');
95
+ const cssModulesRule = (0, find_loader_1.findLoader)(webpackConf, '/\\.module\\.css$/');
96
+ addPrefixCssRule(cssRule, cssPrefix);
97
+ addPrefixCssRule(cssModulesRule, `:global(${cssPrefix})`);
98
+ }
99
+ return webpackConf;
100
+ }
101
+ exports.patchWebpackConfigForCompat = patchWebpackConfigForCompat;
@@ -4,8 +4,11 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.processAssetsPluginOutput = void 0;
7
+ const path_1 = __importDefault(require("path"));
7
8
  const app_configs_1 = __importDefault(require("./app-configs"));
9
+ const modules_1 = require("./modules");
8
10
  function processAssetsPluginOutput(assets) {
11
+ var _a;
9
12
  let adjustedAssets = assets;
10
13
  Object.keys(adjustedAssets).forEach((key) => {
11
14
  // заменяем путь к файлам на корректный в случае если в нем есть 'auto/'
@@ -14,6 +17,17 @@ function processAssetsPluginOutput(assets) {
14
17
  js: replaceAutoPath(adjustedAssets[key].js),
15
18
  };
16
19
  });
20
+ // добавляем в манифест js-файлы для модулей
21
+ Object.keys(((_a = app_configs_1.default.modules) === null || _a === void 0 ? void 0 : _a.exposes) || {}).forEach((moduleName) => {
22
+ var _a, _b;
23
+ if ((_b = (_a = app_configs_1.default.compatModules) === null || _a === void 0 ? void 0 : _a.exposes) === null || _b === void 0 ? void 0 : _b[moduleName]) {
24
+ throw new Error(`Модуль ${moduleName} определен как module и как compat. Поменяйте название одного из модулей или удалите его`);
25
+ }
26
+ adjustedAssets[moduleName] = {
27
+ mode: 'default',
28
+ js: path_1.default.join(app_configs_1.default.publicPath, modules_1.MODULES_ENTRY_NAME),
29
+ };
30
+ });
17
31
  const result = Object.assign(Object.assign({}, adjustedAssets), { __metadata__: {
18
32
  version: app_configs_1.default.version,
19
33
  name: app_configs_1.default.normalizedName,
@@ -17,4 +17,5 @@ exports.serverExternalsExemptions = (0, apply_overrides_1.default)('serverExtern
17
17
  /^date-fns/,
18
18
  /^@corp-front\//,
19
19
  /^corp-sign-ui-react/,
20
+ /^@alfalab\/scripts-/,
20
21
  ]);
@@ -0,0 +1,2 @@
1
+ import webpack from "webpack";
2
+ export declare function findLoader(config: webpack.Configuration, testRule: string): webpack.RuleSetRule | undefined;
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.findLoader = void 0;
4
+ function findLoader(config, testRule) {
5
+ var _a;
6
+ for (const rule of config.module.rules) {
7
+ if (rule === '...' || !rule) {
8
+ // Webpack имеет странный тип для rules, который позволяет в него положить строку '...'. Успокаиваем TS
9
+ continue;
10
+ }
11
+ if (rule.test && rule.test.toString() === testRule) {
12
+ return rule;
13
+ }
14
+ if (rule.oneOf) {
15
+ for (const oneOfRule of rule.oneOf) {
16
+ if (oneOfRule && oneOfRule.test && ((_a = oneOfRule === null || oneOfRule === void 0 ? void 0 : oneOfRule.test) === null || _a === void 0 ? void 0 : _a.toString()) === testRule) {
17
+ return oneOfRule;
18
+ }
19
+ }
20
+ }
21
+ }
22
+ }
23
+ exports.findLoader = findLoader;
@@ -7,4 +7,4 @@ import { Entry } from './util/get-entry';
7
7
  * @param configName Имя конфигурации, если не указано, то используется имя по умолчанию
8
8
  */
9
9
  export declare const createSingleClientWebpackConfig: (mode: 'dev' | 'prod', entry: Entry, configName?: string) => Configuration;
10
- export declare const createClientWebpackConfig: (mode: 'dev' | 'prod') => webpack.Configuration;
10
+ export declare const createClientWebpackConfig: (mode: 'dev' | 'prod') => webpack.Configuration | webpack.Configuration[];
@@ -1,2 +1,2 @@
1
- declare const config: import("webpack").Configuration;
1
+ declare const config: import("webpack").Configuration | import("webpack").Configuration[];
2
2
  export default config;
@@ -27,6 +27,7 @@ const webpack_deduplication_plugin_1 = require("webpack-deduplication-plugin");
27
27
  const minimizers_1 = require("./config-extras/minimizers");
28
28
  const mini_svg_data_uri_1 = __importDefault(require("mini-svg-data-uri"));
29
29
  const process_assets_plugin_output_1 = require("./process-assets-plugin-output");
30
+ const modules_1 = require("./modules");
30
31
  const PnpWebpackPlugin = require('pnp-webpack-plugin');
31
32
  const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
32
33
  const noopPath = require.resolve('./util/noop');
@@ -53,16 +54,9 @@ const clientAssetsPlugin = new assets_webpack_plugin_1.default({
53
54
  * @param entry Точка входа, любой валидный вход для webpack
54
55
  * @param configName Имя конфигурации, если не указано, то используется имя по умолчанию
55
56
  */
56
- const createSingleClientWebpackConfig = (mode, entry, configName) => ({
57
- target: 'web',
58
- mode: mode === 'dev' ? 'development' : 'production',
59
- devtool: mode === 'dev' ? app_configs_1.default.devSourceMaps : 'source-map',
60
- entry: (0, get_entry_1.default)(entry, getSingleEntry, mode),
57
+ const createSingleClientWebpackConfig = (mode, entry, configName) => (Object.assign(Object.assign({}, (configName ? { name: configName } : {})), { target: 'web', mode: mode === 'dev' ? 'development' : 'production', devtool: mode === 'dev' ? app_configs_1.default.devSourceMaps : 'source-map', entry: (0, get_entry_1.default)(entry, getSingleEntry, mode),
61
58
  // in production mode we need to fail on first error
62
- bail: mode === 'prod',
63
- context: app_configs_1.default.cwd,
64
- name: configName,
65
- output: {
59
+ bail: mode === 'prod', context: app_configs_1.default.cwd, output: {
66
60
  assetModuleFilename: 'static/media/[name].[hash:8][ext]',
67
61
  // Add /* filename */ comments to generated require()s in the output.
68
62
  pathinfo: mode === 'dev',
@@ -76,8 +70,7 @@ const createSingleClientWebpackConfig = (mode, entry, configName) => ({
76
70
  devtoolModuleFilenameTemplate: (info) => path_1.default
77
71
  .relative(app_configs_1.default.appSrc, info.absoluteResourcePath)
78
72
  .replace(/\\/g, '/'),
79
- },
80
- optimization: {
73
+ }, optimization: {
81
74
  splitChunks: mode === 'prod'
82
75
  ? {
83
76
  chunks: "all",
@@ -153,8 +146,7 @@ const createSingleClientWebpackConfig = (mode, entry, configName) => ({
153
146
  // Оптимизации времени билда, см https://webpack.js.org/guides/build-performance/
154
147
  removeAvailableModules: mode !== 'dev',
155
148
  removeEmptyChunks: mode !== 'dev',
156
- },
157
- resolve: {
149
+ }, resolve: {
158
150
  // This allows you to set a fallback for where Webpack should look for modules.
159
151
  // We placed these paths second because we want `node_modules` to "win"
160
152
  // if there are any conflicts. This matches Node resolution mechanism.
@@ -173,21 +165,18 @@ const createSingleClientWebpackConfig = (mode, entry, configName) => ({
173
165
  extensions: ['.web.js', '.mjs', '.js', '.json', '.web.jsx', '.jsx', '.ts', '.tsx']
174
166
  })),
175
167
  ].filter(Boolean)),
176
- },
177
- resolveLoader: {
168
+ }, resolveLoader: {
178
169
  plugins: [
179
170
  PnpWebpackPlugin.moduleLoader(module),
180
171
  ],
181
- },
182
- cache: mode === 'dev'
172
+ }, cache: mode === 'dev'
183
173
  ? {
184
174
  type: 'filesystem',
185
175
  buildDependencies: {
186
176
  config: [__filename],
187
177
  },
188
178
  }
189
- : false,
190
- module: {
179
+ : false, module: {
191
180
  // typescript interface will be removed from modules, and we will get an error on correct code
192
181
  // see https://github.com/webpack/webpack/issues/7378
193
182
  strictExportPresence: !app_configs_1.default.tsconfig,
@@ -320,8 +309,7 @@ const createSingleClientWebpackConfig = (mode, entry, configName) => ({
320
309
  // ** STOP ** Are you adding a new loader?
321
310
  // Make sure to add the new loader(s) before asset modules
322
311
  ],
323
- },
324
- plugins: ([
312
+ }, plugins: ([
325
313
  assetsPlugin,
326
314
  clientAssetsPlugin,
327
315
  new webpack_1.default.DefinePlugin(Object.assign({
@@ -381,22 +369,34 @@ const createSingleClientWebpackConfig = (mode, entry, configName) => ({
381
369
  // This should works fine, since proptypes usage should be eliminated in production mode
382
370
  mode === 'prod' && !app_configs_1.default.keepPropTypes && new webpack_1.default.NormalModuleReplacementPlugin(/^react-style-proptype$/, noopPath),
383
371
  mode === 'prod' && !app_configs_1.default.keepPropTypes && new webpack_1.default.NormalModuleReplacementPlugin(/^thrift-services\/proptypes/, noopPath)
384
- ].filter(Boolean)),
385
- experiments: {
372
+ ].filter(Boolean)), experiments: {
386
373
  backCompat: app_configs_1.default.webpack4Compatibility,
387
- },
374
+ },
388
375
  // Без этого комиляция трирегилась на изменение в node_modules и приводила к утечке памяти
389
376
  watchOptions: {
390
377
  ignored: new RegExp(app_configs_1.default.watchIgnorePath.join('|')),
391
378
  aggregateTimeout: 100,
392
- },
379
+ },
393
380
  // Выключаем performance hints, т.к. размеры бандлов контролируются не в рамках arui-scripts
394
381
  performance: {
395
382
  hints: false,
396
- },
397
- });
383
+ } }));
398
384
  exports.createSingleClientWebpackConfig = createSingleClientWebpackConfig;
399
385
  const createClientWebpackConfig = (mode) => {
400
- return (0, exports.createSingleClientWebpackConfig)(mode, app_configs_1.default.clientEntry);
386
+ var _a;
387
+ const appWebpackConfig = (0, modules_1.patchMainWebpackConfigForModules)((0, exports.createSingleClientWebpackConfig)(mode, app_configs_1.default.clientEntry));
388
+ const exposedCompatModules = (_a = app_configs_1.default.compatModules) === null || _a === void 0 ? void 0 : _a.exposes;
389
+ if (!exposedCompatModules || Object.keys(exposedCompatModules).length === 0) {
390
+ return appWebpackConfig;
391
+ }
392
+ // Добавляем отдельные конфигурации для compat модулей
393
+ const modulesWebpackConfigs = Object.keys(exposedCompatModules).map((moduleName) => {
394
+ const module = Object.assign({ name: moduleName }, exposedCompatModules[moduleName]);
395
+ const config = (0, exports.createSingleClientWebpackConfig)(mode, {
396
+ [module.name]: module.entry,
397
+ }, module.name);
398
+ return (0, modules_1.patchWebpackConfigForCompat)(module, config);
399
+ });
400
+ return [appWebpackConfig, ...modulesWebpackConfigs];
401
401
  };
402
402
  exports.createClientWebpackConfig = createClientWebpackConfig;
@@ -1,2 +1,2 @@
1
- declare const config: import("webpack").Configuration;
1
+ declare const config: import("webpack").Configuration | import("webpack").Configuration[];
2
2
  export default config;