junobuild / cli

The Juno command-line interface
MIT License
2 stars 2 forks source link

Detect type of configuration to on juno init #117

Closed peterpeterparker closed 3 months ago

peterpeterparker commented 6 months ago

If package.json contains TypeScript => juno.config.ts Else, if package.json type module => juno.config.js Else, choice

peterpeterparker commented 3 months ago

It has been resolved for some time

export const detectJunoConfigType = ({
  filename
}: {
  filename: ConfigFilename;
}): ConfigFile | undefined => {
  const tsconfig = join(process.cwd(), 'tsconfig.json');

  if (existsSync(tsconfig)) {
    const junoTs = ts(filename);

    return {
      configPath: junoTs,
      configType: 'ts'
    };
  }

  try {
    const packageJsonPath = join(process.cwd(), 'package.json');

    if (existsSync(packageJsonPath)) {
      type PackageJson = {
        dependencies?: Record<string, string>;
        devDependencies?: Record<string, string>;
        type?: string;
      };

      const packageJson: PackageJson = JSON.parse(readFileSync(packageJsonPath, 'utf8'));

      if (
        'typescript' in (packageJson.dependencies ?? {}) ||
        'typescript' in (packageJson.devDependencies ?? {})
      ) {
        const junoTs = ts(filename);

        return {
          configPath: junoTs,
          configType: 'ts'
        };
      }

      if (packageJson.type === 'module') {
        const junoMjs = mjs(filename);

        return {
          configPath: junoMjs,
          configType: 'js'
        };
      }
    }
  } catch (_error: unknown) {
    // We ignore the error as returning undefined will lead the CLI to ask the user what type of configuration type should be used.
  }

  return undefined;
};