/
loadConfigFile.ts
127 lines (119 loc) · 4.47 KB
/
loadConfigFile.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
import { bold } from 'colorette';
import * as fs from 'fs';
import * as path from 'path';
import { pathToFileURL } from 'url';
import * as rollup from '../../src/node-entry';
import { MergedRollupOptions } from '../../src/rollup/types';
import { error } from '../../src/utils/error';
import { mergeOptions } from '../../src/utils/options/mergeOptions';
import { GenericConfigObject } from '../../src/utils/options/options';
import relativeId from '../../src/utils/relativeId';
import { stderr } from '../logging';
import batchWarnings, { BatchWarnings } from './batchWarnings';
import { addCommandPluginsToInputOptions } from './commandPlugins';
function supportsNativeESM() {
return Number(/^v(\d+)/.exec(process.version)![1]) >= 13;
}
interface NodeModuleWithCompile extends NodeModule {
_compile(code: string, filename: string): any;
}
export default async function loadAndParseConfigFile(
fileName: string,
commandOptions: any = {}
): Promise<{ options: MergedRollupOptions[]; warnings: BatchWarnings }> {
const configs = await loadConfigFile(fileName, commandOptions);
const warnings = batchWarnings();
try {
const normalizedConfigs = configs.map(config => {
const options = mergeOptions(config, commandOptions, warnings.add);
addCommandPluginsToInputOptions(options, commandOptions);
return options;
});
return { options: normalizedConfigs, warnings };
} catch (err) {
warnings.flush();
throw err;
}
}
async function loadConfigFile(
fileName: string,
commandOptions: any
): Promise<GenericConfigObject[]> {
const extension = path.extname(fileName);
const configFileExport =
extension === '.mjs' && supportsNativeESM()
? (await import(pathToFileURL(fileName).href)).default
: extension === '.cjs'
? getDefaultFromCjs(require(fileName))
: await getDefaultFromTranspiledConfigFile(fileName, commandOptions.silent);
return getConfigList(configFileExport, commandOptions);
}
function getDefaultFromCjs(namespace: GenericConfigObject) {
return namespace.__esModule ? namespace.default : namespace;
}
async function getDefaultFromTranspiledConfigFile(
fileName: string,
silent: boolean
): Promise<unknown> {
const warnings = batchWarnings();
const bundle = await rollup.rollup({
external: (id: string) =>
(id[0] !== '.' && !path.isAbsolute(id)) || id.slice(-5, id.length) === '.json',
input: fileName,
onwarn: warnings.add,
treeshake: false
});
if (!silent && warnings.count > 0) {
stderr(bold(`loaded ${relativeId(fileName)} with warnings`));
warnings.flush();
}
const {
output: [{ code }]
} = await bundle.generate({
exports: 'named',
format: 'cjs'
});
return loadConfigFromBundledFile(fileName, code);
}
async function loadConfigFromBundledFile(fileName: string, bundledCode: string) {
const resolvedFileName = fs.realpathSync(fileName);
const extension = path.extname(resolvedFileName);
const defaultLoader = require.extensions[extension];
require.extensions[extension] = (module: NodeModule, requiredFileName: string) => {
if (requiredFileName === resolvedFileName) {
(module as NodeModuleWithCompile)._compile(bundledCode, requiredFileName);
} else {
defaultLoader(module, requiredFileName);
}
};
delete require.cache[resolvedFileName];
try {
const config = getDefaultFromCjs(require(fileName));
require.extensions[extension] = defaultLoader;
return config;
} catch (err) {
if (err.code === 'ERR_REQUIRE_ESM') {
return error({
code: 'TRANSPILED_ESM_CONFIG',
message: `While loading the Rollup configuration from "${relativeId(
fileName
)}", Node tried to require an ES module from a CommonJS file, which is not supported. A common cause is if there is a package.json file with "type": "module" in the same folder. You can try to fix this by changing the extension of your configuration file to ".cjs" or ".mjs" depending on the content, which will prevent Rollup from trying to preprocess the file but rather hand it to Node directly.`,
url: 'https://rollupjs.org/guide/en/#using-untranspiled-config-files'
});
}
throw err;
}
}
async function getConfigList(configFileExport: any, commandOptions: any) {
const config = await (typeof configFileExport === 'function'
? configFileExport(commandOptions)
: configFileExport);
if (Object.keys(config).length === 0) {
return error({
code: 'MISSING_CONFIG',
message: 'Config file must export an options object, or an array of options objects',
url: 'https://rollupjs.org/guide/en/#configuration-files'
});
}
return Array.isArray(config) ? config : [config];
}