@beqa/unplugin-transform-react-slots
Version:
JSX to slot function transpilation plugin for some of the common build systems
83 lines (79 loc) • 2.5 kB
JavaScript
// src/index.ts
import { createUnplugin } from "unplugin";
import { createFilter } from "@rollup/pluginutils";
// src/core/options.ts
var defaultInclude = /\.(js)|(jsx)|(cjs)|(cjsx)|(mjs)|(mjsx)|(tsx)|(ctsx)|(mtsx)/;
function resolveOption(options = {}) {
const include = options.include ?? defaultInclude;
let exclude = [/node_modules/];
if (options.exclude) {
exclude = exclude.concat(options.exclude);
}
return {
include,
exclude
};
}
// src/index.ts
import { transformAsync } from "@babel/core";
import transformReactSlots from "@beqa/babel-plugin-transform-react-slots";
import SyntaxTypescript from "@babel/plugin-syntax-typescript";
var isDisabledRegex = /^(?:\s*(?:\/\/[^\n\r]*|\/\*(?:.|[\n\r])*?\*\/))*\s*\/\/\s*@disable-transform-react-slots\W/;
function appendTestComment(code, isDisabled) {
if (isDisabled) {
code += "/* slot transformation skipped by unplugin-transform-react-slots */";
} else {
code += "/* slot transformation done by unplugin-transform-react-slots */";
}
return code;
}
var src_default = createUnplugin((rawOptions) => {
const options = resolveOption(rawOptions);
const filter = createFilter(options.include, options.exclude);
return {
name: "unplugin-transform-react-slots",
enforce: "pre",
transformInclude(id) {
return filter(id);
},
async transform(code, id) {
if (id.endsWith(".ts")) {
return appendTestComment(code, true);
}
if (isDisabledRegex.test(code)) {
return appendTestComment(code, true);
}
if (!(code.includes("@beqa/react-slots") && code.includes("useSlot"))) {
return appendTestComment(code, true);
}
const transformed = await transformAsync(code, {
plugins: [
id.endsWith(".tsx") ? [SyntaxTypescript, { isTSX: true }] : "",
transformReactSlots
].filter(Boolean),
filename: id
});
if (!transformed) {
throw new Error(
"unplugin-transform-react-slots failed to transform file: " + id
);
}
return transformed.code && appendTestComment(transformed.code, false);
},
esbuild: {
onLoadFilter: !!options.include && !Array.isArray(options.include) ? options.include : defaultInclude,
loader(code, id) {
if (id.endsWith("tsx")) {
return "tsx";
}
if (id.endsWith("ts")) {
return "ts";
}
return "jsx";
}
}
};
});
export {
src_default
};