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

feat(esbuild): former @linaria/esbuild #12

Merged
merged 2 commits into from
Oct 5, 2023
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
7 changes: 7 additions & 0 deletions .changeset/weak-owls-rule.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@wyw-in-js/esbuild': patch
'@wyw-in-js/vite': patch
'wyw-in-js': patch
---

Plugin for esbuild.
3 changes: 3 additions & 0 deletions packages/esbuild/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = {
extends: ['@wyw-in-js/eslint-config/library'],
};
3 changes: 3 additions & 0 deletions packages/esbuild/babel.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const config = require('@wyw-in-js/babel-config');

module.exports = config;
18 changes: 18 additions & 0 deletions packages/esbuild/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// @ts-check

/**
* @type {import('@jest/types').Config.InitialOptions}
*/
module.exports = {
displayName: 'webpack-loader',
preset: '@wyw-in-js/jest-preset',
transform: {
'^.+\\.ts$': [
'ts-jest',
{
tsconfig: '<rootDir>/tsconfig.spec.json',
isolatedModules: true,
},
],
},
};
45 changes: 45 additions & 0 deletions packages/esbuild/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
{
"name": "@wyw-in-js/esbuild",
"version": "0.1.0",
"dependencies": {
"@wyw-in-js/shared": "workspace:*",
"@wyw-in-js/transform": "workspace:*"
},
"devDependencies": {
"@types/node": "^16.18.55",
"@wyw-in-js/babel-config": "workspace:*",
"@wyw-in-js/eslint-config": "workspace:*",
"@wyw-in-js/jest-preset": "workspace:*",
"@wyw-in-js/ts-config": "workspace:*",
"esbuild": "^0.15.16"
},
"engines": {
"node": ">=16.0.0"
},
"files": [
"esm/",
"lib/",
"types/"
],
"license": "MIT",
"exports": {
"import": "./esm/index.js",
"require": "./lib/index.js",
"types": "./types/index.d.ts"
},
"main": "lib/index.js",
"module": "esm/index.js",
"peerDependencies": {
"esbuild": ">=0.12.0"
},
"publishConfig": {
"access": "public"
},
"scripts": {
"build:esm": "babel src --out-dir esm --extensions '.js,.jsx,.ts,.tsx' --source-maps --delete-dir-on-start",
"build:lib": "cross-env NODE_ENV=legacy babel src --out-dir lib --extensions '.js,.jsx,.ts,.tsx' --source-maps --delete-dir-on-start",
"build:types": "tsc --project ./tsconfig.lib.json --baseUrl . --rootDir ./src",
"lint": "eslint --ext .js,.ts ."
},
"types": "types/index.d.ts"
}
157 changes: 157 additions & 0 deletions packages/esbuild/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
/**
* This file contains an esbuild loader for wyw-in-js.
* It uses the transform.ts function to generate class names from source code,
* returns transformed code without template literals and attaches generated source maps
*/

import { readFileSync } from 'fs';
import { basename, dirname, isAbsolute, join, parse, posix } from 'path';

import type { Plugin, TransformOptions, Loader } from 'esbuild';
import { transformSync } from 'esbuild';

import type { PluginOptions, Preprocessor } from '@wyw-in-js/transform';
import {
slugify,
transform,
TransformCacheCollection,
} from '@wyw-in-js/transform';

type EsbuildPluginOptions = {
esbuildOptions?: TransformOptions;
preprocessor?: Preprocessor;
sourceMap?: boolean;
} & Partial<PluginOptions>;

const nodeModulesRegex = /^(?:.*[\\/])?node_modules(?:[\\/].*)?$/;

export default function wywInJS({
sourceMap,
preprocessor,
esbuildOptions,
...rest
}: EsbuildPluginOptions = {}): Plugin {
let options = esbuildOptions;
const cache = new TransformCacheCollection();
return {
name: 'wyw-in-js',
setup(build) {
const cssLookup = new Map<string, string>();

const asyncResolve = async (
token: string,
importer: string
): Promise<string> => {
const context = isAbsolute(importer)
? dirname(importer)
: join(process.cwd(), dirname(importer));

const result = await build.resolve(token, {
resolveDir: context,
kind: 'import-statement',
});

if (result.errors.length > 0) {
throw new Error(`Cannot resolve ${token}`);
}

return result.path.replace(/\\/g, posix.sep);
};

build.onResolve({ filter: /\.linaria\.css$/ }, (args) => {
return {
namespace: 'linaria',
path: args.path,
};
});

build.onLoad({ filter: /.*/, namespace: 'linaria' }, (args) => {
return {
contents: cssLookup.get(args.path),
loader: 'css',
resolveDir: basename(args.path),
};
});

build.onLoad({ filter: /\.(js|jsx|ts|tsx)$/ }, async (args) => {
const rawCode = readFileSync(args.path, 'utf8');
const { ext, name: filename } = parse(args.path);
const loader = ext.replace(/^\./, '') as Loader;

if (nodeModulesRegex.test(args.path)) {
return {
loader,
contents: rawCode,
};
}

if (!options) {
options = {};
if ('jsxFactory' in build.initialOptions) {
options.jsxFactory = build.initialOptions.jsxFactory;
}
if ('jsxFragment' in build.initialOptions) {
options.jsxFragment = build.initialOptions.jsxFragment;
}
}

const transformed = transformSync(rawCode, {
...options,
sourcefile: args.path,
sourcemap: sourceMap,
loader,
});
let { code } = transformed;

if (sourceMap) {
const esbuildMap = Buffer.from(transformed.map).toString('base64');
code += `/*# sourceMappingURL=data:application/json;base64,${esbuildMap}*/`;
}

const transformServices = {
options: {
filename: args.path,
root: process.cwd(),
preprocessor,
pluginOptions: rest,
},
cache,
};

const result = await transform(transformServices, code, asyncResolve);

if (!result.cssText) {
return {
contents: code,
loader,
resolveDir: dirname(args.path),
};
}

let { cssText } = result;

const slug = slugify(cssText);
const cssFilename = `${filename}_${slug}.linaria.css`;

let contents = `import ${JSON.stringify(cssFilename)}; ${result.code}`;

if (sourceMap && result.cssSourceMapText) {
const map = Buffer.from(result.cssSourceMapText).toString('base64');
cssText += `/*# sourceMappingURL=data:application/json;base64,${map}*/`;
const linariaMap = Buffer.from(
JSON.stringify(result.sourceMap)
).toString('base64');
contents += `/*# sourceMappingURL=data:application/json;base64,${linariaMap}*/`;
}

cssLookup.set(cssFilename, cssText);

return {
contents,
loader,
resolveDir: dirname(args.path),
};
});
},
};
}
4 changes: 4 additions & 0 deletions packages/esbuild/tsconfig.eslint.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"extends": "./tsconfig.json",
"include": ["./src/**/*.ts"]
}
13 changes: 13 additions & 0 deletions packages/esbuild/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"extends": "@wyw-in-js/ts-config/node.json",
"files": [],
"include": [],
"references": [
{
"path": "./tsconfig.lib.json"
},
{
"path": "./tsconfig.spec.json"
}
]
}
8 changes: 8 additions & 0 deletions packages/esbuild/tsconfig.lib.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./types"
},
"exclude": ["**/__tests__/*"],
"include": ["./src/**/*.ts"]
}
7 changes: 7 additions & 0 deletions packages/esbuild/tsconfig.spec.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"noEmit": true
},
"include": ["**/__tests__/*"]
}
28 changes: 28 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading