1 | "use strict";
|
2 |
|
3 | require(`v8-compile-cache`);
|
4 |
|
5 | const fs = require(`fs-extra`);
|
6 |
|
7 | const path = require(`path`);
|
8 |
|
9 | const dotenv = require(`dotenv`);
|
10 |
|
11 | const PnpWebpackPlugin = require(`pnp-webpack-plugin`);
|
12 |
|
13 | const {
|
14 | store
|
15 | } = require(`../redux`);
|
16 |
|
17 | const {
|
18 | actions
|
19 | } = require(`../redux/actions`);
|
20 |
|
21 | const getPublicPath = require(`./get-public-path`);
|
22 |
|
23 | const debug = require(`debug`)(`gatsby:webpack-config`);
|
24 |
|
25 | const report = require(`gatsby-cli/lib/reporter`);
|
26 |
|
27 | const {
|
28 | withBasePath,
|
29 | withTrailingSlash
|
30 | } = require(`./path`);
|
31 |
|
32 | const getGatsbyDependents = require(`./gatsby-dependents`);
|
33 |
|
34 | const apiRunnerNode = require(`./api-runner-node`);
|
35 |
|
36 | const createUtils = require(`./webpack-utils`);
|
37 |
|
38 | const hasLocalEslint = require(`./local-eslint-config-finder`);
|
39 |
|
40 |
|
41 |
|
42 |
|
43 |
|
44 |
|
45 | module.exports = async (program, directory, suppliedStage, port, {
|
46 | parentSpan
|
47 | } = {}) => {
|
48 | const modulesThatUseGatsby = await getGatsbyDependents();
|
49 | const directoryPath = withBasePath(directory);
|
50 | process.env.GATSBY_BUILD_STAGE = suppliedStage;
|
51 |
|
52 |
|
53 | const stage = suppliedStage;
|
54 | const {
|
55 | rules,
|
56 | loaders,
|
57 | plugins
|
58 | } = await createUtils({
|
59 | stage,
|
60 | program
|
61 | });
|
62 | const {
|
63 | assetPrefix,
|
64 | pathPrefix
|
65 | } = store.getState().config;
|
66 | const publicPath = getPublicPath(Object.assign({
|
67 | assetPrefix,
|
68 | pathPrefix
|
69 | }, program));
|
70 |
|
71 | function processEnv(stage, defaultNodeEnv) {
|
72 | debug(`Building env for "${stage}"`);
|
73 |
|
74 |
|
75 | const nodeEnv = process.env.NODE_ENV || `${defaultNodeEnv}`;
|
76 |
|
77 |
|
78 | const configEnv = process.env.GATSBY_ACTIVE_ENV || nodeEnv;
|
79 | const envFile = path.join(process.cwd(), `./.env.${configEnv}`);
|
80 | let parsed = {};
|
81 |
|
82 | try {
|
83 | parsed = dotenv.parse(fs.readFileSync(envFile, {
|
84 | encoding: `utf8`
|
85 | }));
|
86 | } catch (err) {
|
87 | if (err.code !== `ENOENT`) {
|
88 | report.error(`There was a problem processing the .env file (${envFile})`, err);
|
89 | }
|
90 | }
|
91 |
|
92 | const envObject = Object.keys(parsed).reduce((acc, key) => {
|
93 | acc[key] = JSON.stringify(parsed[key]);
|
94 | return acc;
|
95 | }, {});
|
96 | const gatsbyVarObject = Object.keys(process.env).reduce((acc, key) => {
|
97 | if (key.match(/^GATSBY_/)) {
|
98 | acc[key] = JSON.stringify(process.env[key]);
|
99 | }
|
100 |
|
101 | return acc;
|
102 | }, {});
|
103 |
|
104 | envObject.NODE_ENV = JSON.stringify(nodeEnv);
|
105 | envObject.PUBLIC_DIR = JSON.stringify(`${process.cwd()}/public`);
|
106 | envObject.BUILD_STAGE = JSON.stringify(stage);
|
107 | envObject.CYPRESS_SUPPORT = JSON.stringify(process.env.CYPRESS_SUPPORT);
|
108 | const mergedEnvVars = Object.assign(envObject, gatsbyVarObject);
|
109 | return Object.keys(mergedEnvVars).reduce((acc, key) => {
|
110 | acc[`process.env.${key}`] = mergedEnvVars[key];
|
111 | return acc;
|
112 | }, {
|
113 | "process.env": JSON.stringify({})
|
114 | });
|
115 | }
|
116 |
|
117 | function getHmrPath() {
|
118 |
|
119 | let hmrBasePath = `/`;
|
120 | const hmrSuffix = `__webpack_hmr&reload=true&overlay=false`;
|
121 |
|
122 | if (process.env.GATSBY_WEBPACK_PUBLICPATH) {
|
123 | const pubPath = process.env.GATSBY_WEBPACK_PUBLICPATH;
|
124 |
|
125 | if (pubPath.substr(-1) === `/`) {
|
126 | hmrBasePath = pubPath;
|
127 | } else {
|
128 | hmrBasePath = withTrailingSlash(pubPath);
|
129 | }
|
130 | }
|
131 |
|
132 | return hmrBasePath + hmrSuffix;
|
133 | }
|
134 |
|
135 | debug(`Loading webpack config for stage "${stage}"`);
|
136 |
|
137 | function getOutput() {
|
138 | switch (stage) {
|
139 | case `develop`:
|
140 | return {
|
141 | path: directory,
|
142 | filename: `[name].js`,
|
143 |
|
144 | pathinfo: true,
|
145 |
|
146 | publicPath: process.env.GATSBY_WEBPACK_PUBLICPATH || `/`,
|
147 | devtoolModuleFilenameTemplate: info => path.resolve(info.absoluteResourcePath).replace(/\\/g, `/`),
|
148 |
|
149 |
|
150 | crossOriginLoading: `anonymous`
|
151 | };
|
152 |
|
153 | case `build-html`:
|
154 | case `develop-html`:
|
155 |
|
156 |
|
157 | return {
|
158 | path: directoryPath(`public`),
|
159 | filename: `render-page.js`,
|
160 | libraryTarget: `umd`,
|
161 | library: `lib`,
|
162 | umdNamedDefine: true,
|
163 | globalObject: `this`,
|
164 | publicPath: withTrailingSlash(publicPath)
|
165 | };
|
166 |
|
167 | case `build-javascript`:
|
168 | return {
|
169 | filename: `[name]-[contenthash].js`,
|
170 | chunkFilename: `[name]-[contenthash].js`,
|
171 | path: directoryPath(`public`),
|
172 | publicPath: withTrailingSlash(publicPath)
|
173 | };
|
174 |
|
175 | default:
|
176 | throw new Error(`The state requested ${stage} doesn't exist.`);
|
177 | }
|
178 | }
|
179 |
|
180 | function getEntry() {
|
181 | switch (stage) {
|
182 | case `develop`:
|
183 | return {
|
184 | commons: [require.resolve(`event-source-polyfill`), `${require.resolve(`webpack-hot-middleware/client`)}?path=${getHmrPath()}`, directoryPath(`.cache/app`)]
|
185 | };
|
186 |
|
187 | case `develop-html`:
|
188 | return {
|
189 | main: directoryPath(`.cache/develop-static-entry`)
|
190 | };
|
191 |
|
192 | case `build-html`:
|
193 | return {
|
194 | main: directoryPath(`.cache/static-entry`)
|
195 | };
|
196 |
|
197 | case `build-javascript`:
|
198 | return {
|
199 | app: directoryPath(`.cache/production-app`)
|
200 | };
|
201 |
|
202 | default:
|
203 | throw new Error(`The state requested ${stage} doesn't exist.`);
|
204 | }
|
205 | }
|
206 |
|
207 | function getPlugins() {
|
208 | let configPlugins = [plugins.moment(),
|
209 |
|
210 | plugins.define(Object.assign({}, processEnv(stage, `development`), {
|
211 | __BASE_PATH__: JSON.stringify(program.prefixPaths ? pathPrefix : ``),
|
212 | __PATH_PREFIX__: JSON.stringify(program.prefixPaths ? publicPath : ``),
|
213 | __ASSET_PREFIX__: JSON.stringify(program.prefixPaths ? assetPrefix : ``)
|
214 | }))];
|
215 |
|
216 | switch (stage) {
|
217 | case `develop`:
|
218 | configPlugins = configPlugins.concat([plugins.hotModuleReplacement(), plugins.noEmitOnErrors(), plugins.eslintGraphqlSchemaReload()]);
|
219 | break;
|
220 |
|
221 | case `build-javascript`:
|
222 | {
|
223 | configPlugins = configPlugins.concat([plugins.extractText(),
|
224 |
|
225 | plugins.extractStats()]);
|
226 | break;
|
227 | }
|
228 | }
|
229 |
|
230 | return configPlugins;
|
231 | }
|
232 |
|
233 | function getDevtool() {
|
234 | switch (stage) {
|
235 | case `develop`:
|
236 | return `cheap-module-source-map`;
|
237 |
|
238 |
|
239 |
|
240 | case `develop-html`:
|
241 | case `build-html`:
|
242 | case `build-javascript`:
|
243 | return `source-map`;
|
244 |
|
245 | default:
|
246 | return false;
|
247 | }
|
248 | }
|
249 |
|
250 | function getMode() {
|
251 | switch (stage) {
|
252 | case `build-javascript`:
|
253 | return `production`;
|
254 |
|
255 | case `develop`:
|
256 | case `develop-html`:
|
257 | case `build-html`:
|
258 | return `development`;
|
259 |
|
260 |
|
261 | default:
|
262 | return `production`;
|
263 | }
|
264 | }
|
265 |
|
266 | function getModule() {
|
267 |
|
268 |
|
269 | let configRules = [rules.js({
|
270 | modulesThatUseGatsby
|
271 | }), rules.yaml(), rules.fonts(), rules.images(), rules.media(), rules.miscAssets(),
|
272 |
|
273 |
|
274 |
|
275 | {
|
276 | test: require.resolve(`@reach/router/es/index`),
|
277 | type: `javascript/auto`,
|
278 | use: [{
|
279 | loader: require.resolve(`./reach-router-add-basecontext-export-loader`)
|
280 | }]
|
281 | }];
|
282 |
|
283 |
|
284 | if (stage === `build-javascript`) {
|
285 | configRules.push(rules.dependencies({
|
286 | modulesThatUseGatsby
|
287 | }));
|
288 | }
|
289 |
|
290 | if (store.getState().themes.themes) {
|
291 | configRules = configRules.concat(store.getState().themes.themes.map(theme => {
|
292 | return {
|
293 | test: /\.jsx?$/,
|
294 | include: theme.themeDir,
|
295 | use: [loaders.js()]
|
296 | };
|
297 | }));
|
298 | }
|
299 |
|
300 | switch (stage) {
|
301 | case `develop`:
|
302 | {
|
303 |
|
304 | const {
|
305 | schema,
|
306 | program
|
307 | } = store.getState();
|
308 |
|
309 | if (!hasLocalEslint(program.directory)) {
|
310 | configRules = configRules.concat([rules.eslint(schema)]);
|
311 | }
|
312 |
|
313 | configRules = configRules.concat([{
|
314 | oneOf: [rules.cssModules(), rules.css()]
|
315 | }]);
|
316 |
|
317 |
|
318 | configRules.push({
|
319 | include: /node_modules\/react-dom/,
|
320 | test: /\.jsx?$/,
|
321 | use: {
|
322 | loader: require.resolve(`./webpack-hmr-hooks-patch`)
|
323 | }
|
324 | });
|
325 | break;
|
326 | }
|
327 |
|
328 | case `build-html`:
|
329 | case `develop-html`:
|
330 |
|
331 |
|
332 |
|
333 |
|
334 | configRules = configRules.concat([{
|
335 | oneOf: [rules.cssModules(), Object.assign({}, rules.css(), {
|
336 | use: [loaders.null()]
|
337 | })]
|
338 | }]);
|
339 | break;
|
340 |
|
341 | case `build-javascript`:
|
342 |
|
343 |
|
344 |
|
345 |
|
346 |
|
347 |
|
348 | configRules = configRules.concat([{
|
349 | oneOf: [rules.cssModules(), rules.css()]
|
350 | }]);
|
351 | break;
|
352 | }
|
353 |
|
354 | return {
|
355 | rules: configRules
|
356 | };
|
357 | }
|
358 |
|
359 | function getResolve(stage) {
|
360 | const {
|
361 | program
|
362 | } = store.getState();
|
363 | const resolve = {
|
364 |
|
365 |
|
366 | extensions: [...program.extensions],
|
367 | alias: {
|
368 | gatsby$: directoryPath(path.join(`.cache`, `gatsby-browser-entry.js`)),
|
369 |
|
370 |
|
371 |
|
372 | "@babel/runtime": path.dirname(require.resolve(`@babel/runtime/package.json`)),
|
373 | "core-js": path.dirname(require.resolve(`core-js/package.json`)),
|
374 | "react-hot-loader": path.dirname(require.resolve(`react-hot-loader/package.json`)),
|
375 | "react-lifecycles-compat": directoryPath(`.cache/react-lifecycles-compat.js`),
|
376 | "create-react-context": directoryPath(`.cache/create-react-context.js`)
|
377 | },
|
378 | plugins: [
|
379 |
|
380 | PnpWebpackPlugin.bind(directoryPath(`.cache`), module), PnpWebpackPlugin.bind(directoryPath(`public`), module),
|
381 | PnpWebpackPlugin]
|
382 | };
|
383 | const target = stage === `build-html` || stage === `develop-html` ? `node` : `web`;
|
384 |
|
385 | if (target === `web`) {
|
386 |
|
387 |
|
388 | resolve.alias[`@reach/router`] = path.join(path.dirname(require.resolve(`@reach/router/package.json`)), `es`);
|
389 | }
|
390 |
|
391 | return resolve;
|
392 | }
|
393 |
|
394 | function getResolveLoader() {
|
395 | const root = [path.resolve(directory, `node_modules`)];
|
396 | const userLoaderDirectoryPath = path.resolve(directory, `loaders`);
|
397 |
|
398 | try {
|
399 | if (fs.statSync(userLoaderDirectoryPath).isDirectory()) {
|
400 | root.push(userLoaderDirectoryPath);
|
401 | }
|
402 | } catch (err) {
|
403 | debug(`Error resolving user loaders directory`, err);
|
404 | }
|
405 |
|
406 | return {
|
407 | modules: [...root, path.join(__dirname, `../loaders`), `node_modules`],
|
408 |
|
409 |
|
410 | plugins: [PnpWebpackPlugin.moduleLoader(`${directory}/`)]
|
411 | };
|
412 | }
|
413 |
|
414 | const config = {
|
415 |
|
416 | context: directory,
|
417 | entry: getEntry(),
|
418 | output: getOutput(),
|
419 | module: getModule(),
|
420 | plugins: getPlugins(),
|
421 |
|
422 |
|
423 |
|
424 |
|
425 | target: stage === `build-html` || stage === `develop-html` ? `node` : `web`,
|
426 | devtool: getDevtool(),
|
427 |
|
428 |
|
429 | performance: {
|
430 | hints: false
|
431 | },
|
432 | mode: getMode(),
|
433 | resolveLoader: getResolveLoader(),
|
434 | resolve: getResolve(stage),
|
435 | node: {
|
436 | __filename: true
|
437 | }
|
438 | };
|
439 |
|
440 | if (stage === `build-javascript`) {
|
441 | const componentsCount = store.getState().components.size;
|
442 | config.optimization = {
|
443 | runtimeChunk: {
|
444 | name: `webpack-runtime`
|
445 | },
|
446 |
|
447 |
|
448 |
|
449 | moduleIds: `hashed`,
|
450 | splitChunks: {
|
451 | name: false,
|
452 | chunks: `all`,
|
453 | cacheGroups: {
|
454 | default: false,
|
455 | vendors: false,
|
456 | commons: {
|
457 | name: `commons`,
|
458 | chunks: `all`,
|
459 |
|
460 |
|
461 | minChunks: componentsCount > 2 ? componentsCount * 0.5 : 2
|
462 | },
|
463 | react: {
|
464 | name: `commons`,
|
465 | chunks: `all`,
|
466 | test: /[\\/]node_modules[\\/](react|react-dom|scheduler)[\\/]/
|
467 | },
|
468 |
|
469 |
|
470 |
|
471 |
|
472 | styles: {
|
473 | name: `styles`,
|
474 |
|
475 | test: /\.(css|scss|sass|less|styl)$/,
|
476 | chunks: `all`,
|
477 | enforce: true,
|
478 |
|
479 | priority: 10
|
480 | }
|
481 | }
|
482 | },
|
483 | minimizer: [
|
484 | !program.noUglify && plugins.minifyJs(), plugins.minifyCss()].filter(Boolean)
|
485 | };
|
486 | }
|
487 |
|
488 | if (stage === `build-html` || stage === `develop-html`) {
|
489 |
|
490 |
|
491 | const externalList = [`@reach/router/lib/history`, `@reach/router`, `common-tags`, /^core-js\
|
492 |
|
493 | const userExternalList = [`es6-promise`, `minimatch`, `pify`, `react-helmet`, `react`, /^react-dom\
|
494 |
|
495 | const checkItem = (item, request) => {
|
496 | if (typeof item === `string` && item === request) {
|
497 | return true;
|
498 | } else if (item instanceof RegExp && item.test(request)) {
|
499 | return true;
|
500 | }
|
501 |
|
502 | return false;
|
503 | };
|
504 |
|
505 | const isExternal = request => {
|
506 | if (externalList.some(item => checkItem(item, request))) {
|
507 | return `umd ${require.resolve(request)}`;
|
508 | }
|
509 |
|
510 | if (userExternalList.some(item => checkItem(item, request))) {
|
511 | return `umd ${request}`;
|
512 | }
|
513 |
|
514 | return null;
|
515 | };
|
516 |
|
517 | config.externals = [function (context, request, callback) {
|
518 | const external = isExternal(request);
|
519 |
|
520 | if (external !== null) {
|
521 | callback(null, external);
|
522 | } else {
|
523 | callback();
|
524 | }
|
525 | }];
|
526 | }
|
527 |
|
528 | store.dispatch(actions.replaceWebpackConfig(config));
|
529 |
|
530 | const getConfig = () => store.getState().webpack;
|
531 |
|
532 | await apiRunnerNode(`onCreateWebpackConfig`, {
|
533 | getConfig,
|
534 | stage,
|
535 | rules,
|
536 | loaders,
|
537 | plugins,
|
538 | parentSpan
|
539 | });
|
540 | return getConfig();
|
541 | };
|
542 |
|
\ | No newline at end of file |