UNPKG

3.19 kBJavaScriptView Raw
1"use strict";
2
3exports.__esModule = true;
4exports.default = plugin;
5
6var t = _interopRequireWildcard(require("@babel/types"));
7
8var _getName = _interopRequireDefault(require("../utils/getName"));
9
10var _isCssTag = _interopRequireDefault(require("../utils/isCssTag"));
11
12function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
13
14function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
15
16function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
17
18function plugin() {
19 return {
20 name: 'convert-css-to-stylesheet',
21 visitor: {
22 Program: {
23 exit(program, state) {
24 const {
25 stylesheetTagName = 'stylesheet'
26 } = state.opts;
27 const safeToRemove = !state.file.get('HAS_LEGIT_CSS');
28 const shouldAdd = state.file.get('HAS_STYLESHEET');
29 program.traverse({
30 ImportDeclaration(path) {
31 if (path.get('source').node.value !== 'astroturf' && path.get('source').node.value !== 'astroturf/react') return;
32 const cssImport = path.get('specifiers').find(s => s.isImportSpecifier() && (0, _getName.default)(s.node.imported) === 'css');
33
34 if (shouldAdd) {
35 // @ts-ignore
36 path.unshiftContainer('specifiers', t.importSpecifier(t.identifier(stylesheetTagName), t.identifier('stylesheet')));
37 }
38
39 if (safeToRemove) {
40 if (cssImport) cssImport.remove();
41 }
42 }
43
44 });
45 }
46
47 },
48
49 TaggedTemplateExpression(path, state) {
50 const {
51 cssTagName = 'css',
52 stylesheetTagName = 'stylesheet',
53 allowGlobal = false
54 } = state.opts;
55 const tagPath = path.get('tag');
56
57 if (stylesheetTagName === false || !(0, _isCssTag.default)(tagPath, {
58 cssTagName,
59 allowGlobal
60 })) {
61 return;
62 }
63
64 if (path.findParent(p => p.isJSXAttribute())) {
65 state.file.set('HAS_LEGIT_CSS', true);
66 return;
67 }
68
69 state.file.set('HAS_STYLESHEET', true);
70 tagPath.replaceWith(t.identifier(stylesheetTagName));
71 }
72
73 }
74 };
75}
\No newline at end of file