UNPKG

1.71 kBJavaScriptView Raw
1const { globToRegexp, serverRequire } = require('@storybook/core/common');
2const path = require('path');
3const fs = require('fs');
4
5const cwd = process.cwd();
6
7const toRequireContext = (specifier) => {
8 const { directory, files } = specifier;
9
10 // The importPathMatcher is a `./`-prefixed matcher that includes the directory
11 // For `require.context()` we want the same thing, relative to directory
12 const match = globToRegexp(`./${files}`);
13
14 return {
15 path: directory,
16 recursive: files.includes('**') || files.split('/').length > 1,
17 match,
18 };
19};
20
21function requireUncached(module) {
22 delete require.cache[require.resolve(module)];
23
24 return serverRequire(module);
25}
26
27const supportedExtensions = ['js', 'jsx', 'ts', 'tsx', 'cjs', 'mjs'];
28
29function getFilePathExtension({ configPath }, fileName) {
30 for (const ext of supportedExtensions) {
31 const filePath = path.resolve(cwd, configPath, `${fileName}.${ext}`);
32
33 if (fs.existsSync(filePath)) {
34 return ext;
35 }
36 }
37
38 return null;
39}
40
41function getMain({ configPath }) {
42 const fileExtension = getFilePathExtension({ configPath }, 'main');
43
44 if (fileExtension === null) {
45 throw new Error('main config file not found');
46 }
47
48 const mainPath = path.resolve(cwd, configPath, `main.${fileExtension}`);
49
50 return requireUncached(mainPath);
51}
52
53function ensureRelativePathHasDot(relativePath) {
54 return relativePath.startsWith('.') ? relativePath : `./${relativePath}`;
55}
56
57function getPreviewExists({ configPath }) {
58 return !!getFilePathExtension({ configPath }, 'preview');
59}
60
61module.exports = {
62 toRequireContext,
63 requireUncached,
64 getFilePathExtension,
65 getMain,
66 ensureRelativePathHasDot,
67 getPreviewExists,
68};