|
| 1 | +'use strict'; |
| 2 | +/** |
| 3 | + * Inspired from rollup-plugin-replace https://github.com/rollup/rollup-plugin-replace/blob/master/src/index.js |
| 4 | + * and |
| 5 | + * strip-pragma-loader https://github.com/AnalyticalGraphicsInc/strip-pragma-loader/blob/master/index.js |
| 6 | + * |
| 7 | + * Usage: |
| 8 | + * |
| 9 | + * const rollup = require('rollup'); |
| 10 | + * const rollupStripPragma = require('./rollup-plugin-strip-pragma'); |
| 11 | + * const bundle = await rollup.rollup({ |
| 12 | + * input: ....., |
| 13 | + * plugins: [ |
| 14 | + * rollupStripPragma({ |
| 15 | + * include: '*', // optional |
| 16 | + * pragmas: [ 'debug', .... ] |
| 17 | + * }) |
| 18 | + * ] |
| 19 | + * }); |
| 20 | + */ |
| 21 | +const MagicString = require('magic-string'); |
| 22 | +const { createFilter } = require('rollup-pluginutils'); |
| 23 | + |
| 24 | +function escapeCharacters(token) { |
| 25 | + return token.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&'); |
| 26 | +} |
| 27 | + |
| 28 | +function constructRegex(pragma) { |
| 29 | + const prefix = 'include'; |
| 30 | + pragma = escapeCharacters(pragma); |
| 31 | + |
| 32 | + const s = '[\\t ]*\\/\\/>>\\s?' + |
| 33 | + prefix + |
| 34 | + 'Start\\s?\\(\\s?(["\'])' + |
| 35 | + pragma + |
| 36 | + '\\1\\s?,\\s?pragmas\\.' + |
| 37 | + pragma + |
| 38 | + '\\s?\\)\\s?;?' + |
| 39 | + |
| 40 | + // multiline code block |
| 41 | + '[\\s\\S]*?' + |
| 42 | + |
| 43 | + // end comment |
| 44 | + '[\\t ]*\\/\\/>>\\s?' + |
| 45 | + prefix + |
| 46 | + 'End\\s?\\(\\s?(["\'])' + |
| 47 | + pragma + |
| 48 | + '\\2\\s?\\)\\s?;?\\s?[\\t]*\\n?'; |
| 49 | + |
| 50 | + return new RegExp(s, 'gm'); |
| 51 | +} |
| 52 | + |
| 53 | +function stripPragma(options = {}) { |
| 54 | + const filter = createFilter(options.include, options.exclude); |
| 55 | + const patterns = options.pragmas.map(pragma => constructRegex(pragma)); |
| 56 | + |
| 57 | + return { |
| 58 | + name: 'replace', |
| 59 | + |
| 60 | + // code: The contents of the file |
| 61 | + // id: the file path |
| 62 | + transform(code, id) { |
| 63 | + // Filters out includes and excluded files |
| 64 | + if (!filter(id)) { |
| 65 | + return null; |
| 66 | + } |
| 67 | + |
| 68 | + const magicString = new MagicString(code); |
| 69 | + |
| 70 | + let match; |
| 71 | + let start; |
| 72 | + let end; |
| 73 | + |
| 74 | + for (let i = 0; i < patterns.length; i++) { |
| 75 | + const pattern = patterns[i]; |
| 76 | + while ((match = pattern.exec(code))) { |
| 77 | + start = match.index; |
| 78 | + end = start + match[0].length; |
| 79 | + magicString.overwrite(start, end, ''); |
| 80 | + } |
| 81 | + } |
| 82 | + |
| 83 | + const result = { code: magicString.toString() }; |
| 84 | + return result; |
| 85 | + } |
| 86 | + }; |
| 87 | +} |
| 88 | + |
| 89 | +module.exports = stripPragma; |
0 commit comments