Skip to content

Commit

Permalink
support css module options (#15)
Browse files Browse the repository at this point in the history
  • Loading branch information
indooorsman authored Jan 21, 2022
1 parent d5e8e6c commit 0bd735f
Show file tree
Hide file tree
Showing 7 changed files with 113 additions and 18 deletions.
49 changes: 49 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import type { Plugin } from 'esbuild';

declare type GenerateScopedNameFunction = (
name: string,
filename: string,
css: string
) => string;

declare type LocalsConventionFunction = (
originalClassName: string,
generatedClassName: string,
inputFile: string
) => string;

declare interface CssModulesOptions {
getJSON?(cssFilename: string, json: { [name: string]: string }, outputFilename?: string): void;

localsConvention?:
| 'camelCase'
| 'camelCaseOnly'
| 'dashes'
| 'dashesOnly'
| LocalsConventionFunction;

scopeBehaviour?: 'global' | 'local';
globalModulePaths?: RegExp[];

generateScopedName?: string | GenerateScopedNameFunction;

hashPrefix?: string;
exportGlobals?: boolean;
root?: string;

Loader?: typeof Loader;

resolve?: (file: string) => string | Promise<string>;
}

declare interface PluginOptions {
inject?: boolean;
localsConvention?: CssModulesOptions['localsConvention'];
generateScopedName?: CssModulesOptions['generateScopedName'];
cssModulesOption?: CssModulesOptions;
v2?: boolean;
}

export default function CssModulesPlugin(options?: PluginOptions): Plugin;

export = CssModulesPlugin;
16 changes: 12 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,9 @@ const buildCssModulesJS2 = async (cssFullPath) => {
finalCssContent = finalCssContent.replaceAll(placeholder, getAbsoluteUrl(resolveDir, url));
});
if (map) {
finalCssContent += `\n/*# sourceMappingURL=data:application/json;base64,${map.toString('base64')} */`;
finalCssContent += `\n/*# sourceMappingURL=data:application/json;base64,${map.toString(
'base64'
)} */`;
}
return {
jsContent,
Expand All @@ -54,7 +56,12 @@ const buildCssModulesJS2 = async (cssFullPath) => {
};

const buildCssModulesJS = async (cssFullPath, options) => {
const { localsConvention = 'camelCaseOnly', inject = true, generateScopedName } = options;
const {
localsConvention = 'camelCaseOnly',
inject = true,
generateScopedName,
cssModulesOption = {}
} = options;

const css = await readFile(cssFullPath);

Expand All @@ -66,10 +73,11 @@ const buildCssModulesJS = async (cssFullPath, options) => {
getJSON(cssSourceFile, json) {
cssModulesJSON = { ...json };
return cssModulesJSON;
}
},
...cssModulesOption
})
]).process(css, {
from: undefined,
from: cssFullPath,
map: false
});

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "esbuild-css-modules-plugin",
"version": "2.1.0",
"version": "2.1.1",
"description": "A esbuild plugin to bundle css modules into js(x)/ts(x).",
"main": "index.js",
"keywords": [
Expand Down
7 changes: 6 additions & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,12 @@ esbuild.build({

localsConvention: 'camelCaseOnly', // optional. value could be one of 'camelCaseOnly', 'camelCase', 'dashes', 'dashesOnly', default is 'camelCaseOnly'

generateScopedName: (name, filename, css) => string, // optional.
generateScopedName: (name, filename, css) => string, // optional. refer to: https://github.com/madyankin/postcss-modules#generating-scoped-names

cssModulesOption: {
// optional, refer to: https://github.com/madyankin/postcss-modules/blob/d7cefc427c43bf35f7ebc55e7bda33b4689baf5a/index.d.ts#L27
// this option will override others passed to postcss-modules
},

v2: true // experimental. v2 can bundle images in css, note if set `v2` to true, all other options will be ignored. and v2 only works with `bundle: true`.
})
Expand Down
25 changes: 16 additions & 9 deletions test/components/hello.world.jsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
import React from 'react';
import styles, * as appCssModules from '../styles/app.modules.css';
import styles2, * as h from '../styles/deep/styles/hello.modules.css';

export const HelloWorld = () => <>
<h3 className={styles.helloWorld}>Hello World!</h3>
{
appCssModules.digest && <pre><code>${appCssModules.digest}</code></pre>
}
{
appCssModules.css && <pre><code>${appCssModules.css}</code></pre>
}
</>
export const HelloWorld = () => (
<>
<h3 className={styles.helloWorld}>Hello World!</h3>
<p className={styles2.helloText}>hi...</p>
<pre>
<code>${appCssModules?.digest ?? '// n/a'}</code>
</pre>
<pre>
<code>${h?.digest ?? '// n/a'}</code>
</pre>
<pre>
<code>${h?.css ?? '// n/a'}</code>
</pre>
</>
);
3 changes: 3 additions & 0 deletions test/styles/deep/styles/hello.modules.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.hello-text {
color: red;
}
29 changes: 26 additions & 3 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,26 @@ const fse = require('fs-extra');
fse.emptyDirSync('./dist');

(async () => {
await esbuild.build({
entryPoints: ['app.jsx'],
format: 'esm',
target: ['es2020'],
bundle: true,
minify: false,
sourcemap: true,
external: ['react', 'react-dom'],
outdir: './dist/bundle-default',
write: true,
plugins: [
cssModulesPlugin()
],
logLevel: 'debug',
loader: {
'.jpg': 'file'
}
});
console.log('[test][esbuild:bundle-default] done, please check `test/dist/bundle-default`', '\n');

await esbuild.build({
entryPoints: ['app.jsx'],
format: 'esm',
Expand All @@ -16,7 +36,10 @@ fse.emptyDirSync('./dist');
write: true,
plugins: [
cssModulesPlugin({
inject: false
inject: false,
cssModulesOption: {
generateScopedName: '[path][name]__[local]___[hash:base64:8]'
}
})
],
logLevel: 'debug',
Expand All @@ -27,7 +50,7 @@ fse.emptyDirSync('./dist');
console.log('[test][esbuild:bundle-no-inject] done, please check `test/dist/bundle-no-inject`', '\n');

await esbuild.build({
entryPoints: ['./styles/app.modules.css', 'app.jsx', './components/hello.world.jsx'],
entryPoints: ['./styles/app.modules.css', './styles/deep/styles/hello.modules.css', 'app.jsx', './components/hello.world.jsx'],
format: 'esm',
target: ['es2020'],
bundle: false,
Expand All @@ -49,7 +72,7 @@ fse.emptyDirSync('./dist');
format: 'esm',
target: ['es2020'],
bundle: true,
minify: true,
minify: false,
sourcemap: true,
publicPath: '/static/',
external: ['react', 'react-dom'],
Expand Down

0 comments on commit 0bd735f

Please sign in to comment.