/
cra-config.ts
199 lines (163 loc) · 6.54 KB
/
cra-config.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
import fs from 'fs';
import path from 'path';
import semver from 'semver';
import { Configuration, Plugin, RuleSetRule } from 'webpack';
// import MiniCssExtractPlugin from 'mini-css-extract-plugin';
import { normalizeCondition } from 'webpack/lib/RuleSet';
import { logger } from '@storybook/node-logger';
const appDirectory = fs.realpathSync(process.cwd());
const cssExtensions = ['.css', '.scss', '.sass'];
const cssModuleExtensions = ['.module.css', '.module.scss', '.module.sass'];
const typeScriptExtensions = ['.ts', '.tsx'];
let reactScriptsPath: string;
export function getReactScriptsPath({ noCache }: { noCache?: boolean } = {}) {
if (reactScriptsPath && !noCache) return reactScriptsPath;
let reactScriptsScriptPath = fs.realpathSync(
path.join(appDirectory, '/node_modules/.bin/react-scripts')
);
try {
// Note: Since there is no symlink for .bin/react-scripts on Windows
// we'll parse react-scripts file to find actual package path.
// This is important if you use fork of CRA.
const pathIsNotResolved = /node_modules[\\/]\.bin[\\/]react-scripts/i.test(
reactScriptsScriptPath
);
if (pathIsNotResolved) {
const content = fs.readFileSync(reactScriptsScriptPath, 'utf8');
const packagePathMatch = content.match(
/"\$basedir[\\/]([^\s]+?[\\/]bin[\\/]react-scripts\.js")/i
);
if (packagePathMatch && packagePathMatch.length > 1) {
reactScriptsScriptPath = path.join(
appDirectory,
'/node_modules/.bin/',
packagePathMatch[1]
);
}
}
} catch (e) {
logger.warn(`Error occurred during react-scripts package path resolving: ${e}`);
}
reactScriptsPath = path.join(reactScriptsScriptPath, '../..');
const scriptsPkgJson = path.join(reactScriptsPath, 'package.json');
if (!fs.existsSync(scriptsPkgJson)) {
reactScriptsPath = 'react-scripts';
}
return reactScriptsPath;
}
export function isReactScriptsInstalled(requiredVersion = '2.0.0') {
try {
// eslint-disable-next-line import/no-dynamic-require,global-require
const reactScriptsJson = require(path.join(getReactScriptsPath(), 'package.json'));
return !semver.gtr(requiredVersion, reactScriptsJson.version);
} catch (e) {
return false;
}
}
export const getRules = (extensions: string[]) => (rules: RuleSetRule[]) =>
rules.reduce((craRules, rule) => {
// If at least one extension satisfies the rule test, the rule is one
// we want to extract
if (rule.test && extensions.some(normalizeCondition(rule.test))) {
// If the base test is for extensions, return early
return craRules.concat(rule);
}
// Get any rules contained in rule.oneOf
if (!rule.test && rule.oneOf) {
craRules.push(...getRules(extensions)(rule.oneOf));
}
// Get any rules contained in rule.rules
if (!rule.test && rule.rules) {
craRules.push(...getRules(extensions)(rule.rules));
}
return craRules;
}, [] as RuleSetRule[]);
const getStyleRules = getRules(cssExtensions.concat(cssModuleExtensions));
export const getTypeScriptRules = (webpackConfigRules: RuleSetRule[], configDir: string) => {
const rules = getRules(typeScriptExtensions)(webpackConfigRules);
// Adds support for using TypeScript in the `.storybook` (or config) folder.
return rules.reduce((accRules, rule) => {
// Resolves an issue where this config is parsed twice (#4903).
if (typeof rule.include !== 'string') {
return [...accRules, rule];
}
return [
...accRules,
{
...rule,
include: [rule.include, path.resolve(configDir)],
},
];
}, [] as RuleSetRule[]);
};
function mergePlugins(basePlugins: Plugin[], additionalPlugins: Plugin[]) {
return [...basePlugins, ...additionalPlugins].reduce((plugins, plugin) => {
if (
plugins.some(includedPlugin => includedPlugin.constructor.name === plugin.constructor.name)
) {
return plugins;
}
return [...plugins, plugin];
}, []);
}
export function getCraWebpackConfig(mode: 'development' | 'production' | 'none') {
const pathToReactScripts = getReactScriptsPath();
const craWebpackConfig =
mode === 'production' ? 'config/webpack.config.prod.js' : 'config/webpack.config.dev.js';
let pathToWebpackConfig = path.join(pathToReactScripts, craWebpackConfig);
if (!fs.existsSync(pathToWebpackConfig)) {
pathToWebpackConfig = path.join(pathToReactScripts, 'config/webpack.config.js');
}
// eslint-disable-next-line import/no-dynamic-require,global-require
const webpackConfig = require(pathToWebpackConfig);
if (typeof webpackConfig === 'function') {
return webpackConfig(mode);
}
return webpackConfig;
}
export function applyCRAWebpackConfig(baseConfig: Configuration, configDir: string): Configuration {
// Check if the user can use TypeScript (react-scripts version 2.1+).
const hasTsSupport = isReactScriptsInstalled('2.1.0');
const tsExtensions = hasTsSupport ? typeScriptExtensions : [];
const extensions = [...cssExtensions, ...tsExtensions];
// Remove any rules from baseConfig that test true for any one of the extensions
const filteredBaseRules = baseConfig.module.rules.filter(
rule => !rule.test || !extensions.some(normalizeCondition(rule.test))
);
// Load create-react-app config
const craWebpackConfig = getCraWebpackConfig(baseConfig.mode);
const craStyleRules = getStyleRules(craWebpackConfig.module.rules);
const craTypeScriptRules = hasTsSupport
? getTypeScriptRules(craWebpackConfig.module.rules, configDir)
: [];
// I disabled the MiniCssExtractPlugin, because there's often a version mismatch between CRA & storybook
// causing a lot of issues of the build-storybook failing
// Add css minification for production
const plugins = [...baseConfig.plugins];
// if (baseConfig.mode === 'production') {
// // @ts-ignore
// plugins.push(new MiniCssExtractPlugin());
// }
return {
...baseConfig,
module: {
...baseConfig.module,
rules: [...filteredBaseRules, ...craStyleRules, ...craTypeScriptRules],
},
plugins: mergePlugins(plugins, hasTsSupport ? craWebpackConfig.plugins : []),
resolve: {
...baseConfig.resolve,
extensions: [...baseConfig.resolve.extensions, ...tsExtensions],
modules: Array.from(
new Set([...baseConfig.resolve.modules, ...(craWebpackConfig.resolve.modules || [])])
),
alias: {
...baseConfig.resolve.alias,
...craWebpackConfig.resolve.alias,
},
},
resolveLoader: {
modules: ['node_modules', path.join(getReactScriptsPath(), 'node_modules')],
},
};
}