-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
inline.js
111 lines (96 loc) Β· 2.81 KB
/
inline.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
// @flow strict-local
import type {MutableAsset, TransformerResult} from '@parcel/types';
import {md5FromString} from '@parcel/utils';
import type {PostHTMLNode} from 'posthtml';
import PostHTML from 'posthtml';
import nullthrows from 'nullthrows';
const SCRIPT_TYPES = {
'application/javascript': 'js',
'text/javascript': 'js',
'application/json': false,
'application/ld+json': 'jsonld',
'text/html': false,
};
export default function extractInlineAssets(
asset: MutableAsset,
): Array<TransformerResult> {
let ast = nullthrows(asset.ast);
let program: PostHTMLNode = ast.program;
let key = 0;
// Extract inline <script> and <style> tags for processing.
let parts = [];
new PostHTML().walk.call(program, (node: PostHTMLNode) => {
let parcelKey = md5FromString(`${asset.id}:${key++}`);
if (node.tag === 'script' || node.tag === 'style') {
let value = node.content && node.content.join('').trim();
if (value != null) {
let type;
if (node.tag === 'style') {
if (node.attrs && node.attrs.type) {
type = node.attrs.type.split('/')[1];
} else {
type = 'css';
}
} else if (node.attrs && node.attrs.type) {
// Skip JSON
if (SCRIPT_TYPES[node.attrs.type] === false) {
return node;
}
if (SCRIPT_TYPES[node.attrs.type]) {
type = SCRIPT_TYPES[node.attrs.type];
} else {
type = node.attrs.type.split('/')[1];
}
} else {
type = 'js';
}
if (!node.attrs) {
node.attrs = {};
}
// allow a script/style tag to declare its key
if (node.attrs['data-parcel-key']) {
parcelKey = node.attrs['data-parcel-key'];
}
// Inform packager to remove type, since CSS and JS are the defaults.
// Unless it's application/ld+json
if (
node.attrs &&
(node.tag === 'style' ||
(node.attrs.type && SCRIPT_TYPES[node.attrs.type] === 'js'))
) {
delete node.attrs.type;
}
// insert parcelId to allow us to retrieve node during packaging
node.attrs['data-parcel-key'] = parcelKey;
parts.push({
type,
code: value,
uniqueKey: parcelKey,
isIsolated: true,
isInline: true,
meta: {
type: 'tag',
node,
},
});
}
}
// Process inline style attributes.
if (node.attrs && node.attrs.style) {
parts.push({
type: 'css',
code: node.attrs.style,
uniqueKey: parcelKey,
isIsolated: true,
isInline: true,
meta: {
type: 'attr',
node,
},
});
}
return node;
});
// $FlowFixMe
return parts;
}