I use a CLI that reads capacitor.config.ts
. For some reason, I get "ReferenceError: await is not defined" when the CLI reads the file. I recently had the same error with Vite, but cannot reproduce it.
import type {AppConfig} from '../../utils/app-config';
import {resolveAllConfigs} from '../../utils/app-config';
import type {CapacitorConfig} from '@capacitor/cli';
const appConfig: AppConfig = (await resolveAllConfigs({}));
export default ({} as CapacitorConfig);
[error] Parsing capacitor.config.ts failed.
ReferenceError: await is not defined
at Object.<anonymous>
(/Users/oliver/Desktop/temp/app-mobile/mobile/packages/app/capacitor.config.ts:4:19)
at Module._compile (node:internal/modules/cjs/loader:1256:14)
at require.extensions..ts
(/Users/oliver/Desktop/temp/app-mobile/mobile/node_modules/.pnpm/@capacitor+cli@5.4.1/node_modules/@capacitor/cli/dist/util/node.js:34:72)
at Module.load (node:internal/modules/cjs/loader:1119:32)
at Module._load (node:internal/modules/cjs/loader:960:12)
at Module.require (node:internal/modules/cjs/loader:1143:19)
at require (node:internal/modules/cjs/helpers:121:18)
at requireTS
(/Users/oliver/Desktop/temp/app-mobile/mobile/node_modules/.pnpm/@capacitor+cli@5.4.1/node_modules/@capacitor/cli/dist/util/node.js:36:15)
at loadExtConfigTS
(/Users/oliver/Desktop/temp/app-mobile/mobile/node_modules/.pnpm/@capacitor+cli@5.4.1/node_modules/@capacitor/cli/dist/config.js:89:54)
at loadExtConfig
(/Users/oliver/Desktop/temp/app-mobile/mobile/node_modules/.pnpm/@capacitor+cli@5.4.1/node_modules/@capacitor/cli/dist/config.js:123:16)
import type {AppConfig, AppConfigEnv} from './app-config';
import * as cc from 'cosmiconfig';
import {TypeScriptLoader} from 'cosmiconfig-typescript-loader';
import _ from 'lodash';
const COSMICONFIG_LOADERS: cc.Loaders = {'.ts': TypeScriptLoader()};
const resolveConfig = (async(moduleName: string, env: AppConfigEnv): Promise<AppConfig> => {
const explorer: cc.PublicExplorer = cc.cosmiconfig(moduleName, {loaders: COSMICONFIG_LOADERS});
const result: (cc.CosmiconfigResult | null) = (await explorer.search());
if(!result) {
throw (new Error(`Could not find a valid ${moduleName} configuration.`));
}
if((typeof result.config === 'object')) {
// Object or Promise.
return (await result.config);
} else if((typeof result.config === 'function')) {
// Function.
return (await result.config(env));
}
throw (new Error(`Invalid ${moduleName} configuration.`));
});
const resolveAllConfigs = (async(env: AppConfigEnv): Promise<AppConfig> => {
const isDevelopment: boolean = (env.mode === 'development');
return _.merge(
(await resolveConfig('app', env)),
...(isDevelopment ? [
(await resolveConfig('app--local-default', env)),
(await resolveConfig('app--local', env))
] : [])
);
});
export {
resolveConfig,
resolveAllConfigs
};
Turns out that the Capacitor CLI always compiles capacitor.config.ts
as CommonJS: https://github.com/ionic-team/capacitor/blob/main/cli/src/util/node.ts#L12-L50.