-
-
Notifications
You must be signed in to change notification settings - Fork 215
/
postcss-loader.js
222 lines (193 loc) · 6.61 KB
/
postcss-loader.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
import path from 'path'
import importCwd from 'import-cwd'
import postcss from 'postcss'
import findPostcssConfig from 'postcss-load-config'
import { identifier } from 'safe-identifier'
import humanlizePath from './utils/humanlize-path'
import normalizePath from './utils/normalize-path'
const styleInjectPath = require
.resolve('style-inject/dist/style-inject.es')
.replace(/[\\/]+/g, '/')
function loadConfig(id, { ctx: configOptions, path: configPath }) {
const handleError = err => {
if (!err.message.includes('No PostCSS Config found')) {
throw err
}
// Return empty options for PostCSS
return {}
}
configPath = configPath ? path.resolve(configPath) : path.dirname(id)
const ctx = {
file: {
extname: path.extname(id),
dirname: path.dirname(id),
basename: path.basename(id)
},
options: configOptions || {}
}
return findPostcssConfig(ctx, configPath).catch(handleError)
}
function escapeClassNameDashes(string) {
return string.replace(/-+/g, match => {
return `$${match.replace(/-/g, '_')}$`
})
}
function ensureClassName(name) {
name = escapeClassNameDashes(name)
return identifier(name, false)
}
function ensurePostCSSOption(option) {
return typeof option === 'string' ? importCwd(option) : option
}
function isModuleFile(file) {
return /\.module\.[a-z]{2,6}$/.test(file)
}
export default {
name: 'postcss',
alwaysProcess: true,
// `test` option is dynamically set in ./loaders
async process({ code, map }) {
const config = this.options.config ?
await loadConfig(this.id, this.options.config) :
{}
const { options } = this
const plugins = [
...(options.postcss.plugins || []),
...(config.plugins || [])
]
const shouldExtract = options.extract
const shouldInject = options.inject
const modulesExported = {}
const autoModules = options.autoModules !== false && isModuleFile(this.id)
const supportModules = options.modules || autoModules
if (supportModules) {
plugins.unshift(
require('postcss-modules')({
// In tests
// Skip hash in names since css content on windows and linux would differ because of `new line` (\r?\n)
generateScopedName: process.env.ROLLUP_POSTCSS_TEST ?
'[name]_[local]' :
'[name]_[local]__[hash:base64:5]',
...options.modules,
getJSON(filepath, json, outpath) {
modulesExported[filepath] = json
if (
typeof options.modules === 'object' &&
typeof options.modules.getJSON === 'function'
) {
return options.modules.getJSON(filepath, json, outpath)
}
}
})
)
}
// If shouldExtract, minimize is done after all CSS are extracted to a file
if (!shouldExtract && options.minimize) {
plugins.push(require('cssnano')(options.minimize))
}
const postcssOptions = {
...this.options.postcss,
...config.options,
// Allow overriding `to` for some plugins that are relying on this value
to: options.to || this.id,
// Followings are never modified by user config config
from: this.id,
map: this.sourceMap ?
(shouldExtract ?
{ inline: false, annotation: false } :
{ inline: true, annotation: false }) :
false
}
delete postcssOptions.plugins
postcssOptions.parser = ensurePostCSSOption(postcssOptions.parser)
postcssOptions.syntax = ensurePostCSSOption(postcssOptions.syntax)
postcssOptions.stringifier = ensurePostCSSOption(postcssOptions.stringifier)
if (map && postcssOptions.map) {
postcssOptions.map.prev = typeof map === 'string' ? JSON.parse(map) : map
}
if (plugins.length === 0) {
// Prevent from postcss warning:
// You did not set any plugins, parser, or stringifier. Right now, PostCSS does nothing. Pick plugins for your case on https://www.postcss.parts/ and use them in postcss.config.js
const noopPlugin = postcss.plugin('postcss-noop-plugin', () => () => {
/* noop */
})
plugins.push(noopPlugin())
}
const result = await postcss(plugins).process(code, postcssOptions)
for (const message of result.messages) {
if (message.type === 'dependency') {
this.dependencies.add(message.file)
}
}
for (const warning of result.warnings()) {
if (!warning.message) {
warning.message = warning.text
}
this.warn(warning)
}
const outputMap = result.map && JSON.parse(result.map.toString())
if (outputMap && outputMap.sources) {
outputMap.sources = outputMap.sources.map(v => normalizePath(v))
}
let output = ''
let extracted
if (options.namedExports) {
const json = modulesExported[this.id]
const getClassName =
typeof options.namedExports === 'function' ?
options.namedExports :
ensureClassName
// eslint-disable-next-line guard-for-in
for (const name in json) {
const newName = getClassName(name)
// Log transformed class names
// But skip this when namedExports is a function
// Since a user like you can manually log that if you want
if (name !== newName && typeof options.namedExports !== 'function') {
this.warn(
`Exported "${name}" as "${newName}" in ${humanlizePath(this.id)}`
)
}
if (!json[newName]) {
json[newName] = json[name]
}
output += `export var ${newName} = ${JSON.stringify(json[name])};\n`
}
}
const cssVariableName = identifier('css', true)
if (shouldExtract) {
output += `export default ${JSON.stringify(modulesExported[this.id])};`
extracted = {
id: this.id,
code: result.css,
map: outputMap
}
} else {
const module = supportModules ?
JSON.stringify(modulesExported[this.id]) :
cssVariableName
output +=
`var ${cssVariableName} = ${JSON.stringify(result.css)};\n` +
`export default ${module};\n` +
`export var stylesheet=${JSON.stringify(result.css)};`
}
if (!shouldExtract && shouldInject) {
if (typeof options.inject === 'function') {
output += options.inject(cssVariableName, this.id)
} else {
output += '\n' +
`import styleInject from '${styleInjectPath}';\n` +
`styleInject(${cssVariableName}${
Object.keys(options.inject).length > 0 ?
`,${JSON.stringify(options.inject)}` :
''
});`
}
}
return {
code: output,
map: outputMap,
extracted
}
}
}