/
index.ts
220 lines (202 loc) · 6.97 KB
/
index.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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
import {
ExecutorContext,
joinPathFragments,
logger,
ProjectGraph,
readJsonFile,
readNxJson,
TargetConfiguration,
workspaceRoot,
} from '@nrwl/devkit';
import { getBaseWebpackPartial } from '@nrwl/webpack/src/utils/config';
import { NormalizedWebpackExecutorOptions } from '@nrwl/webpack/src/executors/webpack/schema';
import { getStylesPartial } from '@nrwl/webpack/src/executors/webpack/lib/get-webpack-config';
import { checkAndCleanWithSemver } from '@nrwl/workspace/src/utilities/version-utils';
import { join } from 'path';
import { gte } from 'semver';
import { Configuration, DefinePlugin, WebpackPluginInstance } from 'webpack';
import * as mergeWebpack from 'webpack-merge';
import { mergePlugins } from './merge-plugins';
import { readProjectsConfigurationFromProjectGraph } from 'nx/src/project-graph/project-graph';
const reactWebpackConfig = require('../webpack');
// This is shamelessly taken from CRA and modified for NX use
// https://github.com/facebook/create-react-app/blob/4784997f0682e75eb32a897b4ffe34d735912e6c/packages/react-scripts/config/env.js#L71
function getClientEnvironment(mode) {
// Grab NODE_ENV and NX_* and STORYBOOK_* environment variables and prepare them to be
// injected into the application via DefinePlugin in webpack configuration.
const NX_PREFIX = /^NX_/i;
const STORYBOOK_PREFIX = /^STORYBOOK_/i;
const raw = Object.keys(process.env)
.filter((key) => NX_PREFIX.test(key) || STORYBOOK_PREFIX.test(key))
.reduce(
(env, key) => {
env[key] = process.env[key];
return env;
},
{
// Useful for determining whether we’re running in production mode.
NODE_ENV: process.env.NODE_ENV || mode,
// Environment variables for Storybook
// https://github.com/storybookjs/storybook/blob/bdf9e5ed854b8d34e737eee1a4a05add88265e92/lib/core-common/src/utils/envs.ts#L12-L21
NODE_PATH: process.env.NODE_PATH || '',
STORYBOOK: process.env.STORYBOOK || 'true',
// This is to support CRA's public folder feature.
// In production we set this to dot(.) to allow the browser to access these assets
// even when deployed inside a subpath. (like in GitHub pages)
// In development this is just empty as we always serves from the root.
PUBLIC_URL: mode === 'production' ? '.' : '',
}
);
// Stringify all values so we can feed into webpack DefinePlugin
const stringified = {
'process.env': Object.keys(raw).reduce((env, key) => {
env[key] = JSON.stringify(raw[key]);
return env;
}, {}),
};
return { stringified };
}
export const babelDefault = (): Record<
string,
// eslint-disable-next-line @typescript-eslint/ban-types
(string | [string, object])[]
> => {
// Add babel plugin for styled-components or emotion.
// We don't have a good way to know when a project uses one or the other, so
// add the plugin only if the other style package isn't used.
const packageJson = readJsonFile(join(workspaceRoot, 'package.json'));
const deps = { ...packageJson.dependencies, ...packageJson.devDependencies };
const hasStyledComponents = !!deps['styled-components'];
const plugins = [];
if (hasStyledComponents) {
plugins.push(['styled-components', { ssr: false }]);
}
return {
presets: [],
plugins: [...plugins],
};
};
export const core = (prev, options) => ({
...prev,
disableWebpackDefaults: true,
});
export const webpack = async (
storybookWebpackConfig: Configuration = {},
options: any
): Promise<Configuration> => {
logger.info(
'=> Loading Nrwl React Storybook preset from "@nrwl/react/plugins/storybook"'
);
const tsconfigPath = join(options.configDir, 'tsconfig.json');
const builderOptions: NormalizedWebpackExecutorOptions = {
...options,
root: options.configDir,
sourceRoot: '',
fileReplacements: [],
sourceMap: {
hidden: false,
scripts: true,
styles: true,
vendors: false,
},
styles: [],
optimization: {},
tsConfig: tsconfigPath,
extractCss: storybookWebpackConfig.mode === 'production',
target: 'web',
};
const esm = true;
const isScriptOptimizeOn = storybookWebpackConfig.mode !== 'development';
const extractCss = storybookWebpackConfig.mode === 'production';
// ESM build for modern browsers.
const baseWebpackConfig = mergeWebpack.merge([
getBaseWebpackPartial(builderOptions, {
esm,
isScriptOptimizeOn,
skipTypeCheck: true,
}),
getStylesPartial(
options.workspaceRoot,
options.configDir,
builderOptions,
extractCss
),
]);
// run it through the React customizations
const finalConfig = reactWebpackConfig(baseWebpackConfig);
// Check whether the project .babelrc uses @emotion/babel-plugin. There's currently
// a Storybook issue (https://github.com/storybookjs/storybook/issues/13277) which apparently
// doesn't work with `@emotion/*` >= v11
// this is a workaround to fix that
let resolvedEmotionAliases = {};
const packageJson = readJsonFile(join(workspaceRoot, 'package.json'));
const deps = { ...packageJson.dependencies, ...packageJson.devDependencies };
const emotionReactVersion = deps['@emotion/react'];
if (
emotionReactVersion &&
gte(
checkAndCleanWithSemver('@emotion/react', emotionReactVersion),
'11.0.0'
)
) {
try {
const babelrc = readJsonFile(
options.babelrcPath ||
joinPathFragments(options.configDir, '../', '.babelrc')
);
if (babelrc?.plugins?.includes('@emotion/babel-plugin')) {
resolvedEmotionAliases = {
resolve: {
alias: {
'@emotion/core': joinPathFragments(
workspaceRoot,
'node_modules',
'@emotion/react'
),
'@emotion/styled': joinPathFragments(
workspaceRoot,
'node_modules',
'@emotion/styled'
),
'emotion-theming': joinPathFragments(
workspaceRoot,
'node_modules',
'@emotion/react'
),
},
},
};
}
} catch (error) {
// silently ignore if the .babelrc doesn't exist
}
}
return mergeWebpack.merge(
{
...storybookWebpackConfig,
module: {
...storybookWebpackConfig.module,
rules: [
...storybookWebpackConfig.module.rules,
...finalConfig.module.rules,
],
},
resolve: {
...storybookWebpackConfig.resolve,
plugins: mergePlugins(
...((storybookWebpackConfig.resolve.plugins ??
[]) as unknown as WebpackPluginInstance[]),
...(finalConfig.resolve.plugins ?? [])
),
},
plugins: mergePlugins(
new DefinePlugin(
getClientEnvironment(storybookWebpackConfig.mode).stringified
),
...(storybookWebpackConfig.plugins ?? []),
...(finalConfig.plugins ?? [])
),
},
resolvedEmotionAliases
);
};