1
- import { relative , resolve } from 'node:path' ;
1
+ import { readFile , rm , writeFile } from 'node:fs/promises' ;
2
+ import { join , parse , relative , resolve } from 'node:path' ;
2
3
4
+ import { logger } from 'storybook/internal/node-logger' ;
3
5
import { MainFileEvaluationError } from 'storybook/internal/server-errors' ;
4
6
import type { StorybookConfig } from 'storybook/internal/types' ;
5
7
8
+ import { dedent } from 'ts-dedent' ;
9
+
6
10
import { importModule } from '../../shared/utils/module' ;
7
11
import { getInterpretedFile } from './interpret-files' ;
8
12
import { validateConfigurationFiles } from './validate-configuration-files' ;
@@ -25,6 +29,37 @@ export async function loadMainConfig({
25
29
if ( ! ( e instanceof Error ) ) {
26
30
throw e ;
27
31
}
32
+ if ( e . message . includes ( 'require is not defined' ) ) {
33
+ logger . info (
34
+ 'Loading main config failed, trying a temporary fix, Please ensure the main config is valid ESM'
35
+ ) ;
36
+ const comment =
37
+ '// end of Storybook 10 migration assistant header, you can delete the above code' ;
38
+ const content = await readFile ( mainPath , 'utf-8' ) ;
39
+
40
+ if ( ! content . includes ( comment ) ) {
41
+ const header = dedent `
42
+ import { createRequire } from "node:module";
43
+ import { dirname } from "node:path";
44
+ import { fileURLToPath } from "node:url";
45
+
46
+ const __filename = fileURLToPath(import.meta.url);
47
+ const __dirname = dirname(__filename);
48
+ const require = createRequire(import.meta.url);
49
+ ` ;
50
+
51
+ const { ext, name, dir } = parse ( mainPath ) ;
52
+ const modifiedMainPath = join ( dir , `${ name } .tmp.${ ext } ` ) ;
53
+ await writeFile ( modifiedMainPath , [ header , comment , content ] . join ( '\n\n' ) ) ;
54
+ let out ;
55
+ try {
56
+ out = await importModule ( modifiedMainPath ) ;
57
+ } finally {
58
+ await rm ( modifiedMainPath ) ;
59
+ }
60
+ return out ;
61
+ }
62
+ }
28
63
29
64
throw new MainFileEvaluationError ( {
30
65
location : relative ( process . cwd ( ) , mainPath ) ,
0 commit comments