UNPKG

2.12 kBJavaScriptView Raw
1"use strict";
2
3exports.__esModule = true;
4exports.default = addPragma;
5
6var _helperModuleImports = require("@babel/helper-module-imports");
7
8var _template = _interopRequireDefault(require("@babel/template"));
9
10function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
11
12const opts = {
13 placeholderPattern: false,
14 placeholderWhitelist: new Set(['JSX', 'JSX_FRAG'])
15}; // This pattern of imports is necessary otherwise babel typescript will
16// remove the import as "type only"
17
18const importPattern = 'import JSX from "astroturf/jsx";';
19const buildImport = (0, _template.default)(importPattern, opts);
20const requirePattern = 'const JSX = require("astroturf/jsx");';
21const buildRequire = (0, _template.default)(requirePattern, opts);
22
23function addPragma(path, JSX, insertComments = true) {
24 const [builder, pattern] = (0, _helperModuleImports.isModule)(path) ? [buildImport, importPattern] : [buildRequire, requirePattern];
25 const importNode = builder({
26 JSX
27 }); // see importInjector for note about blockHoist
28
29 const targetPath = path.get('body').find(p => {
30 // @ts-ignore
31 const blockHoist = p.node._blockHoist; // eslint-disable-line no-underscore-dangle
32
33 return blockHoist != null && blockHoist < 4;
34 });
35 if (targetPath) targetPath.insertBefore(importNode);else path.unshiftContainer('body', importNode);
36 const changes = [];
37
38 if (insertComments) {
39 const jsxPrgama = `* @jsx ${JSX.name} `;
40 const jsxFragPrgama = `* @jsxFrag ${JSX.name}.F `;
41 path.addComment('leading', '* @jsxRuntime classic');
42 path.addComment('leading', jsxPrgama);
43 path.addComment('leading', jsxFragPrgama);
44 changes.push({
45 type: 'pragma',
46 code: `/** @jsxRuntime classic*/\n`,
47 start: 0,
48 end: 0
49 }, {
50 type: 'pragma',
51 code: `/*${jsxPrgama}*/\n`,
52 start: 0,
53 end: 0
54 }, {
55 type: 'pragma',
56 code: `/*${jsxFragPrgama}*/\n\n`,
57 start: 0,
58 end: 0
59 });
60 }
61
62 changes.push({
63 type: 'pragma',
64 code: `${pattern.replace('JSX', JSX.name)}\n`,
65 start: 0,
66 end: 0
67 });
68 return changes;
69}
\No newline at end of file