Mirror: Rollup plugin to automatically check the exports of a library for cjs-module-lexer compatibility.
at v1.0.1 1.7 kB view raw
1import { parse, init } from 'cjs-module-lexer'; 2import { createFilter } from '@rollup/pluginutils'; 3 4function cjsCheck(opts = {}) { 5 const filter = createFilter(opts.include, opts.exclude, { 6 resolve: false 7 }); 8 9 return { 10 name: "cjs-check", 11 12 async renderChunk(code, chunk) { 13 if (!filter(chunk.fileName)) { 14 return null; 15 } else if (!/\.c?js$/g.test(chunk.fileName)) { 16 return null; 17 } 18 19 await init() 20 const output = parse(code); 21 const missingReexports = []; 22 const missingExports = []; 23 24 let hasMissing = false; 25 for (const mod of chunk.exports) { 26 if (mod[0] == '*' && !output.reexports.includes(mod.slice(1))) { 27 hasMissing = true; 28 missingReexports.push(mod.slice(1)); 29 } else if (mod[0] != '*' && !output.exports.includes(mod)) { 30 hasMissing = true; 31 missingExports.push(mod); 32 } 33 } 34 35 if (hasMissing) { 36 let message = ''; 37 if (missingReexports.length) { 38 message += 'The following re-exports are undetected:\n'; 39 message += missingReexports.map(x => `- ${x}\n`).join(''); 40 } 41 42 if (missingExports.length) { 43 message += 'The following exports are undetected:\n'; 44 message += missingExports.map(x => `- ${x}\n`).join(''); 45 } 46 47 if (missingExports.length + missingReexports.length >= chunk.exports.length) { 48 message = 'All chunk exports have not been detected. Is the chunk a CommonJS module?' 49 } 50 51 throw new Error( 52 `cjs-module-lexer did not agree with Rollup\'s exports for ${chunk.fileName}.\n${message}` 53 ); 54 } 55 56 return null; 57 } 58 }; 59} 60 61export default cjsCheck;