Skip to content

Commit

Permalink
ci: bundle esm module
Browse files Browse the repository at this point in the history
  • Loading branch information
noyobo committed Dec 18, 2024
1 parent 8b2cd3b commit 7657da0
Show file tree
Hide file tree
Showing 8 changed files with 61 additions and 188 deletions.
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,25 +34,25 @@
],
"dependencies": {
"browserslist": "^4.24.3",
"change-case": "^4.1.2",
"colors": "1.4.0",
"deepmerge": "^4.3.1",
"less": "^4.2.1",
"less-plugin-module-resolver": "^1.0.3",
"less-plugin-npm-import": "^2.1.0",
"lightningcss": "^1.28.2",
"query-string": "^7.0.1"
"lightningcss": "^1.28.2"
},
"devDependencies": {
"@biomejs/biome": "^1.9.4",
"@types/fs-extra": "^11.0.4",
"@types/less": "^3.0.7",
"@types/node": "^22.10.2",
"@vitest/coverage-v8": "^2.1.8",
"change-case": "^5.4.4",
"conventional-changelog-cli": "^5.0.0",
"esbuild": "^0.23.1",
"fs-extra": "^11.2.0",
"less-test-module": "^0.0.10",
"query-string": "^9.1.1",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"sass": "^1.83.0",
Expand Down
24 changes: 12 additions & 12 deletions src/index.mts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { readFile } from 'node:fs/promises';
import PATH from 'node:path';
import { dirname, extname, join, relative } from 'node:path';
import colors from 'colors';
import deepmerge from 'deepmerge';
import type { OnResolveArgs, PartialMessage, Plugin } from 'esbuild';
import { type CSSModulesConfig, type TransformResult, transform } from 'lightningcss';
import { type CSSModulesConfig, transform, type TransformResult } from 'lightningcss';
import qs from 'query-string';

import { convertLessError } from './less-utils.mts';
Expand Down Expand Up @@ -63,8 +63,8 @@ export const styleLoader = (options: StyleLoaderOptions = {}): Plugin => {
const cwd = process.cwd();

const styleTransform = async (filePath: string): Promise<StyleTransformResult | undefined> => {
const extname = PATH.extname(filePath);
if (extname === '.less') {
const ext = extname(filePath);
if (ext === '.less') {
return await transformLess(filePath, {
sourcemap: !!buildOptions.sourcemap,
alias: buildOptions.alias,
Expand All @@ -74,11 +74,11 @@ export const styleLoader = (options: StyleLoaderOptions = {}): Plugin => {
throw convertLessError(error);
});
}
if (extname === '.styl') {
if (ext === '.styl') {
// TODO: support stylus
throw new Error('stylus is not supported yet');
}
if (extname === '.scss' || extname === '.sass') {
if (ext === '.scss' || ext === '.sass') {
return await transformSass(filePath, {
sourcemap: !!buildOptions.sourcemap,
alias: buildOptions.alias,
Expand Down Expand Up @@ -131,14 +131,14 @@ export const styleLoader = (options: StyleLoaderOptions = {}): Plugin => {
try {
const t = Date.now();
result = await styleTransform(styleFile);
logger('Compile', PATH.relative(cwd, styleFile).blue.underline, `in ${Date.now() - t}ms`);
logger('Compile', relative(cwd, styleFile).blue.underline, `in ${Date.now() - t}ms`);
cssContent = result.css;
cssSourceMap = result.map;
watchImports = result.imports;
} catch (error) {
return {
errors: [error],
resolveDir: PATH.dirname(styleFile),
resolveDir: dirname(styleFile),
watchFiles: [styleFile],
};
}
Expand Down Expand Up @@ -180,7 +180,7 @@ export const styleLoader = (options: StyleLoaderOptions = {}): Plugin => {
},
} as PartialMessage,
],
resolveDir: PATH.dirname(styleFile),
resolveDir: dirname(styleFile),
watchFiles,
};
}
Expand Down Expand Up @@ -220,7 +220,7 @@ export const styleLoader = (options: StyleLoaderOptions = {}): Plugin => {
if (result.errors.length) {
return {
errors: result.errors,
resolveDir: PATH.dirname(args.path),
resolveDir: dirname(args.path),
watchFiles: [args.path],
};
}
Expand All @@ -240,15 +240,15 @@ export const styleLoader = (options: StyleLoaderOptions = {}): Plugin => {
return {
contents: cssContent,
loader: 'css',
resolveDir: PATH.dirname(args.path),
resolveDir: dirname(args.path),
watchFiles: [rawPath],
};
});

build.onResolve({ filter: /^\//, namespace: 'css-loader' }, async (args) => {
if (opts.publicPath) {
// absolute files base on publicPath
return { path: PATH.join(opts.publicPath, `.${args.path}`) };
return { path: join(opts.publicPath, `.${args.path}`) };
}
return { external: true };
});
Expand Down
1 change: 1 addition & 0 deletions src/less-utils.mts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { PartialMessage } from 'esbuild';

/** Convert less error into esbuild error */
export const convertLessError = (error: Less.RenderError): PartialMessage => {
const sourceLine = error.extract.filter(Boolean);
Expand Down
12 changes: 6 additions & 6 deletions src/sass-utils.mts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import path from 'node:path';
import { dirname, extname, isAbsolute, resolve } from 'node:path';
import type { PartialMessage } from 'esbuild';
import type { Syntax } from 'sass';

Expand Down Expand Up @@ -32,26 +32,26 @@ export function fileSyntax(filename: string): Syntax {
}

export function resolveCanonicalize(importer: string, file: string, alias: Record<string, string>) {
const importerExt = path.extname(importer);
const fileExt = path.extname(file);
const importerExt = extname(importer);
const fileExt = extname(file);

if (!fileExt) {
file += importerExt;
}

// absolute path
if (path.isAbsolute(file)) {
if (isAbsolute(file)) {
return file;
}

const scope = file.split('/')[0];
// alias
if (alias[scope]) {
const baseFile = file.slice(scope.length + 1);
return path.resolve(alias[scope], baseFile);
return resolve(alias[scope], baseFile);
}

return path.resolve(path.dirname(importer), file);
return resolve(dirname(importer), file);
}

export function convertScssError(error, filePath: string) {
Expand Down
16 changes: 8 additions & 8 deletions src/transform-sass.mts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import { readFile } from 'node:fs/promises';
import type * as sass from 'sass';
import type { ImporterResult, PromiseOr, SourceSpan } from 'sass';
import { fileSyntax, getDefaultSassImplementation, resolveCanonicalize } from './sass-utils.mts';
let sassEngine: typeof sass;

import * as fs from 'node:fs';
import path from 'node:path';
import { readFileSync } from 'node:fs';
import { dirname, relative } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import type { PartialMessage } from 'esbuild';
import type { ImporterResult, PromiseOr, SourceSpan } from 'sass';
import type { StyleTransformResult } from './types.mts';

let sassEngine: typeof sass;

export const transformSass = async (
filePath: string,
options: { sourcemap: boolean; alias?: Record<string, string> },
Expand All @@ -24,7 +24,7 @@ export const transformSass = async (
}
}
const syntax = fileSyntax(filePath);
const basedir = path.dirname(filePath);
const basedir = dirname(filePath);
const contents = await readFile(filePath, 'utf-8');
const warnings: PartialMessage[] = [];

Expand Down Expand Up @@ -62,7 +62,7 @@ export const transformSass = async (
importer: {
load(canonicalUrl: URL): PromiseOr<ImporterResult | null, 'async'> {
const pathname = fileURLToPath(canonicalUrl);
const contents = fs.readFileSync(pathname, 'utf8');
const contents = readFileSync(pathname, 'utf8');
return {
contents,
syntax: fileSyntax(pathname),
Expand All @@ -84,7 +84,7 @@ export const transformSass = async (
if (sourceMap) {
sourceMap.sourceRoot = basedir;
sourceMap.sources = sourceMap.sources.map((source) => {
return path.relative(basedir, source.startsWith('data:') ? filePath : fileURLToPath(source));
return relative(basedir, source.startsWith('data:') ? filePath : fileURLToPath(source));
});
}

Expand Down
8 changes: 4 additions & 4 deletions src/utils.mts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import PATH from 'node:path';
import { extname, isAbsolute } from 'node:path';
import browserslist from 'browserslist';
import { camelCase } from 'change-case';
import type { OnResolveArgs, PluginBuild } from 'esbuild';
import { type CSSModuleExports, browserslistToTargets } from 'lightningcss';
import { browserslistToTargets, type CSSModuleExports } from 'lightningcss';

export const codeWithSourceMap = (code: string, map: string) => {
return `${code}/*# sourceMappingURL=data:application/json;base64,${Buffer.from(map).toString('base64')} */`;
Expand Down Expand Up @@ -50,7 +50,7 @@ export const parsePath = (path: string) => {
export async function resolvePath(args: OnResolveArgs, build: PluginBuild) {
const { path, query } = parsePath(args.path);
let absolutePath = path;
if (!PATH.isAbsolute(absolutePath)) {
if (!isAbsolute(absolutePath)) {
const result = await build.resolve(absolutePath, {
resolveDir: args.resolveDir,
importer: args.importer,
Expand All @@ -67,6 +67,6 @@ export const generateTargets = (queries: string) => {
};

export const replaceExtension = (file: string, ext: string) => {
const extName = PATH.extname(file);
const extName = extname(file);
return file.slice(0, file.length - extName.length) + ext;
};
3 changes: 3 additions & 0 deletions tsup.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,7 @@ export default defineConfig({
js: format === 'cjs' ? '.js' : '.mjs',
}
},
minify: true,
target: 'es2016',
sourcemap: true,
});
Loading

0 comments on commit 7657da0

Please sign in to comment.