forked from codesandbox/codesandbox-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebpack.common.js
More file actions
574 lines (550 loc) · 18.2 KB
/
webpack.common.js
File metadata and controls
574 lines (550 loc) · 18.2 KB
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
/* eslint-disable global-require */
const webpack = require('webpack');
const path = require('path');
const fs = require('fs');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
const threadLoader = require('thread-loader');
const env = require('@codesandbox/common/lib/config/env');
const getHost = require('@codesandbox/common/lib/utils/host');
const postcssNormalize = require('postcss-normalize');
const WatchMissingNodeModulesPlugin = require('../scripts/utils/WatchMissingNodeModulesPlugin');
const paths = require('./paths');
const babelDev = require('./babel.dev');
const babelProd = require('./babel.prod');
const NODE_ENV = JSON.parse(env.default['process.env.NODE_ENV']);
const SANDBOX_ONLY = !!process.env.SANDBOX_ONLY;
const __DEV__ = NODE_ENV === 'development'; // eslint-disable-line no-underscore-dangle
const __PROD__ = NODE_ENV === 'production'; // eslint-disable-line no-underscore-dangle
// const __TEST__ = NODE_ENV === 'test'; // eslint-disable-line no-underscore-dangle
const babelConfig = __DEV__ && !SANDBOX_ONLY ? babelDev : babelProd;
const publicPath = SANDBOX_ONLY || __DEV__ ? '/' : getHost.default() + '/';
const isLint = 'LINT' in process.env;
// common function to get style loaders
const getStyleLoaders = (cssOptions, preProcessor) => {
const loaders = [
__DEV__ && require.resolve('style-loader'),
__PROD__ && {
loader: MiniCssExtractPlugin.loader,
options: {},
},
{
loader: require.resolve('css-loader'),
options: cssOptions,
},
{
// Options for PostCSS as we reference these options twice
// Adds vendor prefixing based on your specified browser support in
// package.json
loader: require.resolve('postcss-loader'),
options: {
// Necessary for external CSS imports to work
// https://github.com/facebook/create-react-app/issues/2677
ident: 'postcss',
plugins: () => [
require('postcss-flexbugs-fixes'),
require('postcss-preset-env')({
autoprefixer: {
flexbox: 'no-2009',
},
stage: 3,
}),
// Adds PostCSS Normalize as the reset css with default options,
// so that it honors browserslist config in package.json
// which in turn let's users customize the target behavior as per their needs.
postcssNormalize(),
],
sourceMap: __PROD__,
},
},
].filter(Boolean);
if (preProcessor) {
loaders.push(
{
loader: require.resolve('resolve-url-loader'),
options: {
sourceMap: __PROD__,
},
},
{
loader: require.resolve(preProcessor),
options: {
sourceMap: true,
},
}
);
}
return loaders;
};
// Shim for `eslint-plugin-vue/lib/index.js`
const ESLINT_PLUGIN_VUE_INDEX = `module.exports = {
rules: {${fs
.readdirSync(
path.join(
__dirname,
'..',
'..',
'..',
'node_modules',
'eslint-plugin-vue',
'lib',
'rules'
)
)
.filter(filename => path.extname(filename) === '.js')
.map(filename => {
const ruleId = path.basename(filename, '.js');
return ` "${ruleId}": require("eslint-plugin-vue/lib/rules/${filename}"),`;
})
.join('\n')}
},
processors: {
".vue": require("eslint-plugin-vue/lib/processor")
}
}`;
const sepRe = `\\${path.sep}`; // path separator regex
const threadPoolConfig = {
workers: 2,
};
if (!isLint) {
threadLoader.warmup(threadPoolConfig, ['babel-loader']);
}
module.exports = {
entry: SANDBOX_ONLY
? {
sandbox: [
require.resolve('./polyfills'),
path.join(paths.sandboxSrc, 'index.js'),
],
'sandbox-startup': path.join(paths.sandboxSrc, 'startup.js'),
}
: {
app: [
require.resolve('./polyfills'),
path.join(paths.appSrc, 'index.js'),
],
sandbox: [
require.resolve('./polyfills'),
path.join(paths.sandboxSrc, 'index.js'),
],
'sandbox-startup': path.join(paths.sandboxSrc, 'startup.js'),
embed: [
require.resolve('./polyfills'),
path.join(paths.embedSrc, 'index.js'),
],
},
target: 'web',
mode: 'development',
node: {
setImmediate: false,
module: 'empty',
child_process: 'empty',
},
output: {
path: paths.appBuild,
publicPath,
globalObject: 'this',
jsonpFunction: 'csbJsonP', // So we don't conflict with webpack generated libraries in the sandbox
pathinfo: false,
futureEmitAssets: true,
},
module: {
rules: [
{
test: /\.(graphql|gql)$/,
exclude: /node_modules/,
loader: `graphql-tag/loader`,
},
{
test: /\.wasm$/,
loader: 'file-loader',
type: 'javascript/auto',
},
{
test: /\.scss$/,
use: getStyleLoaders(
{
importLoaders: 2,
sourceMap: true,
},
'sass-loader'
),
// Don't consider CSS imports dead code even if the
// containing package claims to have no side effects.
// Remove this when webpack adds a warning or an error for this.
// See https://github.com/webpack/webpack/issues/6571
sideEffects: true,
},
// Transpile node dependencies, node deps are often not transpiled for IE11
{
test: [
new RegExp(`${sepRe}node_modules${sepRe}.*ansi-styles`),
new RegExp(`${sepRe}node_modules${sepRe}.*chalk`),
new RegExp(`${sepRe}node_modules${sepRe}.*jest`),
new RegExp(`${sepRe}node_modules${sepRe}.*monaco-textmate`),
new RegExp(`${sepRe}node_modules${sepRe}.*onigasm`),
new RegExp(`react-icons`),
new RegExp(`${sepRe}node_modules${sepRe}.*gsap`),
new RegExp(`${sepRe}node_modules${sepRe}.*babel-plugin-macros`),
new RegExp(`sandbox-hooks`),
new RegExp(
`${sepRe}node_modules${sepRe}vue-template-es2015-compiler`
),
new RegExp(
`${sepRe}node_modules${sepRe}babel-plugin-transform-vue-jsx`
),
],
loader: 'babel-loader',
query: {
presets: [
'@babel/preset-flow',
[
'@babel/preset-env',
{
targets: {
ie: 11,
esmodules: true,
},
modules: 'umd',
useBuiltIns: false,
},
],
'@babel/preset-react',
],
plugins: [
'@babel/plugin-transform-template-literals',
'@babel/plugin-transform-destructuring',
'@babel/plugin-transform-async-to-generator',
'@babel/plugin-proposal-object-rest-spread',
'@babel/plugin-proposal-class-properties',
'@babel/plugin-transform-runtime',
],
},
},
{
test: /\.(j|t)sx?$/,
include: [paths.src, /@emmetio/],
exclude: [
/eslint\.4\.1\.0\.min\.js$/,
/typescriptServices\.js$/,
/\.no-webpack\./,
],
use: [
!isLint
? {
loader: 'thread-loader',
options: threadPoolConfig,
}
: false,
{
loader: 'babel-loader',
options: babelConfig,
},
].filter(Boolean),
},
// `eslint-plugin-vue/lib/index.js` depends on `fs` module we cannot use in browsers, so needs shimming.
{
test: new RegExp(`eslint-plugin-vue${sepRe}lib${sepRe}index\\.js$`),
loader: 'string-replace-loader',
options: {
search: '[\\s\\S]+', // whole file.
replace: ESLINT_PLUGIN_VUE_INDEX,
flags: 'g',
},
},
// `eslint` has some dynamic `require(...)`.
// Delete those.
{
test: new RegExp(`eslint${sepRe}lib${sepRe}(?:linter|rules)\\.js$`),
loader: 'string-replace-loader',
options: {
search: '(?:\\|\\||(\\())\\s*require\\(.+?\\)',
replace: '$1',
flags: 'g',
},
},
// `vue-eslint-parser` has `require(parserOptions.parser || "espree")`.
// Modify it by a static importing.
{
test: /vue-eslint-parser/,
loader: 'string-replace-loader',
options: {
search: 'require(parserOptions.parser || "espree")',
replace:
'(parserOptions.parser === "babel-eslint" ? require("babel-eslint") : require("espree"))',
},
},
// Patch for `babel-eslint`
{
test: new RegExp(`babel-eslint${sepRe}lib${sepRe}index\\.js$`),
loader: 'string-replace-loader',
options: {
search: '[\\s\\S]+', // whole file.
replace:
'module.exports.parseForESLint = require("./parse-with-scope")',
flags: 'g',
},
},
// Remove dynamic require in jest circus
{
test: /format_node_assert_errors\.js/,
loader: 'string-replace-loader',
options: {
search: `assert = require.call(null, 'assert');`,
replace: `throw new Error('module assert not found')`,
},
},
// Remove dynamic require in jest circus
{
test: /babel-plugin-macros/,
loader: 'string-replace-loader',
options: {
search: `_require(`,
replace: `self.require(`,
},
},
// "postcss" loader applies autoprefixer to our CSS.
// "css" loader resolves paths in CSS and adds assets as dependencies.
// "style" loader turns CSS into JS modules that inject <style> tags.
// In production, we use a plugin to extract that CSS to a file, but
// in development "style" loader enables hot editing of CSS.
{
test: /\.css$/,
loaders: getStyleLoaders({
importLoaders: 1,
sourceMap: true,
}),
// Don't consider CSS imports dead code even if the
// containing package claims to have no side effects.
// Remove this when webpack adds a warning or an error for this.
// See https://github.com/webpack/webpack/issues/6571
sideEffects: true,
},
// For importing README.md
{
test: /\.md$/,
loader: 'raw-loader',
},
// "file" loader makes sure those assets get served by WebpackDevServer.
// When you `import` an asset, you get its (virtual) filename.
// In production, they would get copied to the `build` folder.
{
test: /\.(svg)(\?.*)?$/,
use: [
{
loader: 'file-loader',
options: {
name: 'static/media/[name].[hash:8].[ext]',
},
},
{ loader: 'svgo-loader' },
],
},
{
test: /\.(ico|jpg|png|gif|eot|otf|webp|ttf|woff|woff2)(\?.*)?$/,
exclude: [/\/favicon.ico$/],
loader: 'file-loader',
options: {
name: 'static/media/[name].[hash:8].[ext]',
},
},
// A special case for favicon.ico to place it into build root directory.
{
test: /\/favicon.ico$/,
include: [paths.src],
loader: 'file-loader',
options: {
name: 'favicon.ico?[hash:8]',
},
},
// "url" loader works just like "file" loader but it also embeds
// assets smaller than specified size as data URLs to avoid requests.
{
test: /\.(mp4|webm)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: 'static/media/[name].[hash:8].[ext]',
},
},
],
noParse: [
/eslint\.4\.1\.0\.min\.js$/,
/typescriptServices\.js$/,
/browserfs\.js/,
/browserfs\.min\.js/,
/standalone-packages\/codesandbox-browserfs/,
/standalone-packages\/vscode\//,
/fontfaceobserver\.standalone\.js/,
],
},
externals: ['jsdom', 'prettier', 'cosmiconfig'],
resolve: {
mainFields: ['browser', 'module', 'jsnext:main', 'main'],
modules: [
'node_modules',
path.resolve(__dirname, '../src'),
'standalone-packages',
],
extensions: ['.js', '.json', '.ts', '.tsx'],
alias: {
moment: 'moment/moment.js',
fs: 'codesandbox-browserfs/dist/shims/fs.js',
buffer: 'codesandbox-browserfs/dist/shims/buffer.js',
processGlobal: 'codesandbox-browserfs/dist/shims/process.js',
bufferGlobal: 'codesandbox-browserfs/dist/shims/bufferGlobal.js',
bfsGlobal: require.resolve(
path.join(
'..',
'..',
'..',
'standalone-packages',
'codesandbox-browserfs',
'build',
__DEV__ ? 'browserfs.js' : 'browserfs.min.js'
)
),
},
},
plugins: [
...(SANDBOX_ONLY
? [
new HtmlWebpackPlugin({
inject: true,
chunks: ['sandbox-startup', 'vendors~sandbox', 'sandbox'],
filename: 'index.html',
template: paths.sandboxHtml,
minify: __PROD__ && {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true,
},
}),
new ScriptExtHtmlWebpackPlugin({
custom: {
test: 'sandbox',
attribute: 'crossorigin',
value: 'anonymous',
},
}),
]
: [
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin({
inject: true,
chunks: __PROD__ ? ['common-sandbox', 'common', 'app'] : ['app'],
chunksSortMode: 'manual',
filename: 'app.html',
template: paths.appHtml,
minify: __PROD__ && {
removeComments: false,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true,
},
}),
new HtmlWebpackPlugin({
inject: true,
chunks: __PROD__
? [
'sandbox-startup',
'common-sandbox',
'vendors~sandbox',
'sandbox',
]
: ['sandbox-startup', 'sandbox'],
chunksSortMode: 'manual',
filename: 'frame.html',
template: paths.sandboxHtml,
minify: __PROD__ && {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true,
},
}),
new ScriptExtHtmlWebpackPlugin({
custom: {
test: 'sandbox',
attribute: 'crossorigin',
value: 'anonymous',
},
}),
new HtmlWebpackPlugin({
inject: true,
chunks: __PROD__
? ['common-sandbox', 'common', 'embed']
: ['embed'],
chunksSortMode: 'manual',
filename: 'embed.html',
template: path.join(paths.embedSrc, 'index.html'),
minify: __PROD__ && {
removeComments: false,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true,
},
}),
]),
// Makes some environment variables available to the JS code, for example:
// if (process.env.NODE_ENV === 'development') { ... }. See `env.js`.
new webpack.DefinePlugin(env.default),
new webpack.DefinePlugin({ __DEV__ }),
// Watcher doesn't work well if you mistype casing in a path so we use
// a plugin that prints an error when you attempt to do this.
// See https://github.com/facebookincubator/create-react-app/issues/240
new CaseSensitivePathsPlugin(),
// With this plugin we override the load-rules of eslint, this function prevents
// us from using eslint in the browser, therefore we need to stop it!
!SANDBOX_ONLY &&
new webpack.NormalModuleReplacementPlugin(
new RegExp(['eslint', 'lib', 'load-rules'].join(sepRe)),
path.join(paths.config, 'stubs/load-rules.compiled.js')
),
// DON'T TOUCH THIS. There's a bug in Webpack 4 that causes bundle splitting
// to break when using lru-cache. So we literally gice them our own version
new webpack.NormalModuleReplacementPlugin(
/^lru-cache$/,
path.join(paths.config, 'stubs/lru-cache.js')
),
// If you require a missing module and then `npm install` it, you still have
// to restart the development server for Webpack to discover it. This plugin
// makes the discovery automatic so you don't have to restart.
// See https://github.com/facebookincubator/create-react-app/issues/186
new WatchMissingNodeModulesPlugin(paths.appNodeModules),
__PROD__ &&
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: 'static/css/[name].[contenthash:8].css',
chunkFilename: 'static/css/[name].[contenthash:8].chunk.css',
}),
].filter(Boolean),
};