Skip to content

Commit c6134c6

Browse files
ruanylQxisylolo
authored andcommitted
Support path alias for webpack and babel (opensearch-project#9205)
* feat: added path alias support for webpack and babel Signed-off-by: Yulong Ruan <[email protected]> * update yarn.lock Signed-off-by: Yulong Ruan <[email protected]> --------- Signed-off-by: Yulong Ruan <[email protected]>
1 parent 5c4fa61 commit c6134c6

File tree

10 files changed

+110
-105
lines changed

10 files changed

+110
-105
lines changed

packages/osd-babel-preset/node_preset.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@
2828
* under the License.
2929
*/
3030

31+
const path = require('path');
32+
3133
module.exports = (_, options = {}) => {
3234
return {
3335
presets: [
@@ -60,5 +62,18 @@ module.exports = (_, options = {}) => {
6062
],
6163
require('./common_preset'),
6264
],
65+
plugins: [
66+
[
67+
require.resolve('babel-plugin-module-resolver'),
68+
{
69+
root: [path.resolve(__dirname, '../..')],
70+
cwd: path.resolve(__dirname, '../..'),
71+
alias: {
72+
'opensearch-dashboards/server': './src/core/server',
73+
'opensearch-dashboards/public': './src/core/public',
74+
},
75+
},
76+
],
77+
],
6378
};
6479
};

packages/osd-babel-preset/package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
"@babel/preset-react": "^7.22.9",
1616
"@babel/preset-typescript": "^7.22.9",
1717
"babel-plugin-add-module-exports": "^1.0.4",
18+
"babel-plugin-module-resolver": "^5.0.1",
1819
"babel-plugin-styled-components": "^2.0.2",
1920
"babel-plugin-transform-react-remove-prop-types": "^0.4.24",
2021
"browserslist": "^4.21.10",

packages/osd-optimizer/src/worker/bundle_refs_plugin.ts

Lines changed: 21 additions & 81 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@
2020
*/
2121

2222
import Path from 'path';
23-
import Fs from 'fs';
2423

2524
import webpack from 'webpack';
2625

@@ -29,20 +28,6 @@ import { BundleRefModule } from './bundle_ref_module';
2928

3029
const RESOLVE_EXTENSIONS = ['.js', '.ts', '.tsx'];
3130

32-
function safeStat(path: string): Promise<Fs.Stats | undefined> {
33-
return new Promise((resolve, reject) => {
34-
Fs.stat(path, (error, stat) => {
35-
if (error?.code === 'ENOENT') {
36-
resolve(undefined);
37-
} else if (error) {
38-
reject(error);
39-
} else {
40-
resolve(stat);
41-
}
42-
});
43-
});
44-
}
45-
4631
interface RequestData {
4732
context: string;
4833
dependencies: Array<{ request: string }>;
@@ -80,7 +65,7 @@ export class BundleRefsPlugin {
8065
const context = data.context;
8166
const dep = data.dependencies[0];
8267

83-
this.maybeReplaceImport(context, dep.request).then(
68+
this.maybeReplaceImport(context, dep.request, compiler).then(
8469
(module) => {
8570
if (!module) {
8671
wrappedFactory(data, callback);
@@ -134,64 +119,17 @@ export class BundleRefsPlugin {
134119
});
135120
}
136121

137-
private cachedResolveRefEntry(ref: BundleRef) {
138-
const cached = this.resolvedRefEntryCache.get(ref);
139-
140-
if (cached) {
141-
return cached;
142-
}
143-
144-
const absoluteRequest = Path.resolve(ref.contextDir, ref.entry);
145-
const promise = this.cachedResolveRequest(absoluteRequest).then((resolved) => {
146-
if (!resolved) {
147-
throw new Error(`Unable to resolve request [${ref.entry}] relative to [${ref.contextDir}]`);
148-
}
149-
150-
return resolved;
151-
});
152-
this.resolvedRefEntryCache.set(ref, promise);
153-
return promise;
154-
}
155-
156-
private cachedResolveRequest(absoluteRequest: string) {
157-
const cached = this.resolvedRequestCache.get(absoluteRequest);
158-
159-
if (cached) {
160-
return cached;
161-
}
162-
163-
const promise = this.resolveRequest(absoluteRequest);
164-
this.resolvedRequestCache.set(absoluteRequest, promise);
165-
return promise;
166-
}
167-
168-
private async resolveRequest(absoluteRequest: string) {
169-
const stats = await safeStat(absoluteRequest);
170-
if (stats && stats.isFile()) {
171-
return absoluteRequest;
172-
}
173-
174-
// look for an index file in directories
175-
if (stats?.isDirectory()) {
176-
for (const ext of RESOLVE_EXTENSIONS) {
177-
const indexPath = Path.resolve(absoluteRequest, `index${ext}`);
178-
const indexStats = await safeStat(indexPath);
179-
if (indexStats?.isFile()) {
180-
return indexPath;
122+
private async resolve(request: string, startPath: string, compiler: webpack.Compiler) {
123+
const resolver = compiler.resolverFactory.get('normal');
124+
return new Promise<string | undefined>((resolve, reject) => {
125+
resolver.resolve({}, startPath, request, {}, (err: unknown | null, resolvedPath: string) => {
126+
if (err) {
127+
reject(err);
128+
} else {
129+
resolve(resolvedPath);
181130
}
182-
}
183-
}
184-
185-
// look for a file with one of the supported extensions
186-
for (const ext of RESOLVE_EXTENSIONS) {
187-
const filePath = `${absoluteRequest}${ext}`;
188-
const fileStats = await safeStat(filePath);
189-
if (fileStats?.isFile()) {
190-
return filePath;
191-
}
192-
}
193-
194-
return;
131+
});
132+
});
195133
}
196134

197135
/**
@@ -200,9 +138,12 @@ export class BundleRefsPlugin {
200138
* then an error is thrown. If the request does not resolve to a bundleRef then
201139
* undefined is returned. Otherwise it returns the referenced bundleRef.
202140
*/
203-
private async maybeReplaceImport(context: string, request: string) {
204-
// ignore imports that have loaders defined or are not relative seeming
205-
if (request.includes('!') || !request.startsWith('.')) {
141+
private async maybeReplaceImport(context: string, request: string, compiler: webpack.Compiler) {
142+
const alias = Object.keys(compiler.options.resolve?.alias ?? {});
143+
const isAliasRequest = alias.some((a) => request.startsWith(a));
144+
145+
// For non-alias import path, ignore imports that have loaders defined or are not relative seeming
146+
if (!isAliasRequest && (request.includes('!') || !request.startsWith('.'))) {
206147
return;
207148
}
208149

@@ -211,13 +152,12 @@ export class BundleRefsPlugin {
211152
return;
212153
}
213154

214-
const absoluteRequest = Path.resolve(context, request);
215-
if (absoluteRequest.startsWith(this.ignorePrefix)) {
155+
const resolved = await this.resolve(request, context, compiler);
156+
if (!resolved) {
216157
return;
217158
}
218159

219-
const resolved = await this.cachedResolveRequest(absoluteRequest);
220-
if (!resolved) {
160+
if (resolved.startsWith(this.ignorePrefix)) {
221161
return;
222162
}
223163

@@ -228,7 +168,7 @@ export class BundleRefsPlugin {
228168
}
229169

230170
for (const ref of possibleRefs) {
231-
const resolvedEntry = await this.cachedResolveRefEntry(ref);
171+
const resolvedEntry = await this.resolve(`./${ref.entry}`, ref.contextDir, compiler);
232172
if (resolved !== resolvedEntry) {
233173
continue;
234174
}

packages/osd-optimizer/src/worker/webpack.config.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,7 @@ export function getWebpackConfig(bundle: Bundle, bundleRefs: BundleRefs, worker:
274274
mainFields: ['browser', 'main'],
275275
alias: {
276276
core_app_image_assets: Path.resolve(worker.repoRoot, 'src/core/public/core_app/images'),
277+
'opensearch-dashboards/public': Path.resolve(worker.repoRoot, 'src/core/public'),
277278
},
278279
},
279280

src/plugins/workspace/public/plugin.test.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,8 @@
44
*/
55

66
import { BehaviorSubject } from 'rxjs';
7-
import { waitFor } from '@testing-library/dom';
87
import { first } from 'rxjs/operators';
9-
import { coreMock } from '../../../core/public/mocks';
8+
import { coreMock } from 'opensearch-dashboards/public/mocks';
109
import {
1110
ChromeBreadcrumb,
1211
NavGroupStatus,
@@ -15,7 +14,7 @@ import {
1514
WorkspaceAvailability,
1615
AppStatus,
1716
WorkspaceError,
18-
} from '../../../core/public';
17+
} from 'opensearch-dashboards/public';
1918
import { WORKSPACE_FATAL_ERROR_APP_ID, WORKSPACE_DETAIL_APP_ID } from '../common/constants';
2019
import { savedObjectsManagementPluginMock } from '../../saved_objects_management/public/mocks';
2120
import { managementPluginMock } from '../../management/public/mocks';

src/plugins/workspace/public/plugin.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@ import {
2222
DEFAULT_NAV_GROUPS,
2323
NavGroupType,
2424
ALL_USE_CASE_ID,
25-
} from '../../../core/public';
25+
} from 'opensearch-dashboards/public';
26+
import { getWorkspaceIdFromUrl } from 'opensearch-dashboards/public/utils';
2627
import {
2728
WORKSPACE_FATAL_ERROR_APP_ID,
2829
WORKSPACE_DETAIL_APP_ID,
@@ -32,7 +33,6 @@ import {
3233
WORKSPACE_NAVIGATION_APP_ID,
3334
WORKSPACE_COLLABORATORS_APP_ID,
3435
} from '../common/constants';
35-
import { getWorkspaceIdFromUrl } from '../../../core/public/utils';
3636
import { Services, WorkspaceUseCase, WorkspacePluginSetup } from './types';
3737
import { WorkspaceClient } from './workspace_client';
3838
import { SavedObjectsManagementPluginSetup } from '../../../plugins/saved_objects_management/public';

src/plugins/workspace/server/plugin.test.ts

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,19 @@
44
*/
55

66
import { OnPostAuthHandler, OnPreRoutingHandler } from 'src/core/server';
7-
import { coreMock, httpServerMock, uiSettingsServiceMock } from '../../../core/server/mocks';
7+
import {
8+
coreMock,
9+
httpServerMock,
10+
uiSettingsServiceMock,
11+
} from 'opensearch-dashboards/server/mocks';
812
import { WorkspacePlugin, WorkspacePluginDependencies } from './plugin';
913
import {
1014
getACLAuditor,
1115
getClientCallAuditor,
1216
getWorkspaceState,
1317
updateWorkspaceState,
14-
} from '../../../core/server/utils';
15-
import * as serverUtils from '../../../core/server/utils/auth_info';
18+
} from 'opensearch-dashboards/server/utils';
19+
import * as serverUtils from 'opensearch-dashboards/server/utils/auth_info';
1620
import { SavedObjectsPermissionControl } from './permission_control/client';
1721
import { DataSourcePluginSetup } from '../../data_source/server';
1822
import { DataSourceError } from '../../data_source/common/data_sources';

src/plugins/workspace/server/plugin.ts

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,18 @@ import {
1313
Logger,
1414
CoreStart,
1515
SharedGlobalConfig,
16-
} from '../../../core/server';
16+
} from 'opensearch-dashboards/server';
17+
import {
18+
cleanWorkspaceId,
19+
cleanUpACLAuditor,
20+
cleanUpClientCallAuditor,
21+
getACLAuditor,
22+
getWorkspaceIdFromUrl,
23+
getWorkspaceState,
24+
initializeACLAuditor,
25+
initializeClientCallAuditor,
26+
updateWorkspaceState,
27+
} from 'opensearch-dashboards/server/utils';
1728
import {
1829
WORKSPACE_SAVED_OBJECTS_CLIENT_WRAPPER_ID,
1930
WORKSPACE_CONFLICT_CONTROL_SAVED_OBJECTS_CLIENT_WRAPPER_ID,
@@ -33,17 +44,6 @@ import { IWorkspaceClientImpl, WorkspacePluginSetup, WorkspacePluginStart } from
3344
import { WorkspaceClient } from './workspace_client';
3445
import { registerRoutes } from './routes';
3546
import { WorkspaceSavedObjectsClientWrapper } from './saved_objects';
36-
import {
37-
cleanWorkspaceId,
38-
cleanUpACLAuditor,
39-
cleanUpClientCallAuditor,
40-
getACLAuditor,
41-
getWorkspaceIdFromUrl,
42-
getWorkspaceState,
43-
initializeACLAuditor,
44-
initializeClientCallAuditor,
45-
updateWorkspaceState,
46-
} from '../../../core/server/utils';
4747
import { WorkspaceConflictSavedObjectsClientWrapper } from './saved_objects/saved_objects_wrapper_for_check_workspace_conflict';
4848
import {
4949
SavedObjectsPermissionControl,

tsconfig.base.json

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,11 @@
55
// Allows for importing from `opensearch-dashboards` package for the exported types.
66
"opensearch-dashboards": ["./opensearch_dashboards"],
77
"opensearch-dashboards/public": ["src/core/public"],
8+
"opensearch-dashboards/public/*": ["src/core/public/*"],
89
"opensearch-dashboards/server": ["src/core/server"],
10+
"opensearch-dashboards/server/*": ["src/core/server/*"],
911
"plugins/*": ["src/legacy/core_plugins/*/public/"],
10-
"test_utils/*": [
11-
"src/test_utils/public/*"
12-
],
12+
"test_utils/*": ["src/test_utils/public/*"],
1313
"fixtures/*": ["src/fixtures/*"],
1414
"@opensearch-project/opensearch": ["node_modules/@opensearch-project/opensearch/api/new"],
1515
"@opensearch-project/opensearch/lib/*": ["node_modules/@opensearch-project/opensearch/lib/*"],

0 commit comments

Comments
 (0)