/
iframe-webpack.config.ts
230 lines (220 loc) · 7.24 KB
/
iframe-webpack.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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
import path from 'path';
import fse from 'fs-extra';
import { Configuration, DefinePlugin, HotModuleReplacementPlugin, ProgressPlugin } from 'webpack';
import Dotenv from 'dotenv-webpack';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import CaseSensitivePathsPlugin from 'case-sensitive-paths-webpack-plugin';
import WatchMissingNodeModulesPlugin from 'react-dev-utils/WatchMissingNodeModulesPlugin';
import TerserWebpackPlugin from 'terser-webpack-plugin';
import VirtualModulePlugin from 'webpack-virtual-modules';
import ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin';
import themingPaths from '@storybook/theming/paths';
import {
toRequireContextString,
es6Transpiler,
stringifyEnvs,
nodeModulesPaths,
interpolate,
Options,
hasDotenv,
} from '@storybook/core-common';
import { createBabelLoader } from './babel-loader-preview';
import { useBaseTsSupport } from './useBaseTsSupport';
const storybookPaths: Record<string, string> = [
'addons',
'api',
'channels',
'channel-postmessage',
'components',
'core-events',
'router',
'theming',
'semver',
'client-api',
'client-logger',
].reduce(
(acc, sbPackage) => ({
...acc,
[`@storybook/${sbPackage}`]: path.dirname(
require.resolve(`@storybook/${sbPackage}/package.json`)
),
}),
{}
);
export default async ({
configDir,
babelOptions,
entries,
stories,
outputDir = path.join('.', 'public'),
quiet,
packageJson,
configType,
framework,
frameworkPath,
presets,
typescriptOptions,
modern,
}: Options & Record<string, any>): Promise<Configuration> => {
const envs = await presets.apply<Record<string, string>>('env');
const logLevel = await presets.apply('logLevel', undefined);
const frameworkOptions = await presets.apply(`${framework}Options`, {});
const headHtmlSnippet = await presets.apply('previewHead');
const bodyHtmlSnippet = await presets.apply('previewBody');
const template = await presets.apply<string>('previewMainTemplate');
const babelLoader = createBabelLoader(babelOptions, framework);
const isProd = configType === 'PRODUCTION';
// TODO FIX ME - does this need to be ESM?
const entryTemplate = await fse.readFile(path.join(__dirname, 'virtualModuleEntry.template.js'), {
encoding: 'utf8',
});
const storyTemplate = await fse.readFile(path.join(__dirname, 'virtualModuleStory.template.js'), {
encoding: 'utf8',
});
const frameworkInitEntry = path.resolve(
path.join(configDir, 'storybook-init-framework-entry.js')
);
// Allows for custom frameworks that are not published under the @storybook namespace
const frameworkImportPath = frameworkPath || `@storybook/${framework}`;
const virtualModuleMapping = {
// Ensure that the client API is initialized by the framework before any other iframe code
// is loaded. That way our client-apis can assume the existence of the API+store
[frameworkInitEntry]: `import '${frameworkImportPath}';`,
};
entries.forEach((entryFilename: any) => {
const match = entryFilename.match(/(.*)-generated-(config|other)-entry.js$/);
if (match) {
const configFilename = match[1];
const clientApi = storybookPaths['@storybook/client-api'];
const clientLogger = storybookPaths['@storybook/client-logger'];
virtualModuleMapping[entryFilename] = interpolate(entryTemplate, {
configFilename,
clientApi,
clientLogger,
});
}
});
if (stories) {
const storiesFilename = path.resolve(path.join(configDir, `generated-stories-entry.js`));
virtualModuleMapping[storiesFilename] = interpolate(storyTemplate, { frameworkImportPath })
// Make sure we also replace quotes for this one
.replace("'{{stories}}'", stories.map(toRequireContextString).join(','));
}
const shouldCheckTs = useBaseTsSupport(framework) && typescriptOptions.check;
const tsCheckOptions = typescriptOptions.checkOptions || {};
return {
name: 'preview',
mode: isProd ? 'production' : 'development',
bail: isProd,
devtool: 'cheap-module-source-map',
entry: entries,
output: {
path: path.resolve(process.cwd(), outputDir),
filename: isProd ? '[name].[contenthash:8].iframe.bundle.js' : '[name].iframe.bundle.js',
publicPath: '',
},
stats: {
preset: 'none',
logging: 'error',
},
watchOptions: {
aggregateTimeout: 10,
ignored: /node_modules/,
},
ignoreWarnings: [
{
message: /export '\S+' was not found in 'global'/,
},
],
plugins: [
Object.keys(virtualModuleMapping).length > 0
? new VirtualModulePlugin(virtualModuleMapping)
: (null as any),
new HtmlWebpackPlugin({
filename: `iframe.html`,
// FIXME: `none` isn't a known option
chunksSortMode: 'none' as any,
alwaysWriteToDisk: true,
inject: false,
templateParameters: (compilation, files, options) => ({
compilation,
files,
options,
version: packageJson.version,
globals: {
LOGLEVEL: logLevel,
FRAMEWORK_OPTIONS: frameworkOptions,
},
headHtmlSnippet,
bodyHtmlSnippet,
}),
minify: {
collapseWhitespace: true,
removeComments: true,
removeRedundantAttributes: true,
removeScriptTypeAttributes: false,
removeStyleLinkTypeAttributes: true,
useShortDoctype: true,
},
template,
}),
new DefinePlugin({
'process.env': stringifyEnvs(envs),
NODE_ENV: JSON.stringify(process.env.NODE_ENV),
}),
isProd ? null : new WatchMissingNodeModulesPlugin(nodeModulesPaths),
isProd ? null : new HotModuleReplacementPlugin(),
new CaseSensitivePathsPlugin(),
quiet ? null : new ProgressPlugin({}),
hasDotenv() ? new Dotenv({ silent: true }) : null,
shouldCheckTs ? new ForkTsCheckerWebpackPlugin(tsCheckOptions) : null,
].filter(Boolean),
module: {
rules: [
babelLoader,
es6Transpiler() as any,
{
test: /\.md$/,
type: 'asset/source',
},
],
},
resolve: {
extensions: ['.mjs', '.js', '.jsx', '.ts', '.tsx', '.json', '.cjs'],
modules: ['node_modules'].concat(envs.NODE_PATH || []),
mainFields: [modern ? 'sbmodern' : null, 'browser', 'module', 'main'].filter(Boolean),
alias: {
...themingPaths,
...storybookPaths,
react: path.dirname(require.resolve('react/package.json')),
'react-dom': path.dirname(require.resolve('react-dom/package.json')),
},
fallback: { path: false },
},
optimization: {
splitChunks: {
chunks: 'all',
},
runtimeChunk: true,
sideEffects: true,
usedExports: true,
minimizer: isProd
? [
new TerserWebpackPlugin({
parallel: true,
terserOptions: {
sourceMap: true,
mangle: false,
keep_fnames: true,
},
// It looks like the types from `@types/terser-webpack-plugin` are not matching the latest version of
// Webpack yet
}) as any,
]
: [],
},
performance: {
hints: isProd ? 'warning' : false,
},
};
};