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

refactor: webpack plugin #36

Closed
wants to merge 5 commits into from
Closed
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
2 changes: 1 addition & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@
"./packages/excss/src/compiler.ts",
"./packages/excss/src/plugins/vite.ts",
"./packages/excss/src/plugins/next.ts",
"./packages/excss/src/plugins/webpack/{virtualLoader,loader,plugin}.ts",
"./packages/excss/src/plugins/webpack/**",
"./playground/next/src/app/**/{page,layout,loading,error,template,head}.tsx",
"./playground/next/src/pages/**"
],
Expand Down
12 changes: 6 additions & 6 deletions packages/excss/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,10 @@
"import": "./dist/plugins/webpack/loader.mjs",
"require": "./dist/plugins/webpack/loader.cjs"
},
"./webpack/virtualLoader": {
"types": "./dist/_types/plugins/webpack/virtualLoader.d.ts",
"import": "./dist/plugins/webpack/virtualLoader.mjs",
"require": "./dist/plugins/webpack/virtualLoader.cjs"
"./webpack/cssLoader": {
"types": "./dist/_types/plugins/webpack/cssLoader.d.ts",
"import": "./dist/plugins/webpack/cssLoader.mjs",
"require": "./dist/plugins/webpack/cssLoader.cjs"
},
"./next": {
"types": "./dist/_types/plugins/next.d.ts",
Expand All @@ -74,8 +74,8 @@
"webpack/loader": [
"./dist/_types/plugins/webpack/loader"
],
"webpack/virtualLoader": [
"./dist/_types/plugins/webpack/virtualLoader"
"webpack/cssLoader": [
"./dist/_types/plugins/webpack/cssLoader"
],
"next": [
"./dist/_types/plugins/next"
Expand Down
2 changes: 1 addition & 1 deletion packages/excss/scripts/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ const entryPoints = [
"src/compiler.ts",
"src/plugins/webpack/plugin.ts",
"src/plugins/webpack/loader.ts",
"src/plugins/webpack/virtualLoader.ts",
"src/plugins/webpack/cssLoader.ts",
"src/plugins/vite.ts",
"src/plugins/next.ts",
];
Expand Down
6 changes: 1 addition & 5 deletions packages/excss/src/plugins/next.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,7 @@ export default function createPlugin() {
return {
...nextConfig,
webpack(config: Configuration, options) {
config.plugins?.push(
new ExcssPlugin({
cssOutDir: "./.next/cache/excss",
}),
);
config.plugins?.push(new ExcssPlugin());

if (typeof nextConfig.webpack === "function") {
return nextConfig.webpack(config, options) as unknown;
Expand Down
14 changes: 9 additions & 5 deletions packages/excss/src/plugins/vite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { loadConfig } from "../utils/loadConfig.ts";

const VIRTUAL_MODULE_ID = "virtual:ex.css";
const RESOLVED_VIRTUAL_MODULE_ID = "\0" + VIRTUAL_MODULE_ID;
const CSS_PARAM_NAME = "css";

function plugin(): Vite.Plugin {
let config: ResolvedConfig;
Expand All @@ -32,7 +33,7 @@ function plugin(): Vite.Plugin {
const [filename, _params] = id.split("?");
if (filename === RESOLVED_VIRTUAL_MODULE_ID) {
const params = new URLSearchParams(_params);
return params.get("css") ?? "";
return params.get(CSS_PARAM_NAME) ?? "";
} else {
return;
}
Expand Down Expand Up @@ -64,10 +65,13 @@ function plugin(): Vite.Plugin {
if (isSSR) {
return { code: result.code, map: result.map };
} else {
const fileParams = new URLSearchParams();
fileParams.append("css", result.css);
const virtualModule = `${VIRTUAL_MODULE_ID}?${fileParams.toString()}`;
const importCSS = `import "${virtualModule}";`;
const params = new URLSearchParams({
[CSS_PARAM_NAME]: result.css,
});

const importCSS = `import ${JSON.stringify(
`${VIRTUAL_MODULE_ID}?${params.toString()}`,
)};`;
return {
code: `${result.code}\n${importCSS}`,
map: result.map,
Expand Down
9 changes: 9 additions & 0 deletions packages/excss/src/plugins/webpack/cssLoader.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import type { LoaderContext } from "webpack";
import { CSS_PARAM_NAME } from "./loader.ts";

export default function cssLoader(this: LoaderContext<unknown>, src: string) {
const params = new URLSearchParams(this.resourceQuery);
const css = `${src}\n${params.get(CSS_PARAM_NAME) ?? ""}`;

this.callback(undefined, css);
}
59 changes: 19 additions & 40 deletions packages/excss/src/plugins/webpack/loader.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
import { createHash } from "node:crypto";
import fs from "node:fs";
import path from "node:path";
import { createRequire } from "node:module";
import { transform } from "@excss/compiler";
import type { LoaderContext, LoaderDefinitionFunction } from "webpack";
import { generateFileId } from "../../utils/generateFileId.ts";
import type { ExcssWebpackConfig } from "./plugin.ts";
import type { ResolvedConfig } from "../../utils/loadConfig.ts";

type WebpackLoaderParams = Parameters<LoaderDefinitionFunction<never>>;

const virtualLoader = "excss/webpack/virtualLoader";
const virtualCSS = "excss/assets/ex.css";
declare const require: NodeRequire;
const _require = __ESM__ ? createRequire(import.meta.url) : require;

const VIRTUAL_CSS = "excss/assets/ex.css";
export const CSS_PARAM_NAME = "css";

export type LoaderOption = {
config: () => ExcssWebpackConfig;
config: () => ResolvedConfig;
};

export default function excssLoader(
Expand Down Expand Up @@ -46,16 +47,21 @@ export default function excssLoader(

if (result.type === "Ok") {
if (result.css) {
const importCode = createCSSImportCode(result.css, {
context: this,
cssOutDir: config.cssOutDir,
});

for (const dependency of config.dependencies) {
this.addDependency(dependency);
}
const params = new URLSearchParams({ [CSS_PARAM_NAME]: result.css });

const importCSS = `import ${JSON.stringify(
`${this.utils.contextify(
this.context,
_require.resolve(VIRTUAL_CSS),
)}?${params.toString()}`,
)};`;

this.callback(undefined, `${result.code}\n${importCode}`);
console.log("importCSS\n", importCSS);

this.callback(undefined, `${result.code}\n${importCSS}`);
} else {
this.callback(undefined, code, map);
}
Expand All @@ -74,30 +80,3 @@ export default function excssLoader(
this.callback(error as Error, code, map);
}
}

type CreateCSSImportCodeOption = {
context: LoaderContext<unknown>;
cssOutDir?: string | undefined;
};

function createCSSImportCode(
src: string,
{ context, cssOutDir }: CreateCSSImportCodeOption,
) {
if (cssOutDir) {
if (!fs.existsSync(cssOutDir)) fs.mkdirSync(cssOutDir);
const hash = createHash("md5").update(src).digest("hex");
const srcPath = path.posix.join(cssOutDir, `${hash}.css`);
fs.writeFileSync(srcPath, src);
return `import "${srcPath}";`;
} else {
const content = JSON.stringify({ src });

return `import ${JSON.stringify(
context.utils.contextify(
context.context || context.rootContext,
`ex.css!=!${virtualLoader}?${content}!${virtualCSS}`,
),
)};`;
}
}
61 changes: 29 additions & 32 deletions packages/excss/src/plugins/webpack/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,31 +3,14 @@ import type { ResolvedConfig } from "../../utils/loadConfig.ts";
import { loadConfig } from "../../utils/loadConfig.ts";
import type { LoaderOption } from "./loader.ts";

type PluginOption = {
/**
* @default undefined
*/
cssOutDir?: string | undefined;
};

export type ExcssWebpackConfig = ResolvedConfig & {
cssOutDir?: string | undefined;
};

export default class Plugin {
pluginOption: PluginOption;
_config: ExcssWebpackConfig | undefined;
_config: ResolvedConfig | undefined;

constructor(option?: PluginOption) {
this.pluginOption = option ?? {};
}
// constructor() {}

async loadConfig(root: string) {
const config = await loadConfig(root);
this._config = {
cssOutDir: this.pluginOption.cssOutDir,
...config,
};
this._config = config;
}

config() {
Expand Down Expand Up @@ -57,17 +40,31 @@ export default class Plugin {
},
);

compiler.options.module.rules.push({
test: /\.(tsx|ts|js|mjs|jsx)$/,
exclude: /node_modules/,
use: [
{
loader: "excss/webpack/loader",
options: {
config: this.config.bind(this),
} satisfies LoaderOption,
},
],
});
compiler.options.module.rules.push(
{
test: /\.(tsx|ts|js|mjs|jsx)$/,
exclude: /node_modules/,
use: [
{
loader: "excss/webpack/loader",
options: {
config: this.config.bind(this),
} satisfies LoaderOption,
},
],
},
{
test: /ex\.css$/,
exclude: /node_modules/,
use: [
{
loader: "excss/webpack/cssLoader",
options: {
config: this.config.bind(this),
} satisfies LoaderOption,
},
],
},
);
}
}
6 changes: 0 additions & 6 deletions packages/excss/src/plugins/webpack/virtualLoader.ts

This file was deleted.

Loading