|
| 1 | +import path from 'path' |
| 2 | +import { createFilter } from 'rollup-pluginutils' |
| 3 | +import Loaders from './loaders' |
| 4 | +import styleInject from 'style-inject' |
| 5 | +import fs from 'fs-extra' |
| 6 | +import Concat from 'concat-with-sourcemaps' |
| 7 | + |
| 8 | +const EXT = ['.css', '.styl', '.sass', '.scss', '.less'] |
| 9 | + |
| 10 | +export default (options = {}) => { |
| 11 | + const filter = createFilter(options.include, options.exclude) |
| 12 | + |
| 13 | + const inject = typeof options.inject === 'undefined' ? {} : options.inject |
| 14 | + |
| 15 | + let use = options.use || ['css', 'postcss'] |
| 16 | + use = use.reduce((res, rule) => { |
| 17 | + if (typeof rule === 'string') { |
| 18 | + rule = [rule] |
| 19 | + } |
| 20 | + const name = rule[0] |
| 21 | + const options = rule[1] || {} |
| 22 | + |
| 23 | + if (name === 'css') { |
| 24 | + if (typeof options.inject === 'undefined') { |
| 25 | + options.inject = true |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + res[name] = options |
| 30 | + return res |
| 31 | + }, {}) |
| 32 | + const loaders = new Loaders({ |
| 33 | + use |
| 34 | + }) |
| 35 | + |
| 36 | + const extracted = [] |
| 37 | + |
| 38 | + return { |
| 39 | + name: 'postcss', |
| 40 | + |
| 41 | + intro() { |
| 42 | + if (!use.css.inject || use.css.extract) return |
| 43 | + return styleInject.toString().replace('styleInject', '__$$styleInject') |
| 44 | + }, |
| 45 | + |
| 46 | + async transform(code, id) { |
| 47 | + if (!filter(id) || !loaders.isSupported(id)) { |
| 48 | + return null |
| 49 | + } |
| 50 | + |
| 51 | + const res = await loaders.process({ |
| 52 | + code, |
| 53 | + map: undefined, |
| 54 | + id |
| 55 | + }) |
| 56 | + |
| 57 | + if (use.css.extract) { |
| 58 | + extracted.push(res.extracted) |
| 59 | + return { |
| 60 | + code: res.code, |
| 61 | + map: { mappings: '' } |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + return { |
| 66 | + code: res.code, |
| 67 | + map: res.map |
| 68 | + } |
| 69 | + }, |
| 70 | + |
| 71 | + async onwrite(opts) { |
| 72 | + if (extracted.length === 0) return |
| 73 | + |
| 74 | + const basename = path.basename(opts.file, path.extname(opts.file)) |
| 75 | + const file = path.relative(process.cwd(), path.join( |
| 76 | + path.dirname(opts.file), |
| 77 | + basename + '.css' |
| 78 | + )) |
| 79 | + const concat = new Concat(true, file, '\n') |
| 80 | + for (const res of extracted) { |
| 81 | + const relative = path.relative(process.cwd(), res.id) |
| 82 | + concat.add(relative, res.code, res.map) |
| 83 | + } |
| 84 | + const code = concat.content + `\n/*# sourceMappingURL=${basename}.css.map */` |
| 85 | + await Promise.all([ |
| 86 | + fs.writeFile(file, code, 'utf8'), |
| 87 | + fs.writeFile(file + '.map', concat.sourceMap, 'utf8') |
| 88 | + ]) |
| 89 | + } |
| 90 | + } |
| 91 | +} |
0 commit comments