UNPKG

1.88 kBJavaScriptView Raw
1const requireTrueValue = value => {
2 if (value !== true) {
3 throw new TypeError('When specifying module types, use `true` for ’cjs’, ’mjs’ and ’js’ extensions');
4 }
5};
6
7const normalize = (extension, type, defaultModuleType) => {
8 switch (extension) {
9 case 'cjs':
10 requireTrueValue(type);
11 return 'commonjs';
12 case 'mjs':
13 requireTrueValue(type);
14 return 'module';
15 case 'js':
16 requireTrueValue(type);
17 return defaultModuleType;
18 default:
19 if (type !== 'commonjs' && type !== 'module') {
20 throw new TypeError(`Module type for ’${extension}’ must be ’commonjs’ or ’module’`);
21 }
22
23 return type;
24 }
25};
26
27const deriveFromObject = (extensionsObject, defaultModuleType) => {
28 const moduleTypes = {};
29 for (const [extension, type] of Object.entries(extensionsObject)) {
30 moduleTypes[extension] = normalize(extension, type, defaultModuleType);
31 }
32
33 return moduleTypes;
34};
35
36const deriveFromArray = (extensions, defaultModuleType) => {
37 const moduleTypes = {};
38 for (const extension of extensions) {
39 switch (extension) {
40 case 'cjs':
41 moduleTypes.cjs = 'commonjs';
42 break;
43 case 'mjs':
44 moduleTypes.mjs = 'module';
45 break;
46 case 'js':
47 moduleTypes.js = defaultModuleType;
48 break;
49 default:
50 moduleTypes[extension] = 'commonjs';
51 }
52 }
53
54 return moduleTypes;
55};
56
57module.exports = (configuredExtensions, defaultModuleType, experiments) => {
58 if (configuredExtensions === undefined) {
59 return {
60 cjs: 'commonjs',
61 mjs: 'module',
62 js: defaultModuleType
63 };
64 }
65
66 if (Array.isArray(configuredExtensions)) {
67 return deriveFromArray(configuredExtensions, defaultModuleType);
68 }
69
70 if (!experiments.configurableModuleFormat) {
71 throw new Error('You must enable the `configurableModuleFormat` experiment in order to specify module types');
72 }
73
74 return deriveFromObject(configuredExtensions, defaultModuleType);
75};