UNPKG

1.96 kBJavaScriptView Raw
1import virtual from '@rollup/plugin-virtual';
2import { promise } from 'matched';
3
4/* eslint-disable no-param-reassign */
5
6const DEFAULT_OUTPUT = 'multi-entry.js';
7const AS_IMPORT = 'import';
8const AS_EXPORT = 'export * from';
9
10function multiEntry(conf = {}) {
11 const config = {
12 include: [],
13 exclude: [],
14 entryFileName: DEFAULT_OUTPUT,
15 exports: true,
16 ...conf
17 };
18
19 let prefix = config.exports === false ? AS_IMPORT : AS_EXPORT;
20 const exporter = (path) => `${prefix} ${JSON.stringify(path)}`;
21
22 const configure = (input) => {
23 if (typeof input === 'string') {
24 config.include = [input];
25 } else if (Array.isArray(input)) {
26 config.include = input;
27 } else {
28 const { include = [], exclude = [], entryFileName = DEFAULT_OUTPUT, exports } = input;
29 config.include = include;
30 config.exclude = exclude;
31 config.entryFileName = entryFileName;
32 if (exports === false) {
33 prefix = AS_IMPORT;
34 }
35 }
36 };
37
38 let virtualisedEntry;
39
40 return {
41 name: 'multi-entry',
42
43 options(options) {
44 if (options.input !== config.entryFileName) {
45 configure(options.input);
46 }
47 return {
48 ...options,
49 input: config.entryFileName
50 };
51 },
52
53 outputOptions(options) {
54 return {
55 ...options,
56 entryFileNames: config.entryFileName
57 };
58 },
59
60 buildStart(options) {
61 const patterns = config.include.concat(config.exclude.map((pattern) => `!${pattern}`));
62 const entries = patterns.length
63 ? promise(patterns, { realpath: true }).then((paths) => paths.map(exporter).join('\n'))
64 : Promise.resolve('');
65
66 virtualisedEntry = virtual({ [options.input]: entries });
67 },
68
69 resolveId(id, importer) {
70 return virtualisedEntry && virtualisedEntry.resolveId(id, importer);
71 },
72
73 load(id) {
74 return virtualisedEntry && virtualisedEntry.load(id);
75 }
76 };
77}
78
79export default multiEntry;