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

Resolve Vite aliases. Allow users to specify aliases through StyleX plugin options as well. #43

Merged
merged 3 commits into from
Feb 23, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
5 changes: 5 additions & 0 deletions .changeset/shaggy-flies-trade.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"vite-plugin-stylex": patch
---

Resolve Vite aliases. Allow users to specify aliases through StyleX plugin options as well. Fixes #41.
2 changes: 2 additions & 0 deletions apps/vite-demo/src/Card.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as stylex from "@stylexjs/stylex";
import { tokens } from "./theme.stylex";
import { aliasedTokens } from "@/aliased-import-theme.stylex";
import { colors } from "@stylexjs/open-props/lib/colors.stylex";

export default function Card({ children }: { children: React.ReactNode }) {
Expand All @@ -18,5 +19,6 @@ const styles = stylex.create({
boxShadow: "0 0 16px rgba(0, 0, 0, 0.1)",
color: tokens.primaryTextColor,
border: `1px solid ${colors.blue1}`,
outlineColor: aliasedTokens.primaryOutlineColor,
},
});
5 changes: 5 additions & 0 deletions apps/vite-demo/src/aliased-import-theme.stylex.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import * as stylex from "@stylexjs/stylex";

export const aliasedTokens = stylex.defineVars({
primaryOutlineColor: "blue",
});
8 changes: 7 additions & 1 deletion apps/vite-demo/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,13 @@
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
"noFallthroughCasesInSwitch": true,

"baseUrl": ".",
"rootDir": ".",
"paths": {
"@/*": ["src/*"]
}
},
"include": ["src"],
"references": [{ "path": "./tsconfig.node.json" }]
Expand Down
6 changes: 6 additions & 0 deletions apps/vite-demo/vite.config.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import styleX from "vite-plugin-stylex";
import { resolve } from "node:path";

// https://vitejs.dev/config/
export default defineConfig({
plugins: [react(), styleX()],
resolve: {
alias: {
"@": resolve(__dirname, "src"),
},
},
});
85 changes: 65 additions & 20 deletions packages/vite-plugin-stylex/src/index.mts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Plugin, ViteDevServer, Rollup } from "vite";
import type { Plugin, ViteDevServer, Rollup, AliasOptions } from "vite";
import babel from "@babel/core";
import stylexBabelPlugin, {
Options as StyleXOptions,
Expand Down Expand Up @@ -39,6 +39,22 @@ interface StyleXVitePluginOptions
>
> {
stylexImports?: string[];
/**
* A map of aliases to their respective paths.
*
* @example
*
* ```ts
* {
* "@/*": [path.resolve(__dirname, "src", "*")]
* }
* ```
*
* Ensure that the paths are absolute and that you include the `*` at the end of the path.
*/
aliases?: {
[alias: string]: string[];
};
}

const STYLEX_REPLACE_RULE = "@stylex stylesheet;";
Expand Down Expand Up @@ -67,6 +83,7 @@ export default function styleXVitePlugin({

let server: ViteDevServer;
let framework: Framework = "none";
let aliases: Record<string, string[]> = {};

let reloadCount = 0;
function reloadStyleX() {
Expand Down Expand Up @@ -145,6 +162,15 @@ export default function styleXVitePlugin({
config.optimizeDeps.exclude = config.optimizeDeps.exclude || [];
config.optimizeDeps.exclude.push("@stylexjs/open-props");

for (const viteAlias of config.resolve.alias) {
if (typeof viteAlias.find === "string") {
// We need to convert Vite format to this plugin's format:
// Example: @ -> @/*
const alias = path.join(viteAlias.find, "*");
aliases[alias] = [path.join(viteAlias.replacement, "*")];
}
}

for (const plugin of config.plugins) {
if (!plugin || !("name" in plugin)) {
continue;
Expand Down Expand Up @@ -333,26 +359,45 @@ export default function styleXVitePlugin({
const filename = path.basename(id).split("?")[0];
const filePath = path.join(dir, filename);

const result = await babel.transformAsync(inputCode, {
babelrc: false,
filename: filePath,
plugins: [
/\.jsx?/.test(path.extname(id))
? flowSyntaxPlugin
: typescriptSyntaxPlugin,
jsxSyntaxPlugin,
[
stylexBabelPlugin,
{
dev: !isProd,
unstable_moduleResolution,
importSources: stylexImports,
runtimeInjection: !isCompileMode,
...options,
},
const result = await babel
.transformAsync(inputCode, {
babelrc: false,
filename: filePath,
plugins: [
/\.jsx?/.test(path.extname(id))
? flowSyntaxPlugin
: typescriptSyntaxPlugin,
jsxSyntaxPlugin,
[
stylexBabelPlugin,
{
dev: !isProd,
unstable_moduleResolution,
importSources: stylexImports,
runtimeInjection: !isCompileMode,
aliases: {
...options.aliases,
...aliases,
},
...options,
},
],
],
],
});
})
.catch((error) => {
if (
error.message.includes(
"Only static values are allowed inside of a stylex.create() call."
)
) {
this.error(`StyleX Error: ${error.message}

💡 If you're importing StyleX tokens or styles from another file using aliases, make sure to define those in your Vite config or in the StyleX Plugin options.
`);
}

throw error;
});

if (!result) {
return;
Expand Down