UNPKG

1.91 kBJavaScriptView Raw
1import path from 'path';
2import templateBuilder from '@babel/template';
3
4function isAtom(t, callee) {
5 if (t.isIdentifier(callee) && atomFunctionNames.includes(callee.name)) {
6 return true;
7 }
8 if (t.isMemberExpression(callee)) {
9 const { property } = callee;
10 if (t.isIdentifier(property) && atomFunctionNames.includes(property.name)) {
11 return true;
12 }
13 }
14 return false;
15}
16const atomFunctionNames = [
17 "atom",
18 "atomFamily",
19 "atomWithDefault",
20 "atomWithObservable",
21 "atomWithReducer",
22 "atomWithReset",
23 "atomWithStorage",
24 "freezeAtom",
25 "loadable",
26 "selectAtom",
27 "splitAtom"
28];
29
30function debugLabelPlugin({
31 types: t
32}) {
33 return {
34 visitor: {
35 ExportDefaultDeclaration(nodePath, state) {
36 const { node } = nodePath;
37 if (t.isCallExpression(node.declaration) && isAtom(t, node.declaration.callee)) {
38 const filename = state.filename || "unknown";
39 let displayName = path.basename(filename, path.extname(filename));
40 if (displayName === "index") {
41 displayName = path.basename(path.dirname(filename));
42 }
43 const buildExport = templateBuilder(`
44 const %%atomIdentifier%% = %%atom%%;
45 export default %%atomIdentifier%%
46 `);
47 const ast = buildExport({
48 atomIdentifier: t.identifier(displayName),
49 atom: node.declaration
50 });
51 nodePath.replaceWithMultiple(ast);
52 }
53 },
54 VariableDeclarator(path2) {
55 if (t.isIdentifier(path2.node.id) && t.isCallExpression(path2.node.init) && isAtom(t, path2.node.init.callee)) {
56 path2.parentPath.insertAfter(t.expressionStatement(t.assignmentExpression("=", t.memberExpression(t.identifier(path2.node.id.name), t.identifier("debugLabel")), t.stringLiteral(path2.node.id.name))));
57 }
58 }
59 }
60 };
61}
62
63export { debugLabelPlugin as default };