1 | import fs from 'fs-extra';
|
2 | import { dirname } from 'path';
|
3 | import less from 'less';
|
4 | import { createFilter } from 'rollup-pluginutils';
|
5 | import { insertStyle } from './style.js'
|
6 |
|
7 | let 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 |
|
16 | let fileCount = 0
|
17 |
|
18 | export 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 |
|
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 |
|
60 | function isString (str) {
|
61 | if(typeof str == 'string'){
|
62 | return true;
|
63 | }else{
|
64 | return false;
|
65 | }
|
66 | }
|
67 |
|
68 | function isFunc (fn){
|
69 | if ( typeof fn == 'function' ){
|
70 | return true
|
71 | }else{
|
72 | return false
|
73 | }
|
74 | } |
\ | No newline at end of file |