UNPKG

3.22 kBJavaScriptView Raw
1"use strict";
2
3exports.__esModule = true;
4exports.default = plugin;
5
6var _commonTags = require("common-tags");
7
8var _fsExtra = require("fs-extra");
9
10var _defaults = _interopRequireDefault(require("lodash/defaults"));
11
12var _generator = _interopRequireDefault(require("@babel/generator"));
13
14var _traverse = require("@babel/traverse");
15
16var _cssProp = _interopRequireDefault(require("./features/css-prop"));
17
18var _styledComponent = _interopRequireDefault(require("./features/styled-component"));
19
20var _stylesheet = _interopRequireDefault(require("./features/stylesheet"));
21
22var _Symbols = require("./utils/Symbols");
23
24function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
25
26function plugin() {
27 return {
28 pre(file) {
29 file.set(_Symbols.IMPORTS, []);
30
31 if (!file.has(_Symbols.STYLES)) {
32 file.set(_Symbols.STYLES, {
33 id: 0,
34 changeset: [],
35 styles: new Map()
36 });
37 }
38
39 if (!file.has(_Symbols.COMPONENTS)) {
40 file.set(_Symbols.COMPONENTS, new Map());
41 }
42 },
43
44 post(file) {
45 const {
46 opts
47 } = this;
48 let {
49 styles,
50 changeset
51 } = file.get(_Symbols.STYLES);
52 const importNodes = file.get(_Symbols.IMPORTS);
53 importNodes.forEach(path => {
54 const decl = !path.isImportDeclaration() ? path.findParent(p => p.isImportDeclaration()) : path;
55 if (!decl) return;
56 const {
57 start,
58 end
59 } = decl.node;
60 path.remove();
61 if (opts.generateInterpolations) changeset.push({
62 start,
63 end,
64 // if the path is just a removed specifier we need to regenerate
65 // the import statement otherwise we remove the entire declaration
66 code: !path.isImportDeclaration() ? (0, _generator.default)(decl.node).code : ''
67 });
68 });
69 styles = Array.from(styles.values());
70 changeset = changeset.concat(styles);
71 file.metadata.astroturf = {
72 styles,
73 changeset
74 };
75
76 if (opts.writeFiles !== false) {
77 styles.forEach(({
78 absoluteFilePath,
79 value
80 }) => {
81 (0, _fsExtra.outputFileSync)(absoluteFilePath, (0, _commonTags.stripIndent)([value]));
82 });
83 }
84 },
85
86 visitor: _traverse.visitors.merge([{
87 Program: {
88 enter(_, state) {
89 state.defaultedOptions = (0, _defaults.default)(state.opts, {
90 tagName: 'css',
91 allowGlobal: true,
92 styledTag: 'styled',
93 customCssProperties: 'cssProp' // or: true, false
94
95 });
96 }
97
98 },
99 ImportDeclaration: {
100 exit(path, state) {
101 const {
102 tagName
103 } = state.defaultedOptions;
104 const specifiers = path.get('specifiers');
105 const tagImport = path.get('specifiers').find(p => p.isImportSpecifier() && p.node.imported.name === 'css' && p.node.local.name === tagName);
106
107 if (tagImport) {
108 state.file.get(_Symbols.IMPORTS).push(specifiers.length === 1 ? path : tagImport);
109 }
110 }
111
112 }
113 }, _cssProp.default, _styledComponent.default, _stylesheet.default])
114 };
115}
\No newline at end of file