Skip to content

Commit

Permalink
Revert "Revert "fix: cli should rewrite the aliases (#847)""
Browse files Browse the repository at this point in the history
This reverts commit ef75f1e.
  • Loading branch information
mellyeliu committed Jan 31, 2025
1 parent ef75f1e commit 016c015
Show file tree
Hide file tree
Showing 7 changed files with 80 additions and 13 deletions.
2 changes: 1 addition & 1 deletion .flowconfig
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ module.name_mapper='^@stylexjs\/shared\/lib\/\([a-zA-Z0-9_\-]+\)$' -> '<PROJECT_
module.name_mapper='^@stylexjs/stylex$' -> '<PROJECT_ROOT>/packages/stylex/src/stylex.js'
module.name_mapper='^@stylexjs/stylex\/lib\/\([a-zA-Z0-9_\-]+\)$' -> '<PROJECT_ROOT>/packages/stylex/src/\1'
module.name_mapper='^@stylexjs/babel-plugin$' -> '<PROJECT_ROOT>/packages/babel-plugin/src/index.js'
module.name_mapper='^@stylexjs/babel-plugin\/lib\/\([a-zA-Z0-9_\-]+\)$' -> '<PROJECT_ROOT>/packages/babel-plugin/src/\1'
module.name_mapper='^@stylexjs/babel-plugin\/lib\/\(.+\)$' -> '<PROJECT_ROOT>/packages/babel-plugin/src/\1'
; type-stubs
module.system.node.resolve_dirname=flow_modules
module.system.node.resolve_dirname=node_modules
Expand Down
44 changes: 44 additions & 0 deletions packages/babel-plugin/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@ import type { NodePath } from '@babel/traverse';
import type { PluginObj } from '@babel/core';
import type { StyleXOptions } from './utils/state-manager';
import StateManager from './utils/state-manager';
import {
EXTENSIONS,
filePathResolver,
matchesFileSuffix,
getRelativePath,
} from './utils/state-manager';
import { readImportDeclarations, readRequires } from './visitors/imports';
import transformStyleXCreate from './visitors/stylex-create';
import transformStyleXDefineVars from './visitors/stylex-define-vars';
Expand Down Expand Up @@ -74,6 +80,44 @@ function styleXTransform(): PluginObj<> {
// variables entirely if they're not needed.
exit: (path: NodePath<t.Program>) => {
path.traverse({
ImportDeclaration(path: NodePath<t.ImportDeclaration>) {
const filename = state.filename;
if (filename == null || !state.options.rewriteAliases) {
return;
}

const source = path.node.source.value;

const aliases = state.options.aliases;

const themeFileExtension = '.stylex';
if (!matchesFileSuffix(themeFileExtension)(source)) {
return;
}
const resolvedFilePath = filePathResolver(
source,
filename,
aliases,
);

if (resolvedFilePath == null) {
return;
}

let relativeFilePath = getRelativePath(
filename,
resolvedFilePath,
);

const extension = EXTENSIONS.find((ext) =>
relativeFilePath.endsWith(ext),
);
if (extension != null) {
relativeFilePath = relativeFilePath.slice(0, -extension.length);
}

path.node.source.value = relativeFilePath;
},
Identifier(path: NodePath<t.Identifier>) {
// Look for variables bound to `stylex.create` calls that are used
// outside of `stylex(...)` calls
Expand Down
32 changes: 26 additions & 6 deletions packages/babel-plugin/src/utils/state-manager.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,13 +78,15 @@ export type StyleXOptions = $ReadOnly<{
genConditionalClasses: boolean,
unstable_moduleResolution?: ?ModuleResolution,
aliases?: ?$ReadOnly<{ [string]: string | $ReadOnlyArray<string> }>,
rewriteAliases?: boolean,
...
}>;

type StyleXStateOptions = $ReadOnly<{
...StyleXOptions,
runtimeInjection: ?string | $ReadOnly<{ from: string, as: ?string }>,
aliases?: ?$ReadOnly<{ [string]: $ReadOnlyArray<string> }>,
rewriteAliases: boolean,
...
}>;

Expand Down Expand Up @@ -289,6 +291,10 @@ export default class StateManager {
styleResolution,
unstable_moduleResolution,
treeshakeCompensation,
rewriteAliases:
typeof options.rewriteAliases === 'boolean'
? options.rewriteAliases
: false,
};
return opts;
}
Expand Down Expand Up @@ -671,7 +677,7 @@ const getPossibleFilePaths = (filePath: string) => {

// a function that resolves the absolute path of a file when given the
// relative path of the file from the source file
const filePathResolver = (
export const filePathResolver = (
relativeFilePath: string,
sourceFilePath: string,
aliases: StyleXStateOptions['aliases'],
Expand Down Expand Up @@ -704,7 +710,7 @@ const filePathResolver = (
return null;
};

const EXTENSIONS = ['.js', '.ts', '.tsx', '.jsx', '.mjs', '.cjs'];
export const EXTENSIONS = ['.js', '.ts', '.tsx', '.jsx', '.mjs', '.cjs'];

const addFileExtension = (
importedFilePath: string,
Expand All @@ -721,10 +727,11 @@ const addFileExtension = (
return importedFilePath + fileExtension;
};

const matchesFileSuffix = (allowedSuffix: string) => (filename: string) =>
['', ...EXTENSIONS].some((extension) =>
filename.endsWith(`${allowedSuffix}${extension}`),
);
export const matchesFileSuffix: (string) => (string) => boolean =
(allowedSuffix) => (filename) =>
['', ...EXTENSIONS].some((extension) =>
filename.endsWith(`${allowedSuffix}${extension}`),
);

const getProgramPath = (path: NodePath<>): null | NodePath<t.Program> => {
let programPath = path;
Expand All @@ -749,3 +756,16 @@ const getProgramStatement = (path: NodePath<>): NodePath<> => {
}
return programPath;
};

export function getRelativePath(from: string, to: string): string {
const relativePath = path.relative(path.parse(from).dir, to);
return formatRelativePath(toPosixPath(relativePath));
}

function toPosixPath(filePath: string): string {
return filePath.split(path.sep).join(path.posix.sep);
}

function formatRelativePath(filePath: string) {
return filePath.startsWith('.') ? filePath : './' + filePath;
}
4 changes: 2 additions & 2 deletions packages/cli/src/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
* @flow strict
*/

import type { Rule } from '@stylexjs/babel-plugin';
import type { Rule, Options as StyleXOptions } from '@stylexjs/babel-plugin';

export type ModuleType =
| string
Expand All @@ -24,7 +24,7 @@ export type CliConfig = {
babelPluginsPost?: $ReadOnlyArray<any>,
modules_EXPERIMENTAL: $ReadOnlyArray<ModuleType>,
useCSSLayers?: boolean,
styleXConfig?: { +[string]: mixed },
styleXConfig?: StyleXOptions,
};

export type TransformConfig = {
Expand Down
5 changes: 2 additions & 3 deletions packages/cli/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
* @flow strict
*/

import type { Rule } from '@stylexjs/babel-plugin';
import type { Rule, Options as StyleXOptions } from '@stylexjs/babel-plugin';
import yargs from 'yargs';
import path from 'path';
import ansis from 'ansis';
Expand Down Expand Up @@ -71,8 +71,7 @@ const babelPresets: $ReadOnlyArray<any> = args.babelPresets;
const babelPluginsPre: $ReadOnlyArray<any> = args.babelPluginsPre;
const babelPluginsPost: $ReadOnlyArray<any> = args.babelPluginsPost;
const useCSSLayers: boolean = args.useCSSLayers;
const styleXConfig: { +[string]: mixed } =
(config.styleXConfig as $FlowFixMe) ?? {};
const styleXConfig: StyleXOptions = (config.styleXConfig as $FlowFixMe) ?? {};

const cliArgsConfig: CliConfig = {
input,
Expand Down
5 changes: 4 additions & 1 deletion packages/cli/src/plugins.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,10 @@ import * as nodePath from 'path';

type ImportModifierPlugin = $ReadOnly<{
visitor: {
Program: { enter(path: NodePath<t.Program>): void },
Program: {
enter?: (path: NodePath<t.Program>) => void,
exit?: (path: NodePath<t.Program>) => void,
},
},
}>;

Expand Down
1 change: 1 addition & 0 deletions packages/cli/src/transform.js
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,7 @@ export async function transformFile(
rootDir: path.parse(config.output).dir,
},
...(config.styleXConfig as $FlowFixMe),
rewriteAliases: true,
},
],
createImportPlugin(relativeImport),
Expand Down

0 comments on commit 016c015

Please sign in to comment.