Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat: Automatically Discover StyleX Aliases from Configuration Files #810

Open
wants to merge 19 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
158 changes: 158 additions & 0 deletions packages/babel-plugin/__tests__/stylex-transform-alias-config-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/


'use strict';

import path from 'path';
import fs from 'fs';
import os from 'os';
import StateManager from '../src/utils/state-manager';

describe('StyleX Alias Configuration', () => {
let tmpDir;
let state;

beforeEach(() => {
// Create a temporary directory for our test files
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'stylex-test-'));

// Create a mock babel state
state = {
file: {
metadata: {},
},
filename: path.join(tmpDir, 'src/components/Button.js'),
};
});

afterEach(() => {
// Clean up temporary directory
fs.rmSync(tmpDir, { recursive: true, force: true });
});

const setupFiles = (files) => {
for (const [filePath, content] of Object.entries(files)) {
const fullPath = path.join(tmpDir, filePath);
fs.mkdirSync(path.dirname(fullPath), { recursive: true });
fs.writeFileSync(fullPath, JSON.stringify(content, null, 2));
}
};

test('discovers aliases from package.json', () => {
setupFiles({
'package.json': {
name: 'test-package',
stylex: {
aliases: {
'@components': './src/components',
'@utils/*': ['./src/utils/*'],
},
},
},
});

const manager = new StateManager(state);

expect(manager.options.aliases).toEqual({
'@components': ['./src/components'],
'@utils/*': ['./src/utils/*'],
});
});

test('discovers aliases from tsconfig.json', () => {
setupFiles({
'package.json': { name: 'test-package' },
'tsconfig.json': {
compilerOptions: {
baseUrl: '.',
paths: {
'@components/*': ['src/components/*'],
'@utils/*': ['src/utils/*'],
},
},
},
});

const manager = new StateManager(state);

expect(manager.options.aliases).toEqual({
'@components': ['src/components'],
'@utils': ['src/utils'],
});
});

test('merges aliases from both package.json and tsconfig.json', () => {
setupFiles({
'package.json': {
name: 'test-package',
stylex: {
aliases: {
'@components': './src/components',
},
},
},
'tsconfig.json': {
compilerOptions: {
baseUrl: '.',
paths: {
'@utils/*': ['src/utils/*'],
},
},
},
});

const manager = new StateManager(state);

expect(manager.options.aliases).toEqual({
'@components': ['./src/components'],
'@utils': ['src/utils'],
});
});

test('manual configuration overrides discovered aliases', () => {
setupFiles({
'package.json': {
name: 'test-package',
stylex: {
aliases: {
'@components': './src/components',
},
},
},
});

state.opts = {
aliases: {
'@components': './custom/path',
},
};

const manager = new StateManager(state);

expect(manager.options.aliases).toEqual({
'@components': ['./custom/path'],
});
});

test('handles missing configuration files gracefully', () => {
const manager = new StateManager(state);
expect(manager.options.aliases).toBeNull();
});

test('handles invalid JSON files gracefully', () => {
setupFiles({
'package.json': '{invalid json',
'tsconfig.json': '{also invalid',
});

const manager = new StateManager(state);
expect(manager.options.aliases).toBeNull();
});
});
110 changes: 99 additions & 11 deletions packages/babel-plugin/src/utils/state-manager.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import { addDefault, addNamed } from '@babel/helper-module-imports';
import type { ImportOptions } from '@babel/helper-module-imports';
import * as pathUtils from '../babel-path-utils';
import { buildResolver } from 'esm-resolve';
import JSON5 from 'json5';

type ImportAdditionOptions = Omit<
Partial<ImportOptions>,
Expand Down Expand Up @@ -262,17 +263,7 @@ export default class StateManager {
'options.aliases',
);

const aliases: StyleXStateOptions['aliases'] =
aliasesOption == null
? aliasesOption
: Object.fromEntries(
Object.entries(aliasesOption).map(([key, value]) => {
if (typeof value === 'string') {
return [key, [value]];
}
return [key, value];
}),
);
const aliases = this.loadAliases(aliasesOption);

const opts: StyleXStateOptions = {
aliases,
Expand Down Expand Up @@ -623,6 +614,103 @@ export default class StateManager {
): void {
this.styleVarsToKeep.add(memberExpression);
}

loadAliases(
manualAliases: ?$ReadOnly<{ [string]: string | $ReadOnlyArray<string> }>,
): ?$ReadOnly<{ [string]: $ReadOnlyArray<string> }> {
if (!this.filename) {
return manualAliases ? this.normalizeAliases(manualAliases) : null;
}

let packageAliases = {};
let tsconfigAliases = {};
const projectDir = this.findProjectRoot(this.filename);

// Load aliases from package.json
try {
const packageJsonPath = path.join(projectDir, 'package.json');
if (fs.existsSync(packageJsonPath)) {
const packageJson = JSON.parse(
fs.readFileSync(packageJsonPath, 'utf8'),
);
if (packageJson.stylex?.aliases) {
packageAliases = packageJson.stylex.aliases;
}
}
} catch (err) {
console.warn('Failed to load aliases from package.json:', err.message);
}

// Load aliases from tsconfig.json
try {
const tsconfigPath = path.join(projectDir, 'tsconfig.json');
if (fs.existsSync(tsconfigPath)) {
const tsconfig = JSON5.parse(fs.readFileSync(tsconfigPath, 'utf8'));
const baseUrl = tsconfig.compilerOptions?.baseUrl || '.';
if (tsconfig.compilerOptions?.paths) {
tsconfigAliases = Object.fromEntries(
Object.entries(tsconfig.compilerOptions.paths).map(
([key, value]) => [
key.replace(/\/\*$/, ''),
Array.isArray(value)
? value.map((p) =>
this.normalizePath(
path.join(baseUrl, p.replace(/\/\*$/, '')),
),
)
: [
this.normalizePath(
path.join(baseUrl, value.replace(/\/\*$/, '')),
),
],
],
),
);
}
}
} catch (err) {
console.warn('Failed to load aliases from tsconfig.json:', err.message);
}

// Merge aliases in priority: manual > package.json > tsconfig.json
const mergedAliases = {
...tsconfigAliases,
...packageAliases,
...(manualAliases || {}),
};

return Object.keys(mergedAliases).length > 0
? this.normalizeAliases(mergedAliases)
: null;
}

normalizeAliases(
aliases: $ReadOnly<{ [string]: string | $ReadOnlyArray<string> }>,
): $ReadOnly<{ [string]: $ReadOnlyArray<string> }> {
return Object.fromEntries(
Object.entries(aliases).map(([key, value]) => [
key,
Array.isArray(value)
? value.map((p) => this.normalizePath(p))
: [this.normalizePath(value)],
]),
);
}

findProjectRoot(filePath: string): string {
p0nch000 marked this conversation as resolved.
Show resolved Hide resolved
const dir = path.dirname(filePath);
if (fs.existsSync(path.join(dir, 'package.json'))) {
p0nch000 marked this conversation as resolved.
Show resolved Hide resolved
return dir;
}
if (dir === path.parse(dir).root) {
return dir;
}
return this.findProjectRoot(dir);
}

normalizePath(filePath: string): string {
return filePath.split(path.sep).join('/');
}
}

function possibleAliasedPaths(
Expand Down
Loading