react-live-unplugin
Version:
Turn React components into live code blocks with ease.
70 lines (69 loc) • 2.67 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.reactLiveUnplugin = void 0;
var _parser = require("@babel/parser");
var _defu = _interopRequireDefault(require("defu"));
var _unplugin = require("unplugin");
var _utils = require("./utils.cjs");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
const randomSeed = Math.random().toString(36).slice(2);
const defaults = {
id: /\.live\.(j|t)sx$/,
exclude: /node_modules/,
reactLiveModulePath: "react-live-unplugin/default/ReactLive",
reactLiveExportName: "ReactLive"
};
const reactLiveUnpluginFactory = options => {
const mergedOptions = (0, _defu.default)(options, defaults);
return {
name: "unplugin-react-live",
enforce: mergedOptions.enforce,
transform: {
filter: {
id: mergedOptions.id,
exclude: mergedOptions.exclude
},
async handler(code) {
const ast = (0, _parser.parse)(code, {
// parse in strict mode and allow module declarations
sourceType: "module",
plugins: ["jsx", "typescript"]
});
const imports = [];
const importsCode = [];
const traverse = await (0, _utils.interopDefault)((0, _utils.interopDefault)(Promise.resolve().then(() => require("@babel/traverse"))));
traverse(ast, {
ImportDeclaration(path) {
importsCode.push(code.substring(path.node.start ?? 0, path.node.end ?? code.length));
path.node.specifiers.forEach(specifier => {
imports.push(specifier.local.name);
});
}
});
const codeVarName = `code_${randomSeed}`;
const scopeVarName = `scope_${randomSeed}`;
const componentVarName = `Component_${randomSeed}`;
const codeCode = `const ${codeVarName} = ${JSON.stringify(code)};`;
const scopeCode = `const ${scopeVarName} = ${imports.length === 0 ? "{}" : `{ ${imports.join(", ")} }`};`;
const exportDemo = `export default function Demo() {
return (
<${componentVarName} scope={${scopeVarName}} code={${codeVarName}} />
);
}`;
const compiled = `import { ${mergedOptions.reactLiveExportName} as ${componentVarName} } from "${mergedOptions.reactLiveModulePath.replace(/"/g, '\\"')}";
${importsCode.join("\n")}
${codeCode}
${scopeCode}
${exportDemo}
`;
return compiled;
}
}
};
};
const reactLiveUnpluginInternal = (0, _unplugin.createUnplugin)(reactLiveUnpluginFactory);
const reactLiveUnplugin = exports.reactLiveUnplugin = Object.assign(reactLiveUnpluginInternal, {
defaults
});