Skip to content

bug: capacitor.config.ts cannot support top-level await #6961

Open
@oliveryasuna

Description

@oliveryasuna

Bug Report

Capacitor Version

💊   Capacitor Doctor  💊 

Latest Dependencies:

  @capacitor/cli: 5.4.2
  @capacitor/core: 5.4.2
  @capacitor/android: 5.4.2
  @capacitor/ios: 5.4.2

Installed Dependencies:

  @capacitor/cli: 5.4.2
  @capacitor/core: 5.4.2
  @capacitor/android: 5.4.2
  @capacitor/ios: 5.4.2

[success] iOS looking great! 👌

Current Behavior

I was not sure if I should report this as a bug or feature. I consider it a bug, but a fix would most likely introduce a new feature.

See the Code Reproduction. It is impossible to use top-level await statements in capacitor.config.ts. This is due to https://github.com/ionic-team/capacitor/blob/main/cli/src/util/node.ts#L12-L50. The module is always loaded as a CommonJS module, which does not support top-level await statements.

You may think that you could make the whole module asynchronous:

// capacitor.config.ts

export default new Promise((resolve, reject) => {
  // ...
});

but Capacitor does not handle this.

Expected Behavior

Capacitor should not limit developers to write a CommonJS-compliant capacitor.config.ts. It is a mobile framework, not a JS one. Thus, in my opinion, it can be mobile-opinionated, but not JS opinionated.

I propose two solutions:

  1. Instead of the DIY compiler found on https://github.com/ionic-team/capacitor/blob/main/cli/src/util/node.ts#L12-L50, Capacitor could use a configuration loader. https://github.com/cosmiconfig/cosmiconfig would be a top choice. This would also enable developers to write their Capacitor configurations in whatever format they so chose.
  2. Somehow allow the developer to specify the module type when importing capacitor.config.ts. Perhaps use a predefined TSConfig file, such as tsconfig.capacitor.json. Better if the code allows developers to specify the file, though.

Code Reproduction

https://github.com/oliveryasuna/capacitor-config-bug

Try running cap add ios, for example.

Here's a config that would cause problems.

// capacitor.config.ts

const myFunc = (async(): Promise<void> => {
});

await myFunc();

return {};

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions