|
| 1 | +import fs from 'fs/promises'; |
1 | 2 | import path from 'path'; |
2 | 3 |
|
3 | | -const nodeModulesPath = path.join( |
4 | | - process.env.PWD || process.cwd(), |
5 | | - 'node_modules', |
6 | | - '@commitlint', |
7 | | - 'load' |
8 | | -); |
| 4 | +const getCommitLintModuleType = async (): Promise<'cjs' | 'esm'> => { |
| 5 | + const packageFile = 'node_modules/@commitlint/load/package.json'; |
| 6 | + const packageJsonPath = path.join( |
| 7 | + process.env.PWD || process.cwd(), |
| 8 | + packageFile, |
| 9 | + ); |
| 10 | + const packageJson = JSON.parse(await fs.readFile(packageJsonPath, 'utf8')); |
| 11 | + if (!packageJson) { |
| 12 | + throw new Error(`Failed to parse ${packageFile}`); |
| 13 | + } |
| 14 | + |
| 15 | + return packageJson.type === 'module' ? 'esm' : 'cjs'; |
| 16 | +}; |
| 17 | + |
| 18 | +/** |
| 19 | + * QualifiedConfig from any version of @commitlint/types |
| 20 | + * @see https://github.com/conventional-changelog/commitlint/blob/master/@commitlint/types/src/load.ts |
| 21 | + */ |
| 22 | +type QualifiedConfigOnAnyVersion = { [key:string]: unknown }; |
9 | 23 |
|
10 | 24 | /** |
11 | 25 | * This code is loading the configuration for the `@commitlint` package from the current working |
12 | 26 | * directory (`process.env.PWD`) by requiring the `load` module from the `@commitlint` package. |
13 | 27 | * |
14 | 28 | * @returns |
15 | 29 | */ |
16 | | -export const getCommitLintPWDConfig = async () => { |
17 | | - const load = require(nodeModulesPath).default; |
| 30 | +export const getCommitLintPWDConfig = async (): Promise<QualifiedConfigOnAnyVersion | null> => { |
| 31 | + let load, nodeModulesPath; |
| 32 | + switch (await getCommitLintModuleType()) { |
| 33 | + case 'cjs': |
| 34 | + /** |
| 35 | + * CommonJS (<= commitlint@v18.x.x.) |
| 36 | + */ |
| 37 | + nodeModulesPath = path.join( |
| 38 | + process.env.PWD || process.cwd(), |
| 39 | + 'node_modules/@commitlint/load', |
| 40 | + ); |
| 41 | + load = require(nodeModulesPath).default; |
| 42 | + break; |
| 43 | + case 'esm': |
| 44 | + /** |
| 45 | + * ES Module (commitlint@v19.x.x. <= ) |
| 46 | + * Directory import is not supported in ES Module resolution, so import the file directly |
| 47 | + */ |
| 48 | + nodeModulesPath = path.join( |
| 49 | + process.env.PWD || process.cwd(), |
| 50 | + 'node_modules/@commitlint/load/lib/load.js', |
| 51 | + ); |
| 52 | + load = (await import(nodeModulesPath)).default; |
| 53 | + break; |
| 54 | + } |
18 | 55 |
|
19 | 56 | if (load && typeof load === 'function') { |
20 | 57 | return await load(); |
|
0 commit comments