UNPKG

1.95 kBJavaScriptView Raw
1import fs from 'fs-extra';
2import { dirname } from 'path';
3import less from 'less';
4import { createFilter } from 'rollup-pluginutils';
5import { insertStyle } from './style.js'
6
7let renderSync = (code, option) => {
8 return new Promise((resolve, reject) => {
9 less.render(code, option, function(e, output){
10 if(e) throw e;
11 resolve(output.css);
12 });
13 });
14};
15
16let fileCount = 0
17
18export default function plugin(options = {}) {
19 const filter = createFilter(options.include || [ '**/*.less', '**/*.less' ], options.exclude || 'node_modules/**');
20
21 const injectFnName = '__$styleInject'
22 return {
23 name: 'less',
24 intro() {
25 return insertStyle.toString().replace(/insertStyle/, injectFnName);
26 },
27 async transform(code, id) {
28 if (!filter(id)) {
29 return null;
30 }
31 fileCount++
32
33 try {
34 let css = await renderSync(code, options.option)
35
36 if(isFunc(options.output)){
37 css = await options.output(css, id);
38 }
39
40 if (isString(options.output)) {
41 if(fileCount == 1){
42 //clean output file
43 fs.removeSync(options.output)
44 }
45 fs.appendFileSync(options.output, css);
46 }
47
48 let exportCode = `export default ${injectFnName}(${JSON.stringify(css.toString())});`
49 return {
50 code: exportCode,
51 map: { mappings: '' }
52 };
53 } catch (error) {
54 throw error;
55 }
56 }
57 };
58};
59
60function isString (str) {
61 if(typeof str == 'string'){
62 return true;
63 }else{
64 return false;
65 }
66}
67
68function isFunc (fn){
69 if ( typeof fn == 'function' ){
70 return true
71 }else{
72 return false
73 }
74}
\No newline at end of file