Run yarn prettify for the first time. (#22)

This commit is contained in:
Dandelion Mané 2018-02-18 08:13:29 -08:00 committed by William Chargin
parent de359dbaa4
commit b367da8568
19 changed files with 418 additions and 410 deletions

View File

@ -1,16 +1,16 @@
'use strict'; "use strict";
const fs = require('fs'); const fs = require("fs");
const path = require('path'); const path = require("path");
const paths = require('./paths'); const paths = require("./paths");
// Make sure that including paths.js after env.js will read .env variables. // Make sure that including paths.js after env.js will read .env variables.
delete require.cache[require.resolve('./paths')]; delete require.cache[require.resolve("./paths")];
const NODE_ENV = process.env.NODE_ENV; const NODE_ENV = process.env.NODE_ENV;
if (!NODE_ENV) { if (!NODE_ENV) {
throw new Error( throw new Error(
'The NODE_ENV environment variable is required but was not specified.' "The NODE_ENV environment variable is required but was not specified."
); );
} }
@ -21,7 +21,7 @@ var dotenvFiles = [
// Don't include `.env.local` for `test` environment // Don't include `.env.local` for `test` environment
// since normally you expect tests to produce the same // since normally you expect tests to produce the same
// results for everyone // results for everyone
NODE_ENV !== 'test' && `${paths.dotenv}.local`, NODE_ENV !== "test" && `${paths.dotenv}.local`,
paths.dotenv, paths.dotenv,
].filter(Boolean); ].filter(Boolean);
@ -30,10 +30,10 @@ var dotenvFiles = [
// that have already been set. Variable expansion is supported in .env files. // that have already been set. Variable expansion is supported in .env files.
// https://github.com/motdotla/dotenv // https://github.com/motdotla/dotenv
// https://github.com/motdotla/dotenv-expand // https://github.com/motdotla/dotenv-expand
dotenvFiles.forEach(dotenvFile => { dotenvFiles.forEach((dotenvFile) => {
if (fs.existsSync(dotenvFile)) { if (fs.existsSync(dotenvFile)) {
require('dotenv-expand')( require("dotenv-expand")(
require('dotenv').config({ require("dotenv").config({
path: dotenvFile, path: dotenvFile,
}) })
); );
@ -50,10 +50,10 @@ dotenvFiles.forEach(dotenvFile => {
// https://github.com/facebookincubator/create-react-app/issues/1023#issuecomment-265344421 // https://github.com/facebookincubator/create-react-app/issues/1023#issuecomment-265344421
// We also resolve them to make sure all tools using them work consistently. // We also resolve them to make sure all tools using them work consistently.
const appDirectory = fs.realpathSync(process.cwd()); const appDirectory = fs.realpathSync(process.cwd());
process.env.NODE_PATH = (process.env.NODE_PATH || '') process.env.NODE_PATH = (process.env.NODE_PATH || "")
.split(path.delimiter) .split(path.delimiter)
.filter(folder => folder && !path.isAbsolute(folder)) .filter((folder) => folder && !path.isAbsolute(folder))
.map(folder => path.resolve(appDirectory, folder)) .map((folder) => path.resolve(appDirectory, folder))
.join(path.delimiter); .join(path.delimiter);
// Grab NODE_ENV and REACT_APP_* environment variables and prepare them to be // Grab NODE_ENV and REACT_APP_* environment variables and prepare them to be
@ -62,7 +62,7 @@ const REACT_APP = /^REACT_APP_/i;
function getClientEnvironment(publicUrl) { function getClientEnvironment(publicUrl) {
const raw = Object.keys(process.env) const raw = Object.keys(process.env)
.filter(key => REACT_APP.test(key)) .filter((key) => REACT_APP.test(key))
.reduce( .reduce(
(env, key) => { (env, key) => {
env[key] = process.env[key]; env[key] = process.env[key];
@ -71,7 +71,7 @@ function getClientEnvironment(publicUrl) {
{ {
// Useful for determining whether were running in production mode. // Useful for determining whether were running in production mode.
// Most importantly, it switches React into the correct mode. // Most importantly, it switches React into the correct mode.
NODE_ENV: process.env.NODE_ENV || 'development', NODE_ENV: process.env.NODE_ENV || "development",
// Useful for resolving the correct path to static assets in `public`. // Useful for resolving the correct path to static assets in `public`.
// For example, <img src={process.env.PUBLIC_URL + '/img/logo.png'} />. // For example, <img src={process.env.PUBLIC_URL + '/img/logo.png'} />.
// This should only be used as an escape hatch. Normally you would put // This should only be used as an escape hatch. Normally you would put
@ -81,13 +81,13 @@ function getClientEnvironment(publicUrl) {
); );
// Stringify all values so we can feed into Webpack DefinePlugin // Stringify all values so we can feed into Webpack DefinePlugin
const stringified = { const stringified = {
'process.env': Object.keys(raw).reduce((env, key) => { "process.env": Object.keys(raw).reduce((env, key) => {
env[key] = JSON.stringify(raw[key]); env[key] = JSON.stringify(raw[key]);
return env; return env;
}, {}), }, {}),
}; };
return { raw, stringified }; return {raw, stringified};
} }
module.exports = getClientEnvironment; module.exports = getClientEnvironment;

View File

@ -1,14 +1,14 @@
'use strict'; "use strict";
// This is a custom Jest transformer turning style imports into empty objects. // This is a custom Jest transformer turning style imports into empty objects.
// http://facebook.github.io/jest/docs/en/webpack.html // http://facebook.github.io/jest/docs/en/webpack.html
module.exports = { module.exports = {
process() { process() {
return 'module.exports = {};'; return "module.exports = {};";
}, },
getCacheKey() { getCacheKey() {
// The output is always the same. // The output is always the same.
return 'cssTransform'; return "cssTransform";
}, },
}; };

View File

@ -1,6 +1,6 @@
'use strict'; "use strict";
const path = require('path'); const path = require("path");
// This is a custom Jest transformer turning file imports into filenames. // This is a custom Jest transformer turning file imports into filenames.
// http://facebook.github.io/jest/docs/en/webpack.html // http://facebook.github.io/jest/docs/en/webpack.html

View File

@ -1,18 +1,18 @@
'use strict'; "use strict";
const path = require('path'); const path = require("path");
const fs = require('fs'); const fs = require("fs");
const url = require('url'); const url = require("url");
// Make sure any symlinks in the project folder are resolved: // Make sure any symlinks in the project folder are resolved:
// https://github.com/facebookincubator/create-react-app/issues/637 // https://github.com/facebookincubator/create-react-app/issues/637
const appDirectory = fs.realpathSync(process.cwd()); const appDirectory = fs.realpathSync(process.cwd());
const resolveApp = relativePath => path.resolve(appDirectory, relativePath); const resolveApp = (relativePath) => path.resolve(appDirectory, relativePath);
const envPublicUrl = process.env.PUBLIC_URL; const envPublicUrl = process.env.PUBLIC_URL;
function ensureSlash(path, needsSlash) { function ensureSlash(path, needsSlash) {
const hasSlash = path.endsWith('/'); const hasSlash = path.endsWith("/");
if (hasSlash && !needsSlash) { if (hasSlash && !needsSlash) {
return path.substr(path, path.length - 1); return path.substr(path, path.length - 1);
} else if (!hasSlash && needsSlash) { } else if (!hasSlash && needsSlash) {
@ -22,7 +22,7 @@ function ensureSlash(path, needsSlash) {
} }
} }
const getPublicUrl = appPackageJson => const getPublicUrl = (appPackageJson) =>
envPublicUrl || require(appPackageJson).homepage; envPublicUrl || require(appPackageJson).homepage;
// We use `PUBLIC_URL` environment variable or "homepage" field to infer // We use `PUBLIC_URL` environment variable or "homepage" field to infer
@ -34,22 +34,22 @@ const getPublicUrl = appPackageJson =>
function getServedPath(appPackageJson) { function getServedPath(appPackageJson) {
const publicUrl = getPublicUrl(appPackageJson); const publicUrl = getPublicUrl(appPackageJson);
const servedUrl = const servedUrl =
envPublicUrl || (publicUrl ? url.parse(publicUrl).pathname : '/'); envPublicUrl || (publicUrl ? url.parse(publicUrl).pathname : "/");
return ensureSlash(servedUrl, true); return ensureSlash(servedUrl, true);
} }
// config after eject: we're in ./config/ // config after eject: we're in ./config/
module.exports = { module.exports = {
dotenv: resolveApp('.env'), dotenv: resolveApp(".env"),
appBuild: resolveApp('build'), appBuild: resolveApp("build"),
appPublic: resolveApp('public'), appPublic: resolveApp("public"),
appHtml: resolveApp('public/index.html'), appHtml: resolveApp("public/index.html"),
appIndexJs: resolveApp('src/index.js'), appIndexJs: resolveApp("src/index.js"),
appPackageJson: resolveApp('package.json'), appPackageJson: resolveApp("package.json"),
appSrc: resolveApp('src'), appSrc: resolveApp("src"),
yarnLockFile: resolveApp('yarn.lock'), yarnLockFile: resolveApp("yarn.lock"),
testsSetup: resolveApp('src/setupTests.js'), testsSetup: resolveApp("src/setupTests.js"),
appNodeModules: resolveApp('node_modules'), appNodeModules: resolveApp("node_modules"),
publicUrl: getPublicUrl(resolveApp('package.json')), publicUrl: getPublicUrl(resolveApp("package.json")),
servedPath: getServedPath(resolveApp('package.json')), servedPath: getServedPath(resolveApp("package.json")),
}; };

View File

@ -1,22 +1,22 @@
'use strict'; "use strict";
if (typeof Promise === 'undefined') { if (typeof Promise === "undefined") {
// Rejection tracking prevents a common issue where React gets into an // Rejection tracking prevents a common issue where React gets into an
// inconsistent state due to an error, but it gets swallowed by a Promise, // inconsistent state due to an error, but it gets swallowed by a Promise,
// and the user has no idea what causes React's erratic future behavior. // and the user has no idea what causes React's erratic future behavior.
require('promise/lib/rejection-tracking').enable(); require("promise/lib/rejection-tracking").enable();
window.Promise = require('promise/lib/es6-extensions.js'); window.Promise = require("promise/lib/es6-extensions.js");
} }
// fetch() polyfill for making API calls. // fetch() polyfill for making API calls.
require('whatwg-fetch'); require("whatwg-fetch");
// Object.assign() is commonly used with React. // Object.assign() is commonly used with React.
// It will use the native implementation if it's present and isn't buggy. // It will use the native implementation if it's present and isn't buggy.
Object.assign = require('object-assign'); Object.assign = require("object-assign");
// In tests, polyfill requestAnimationFrame since jsdom doesn't provide it yet. // In tests, polyfill requestAnimationFrame since jsdom doesn't provide it yet.
// We don't polyfill it in the browser--this is user's responsibility. // We don't polyfill it in the browser--this is user's responsibility.
if (process.env.NODE_ENV === 'test') { if (process.env.NODE_ENV === "test") {
require('raf').polyfill(global); require("raf").polyfill(global);
} }

View File

@ -1,24 +1,24 @@
'use strict'; "use strict";
const autoprefixer = require('autoprefixer'); const autoprefixer = require("autoprefixer");
const path = require('path'); const path = require("path");
const webpack = require('webpack'); const webpack = require("webpack");
const HtmlWebpackPlugin = require('html-webpack-plugin'); const HtmlWebpackPlugin = require("html-webpack-plugin");
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin'); const CaseSensitivePathsPlugin = require("case-sensitive-paths-webpack-plugin");
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin'); const InterpolateHtmlPlugin = require("react-dev-utils/InterpolateHtmlPlugin");
const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin'); const WatchMissingNodeModulesPlugin = require("react-dev-utils/WatchMissingNodeModulesPlugin");
const eslintFormatter = require('react-dev-utils/eslintFormatter'); const eslintFormatter = require("react-dev-utils/eslintFormatter");
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin'); const ModuleScopePlugin = require("react-dev-utils/ModuleScopePlugin");
const getClientEnvironment = require('./env'); const getClientEnvironment = require("./env");
const paths = require('./paths'); const paths = require("./paths");
// Webpack uses `publicPath` to determine where the app is being served from. // Webpack uses `publicPath` to determine where the app is being served from.
// In development, we always serve from the root. This makes config easier. // In development, we always serve from the root. This makes config easier.
const publicPath = '/'; const publicPath = "/";
// `publicUrl` is just like `publicPath`, but we will provide it to our app // `publicUrl` is just like `publicPath`, but we will provide it to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript. // as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_PATH%/xyz looks better than %PUBLIC_PATH%xyz. // Omit trailing slash as %PUBLIC_PATH%/xyz looks better than %PUBLIC_PATH%xyz.
const publicUrl = ''; const publicUrl = "";
// Get environment variables to inject into our app. // Get environment variables to inject into our app.
const env = getClientEnvironment(publicUrl); const env = getClientEnvironment(publicUrl);
@ -28,13 +28,13 @@ const env = getClientEnvironment(publicUrl);
module.exports = { module.exports = {
// You may want 'eval' instead if you prefer to see the compiled output in DevTools. // You may want 'eval' instead if you prefer to see the compiled output in DevTools.
// See the discussion in https://github.com/facebookincubator/create-react-app/issues/343. // See the discussion in https://github.com/facebookincubator/create-react-app/issues/343.
devtool: 'cheap-module-source-map', devtool: "cheap-module-source-map",
// These are the "entry points" to our application. // These are the "entry points" to our application.
// This means they will be the "root" imports that are included in JS bundle. // This means they will be the "root" imports that are included in JS bundle.
// The first two entry points enable "hot" CSS and auto-refreshes for JS. // The first two entry points enable "hot" CSS and auto-refreshes for JS.
entry: [ entry: [
// We ship a few polyfills by default: // We ship a few polyfills by default:
require.resolve('./polyfills'), require.resolve("./polyfills"),
// Include an alternative client for WebpackDevServer. A client's job is to // Include an alternative client for WebpackDevServer. A client's job is to
// connect to WebpackDevServer by a socket and get notified about changes. // connect to WebpackDevServer by a socket and get notified about changes.
// When you save a file, the client will either apply hot updates (in case // When you save a file, the client will either apply hot updates (in case
@ -45,7 +45,7 @@ module.exports = {
// the line below with these two lines if you prefer the stock client: // the line below with these two lines if you prefer the stock client:
// require.resolve('webpack-dev-server/client') + '?/', // require.resolve('webpack-dev-server/client') + '?/',
// require.resolve('webpack/hot/dev-server'), // require.resolve('webpack/hot/dev-server'),
require.resolve('react-dev-utils/webpackHotDevClient'), require.resolve("react-dev-utils/webpackHotDevClient"),
// Finally, this is your app's code: // Finally, this is your app's code:
paths.appIndexJs, paths.appIndexJs,
// We include the app code last so that if there is a runtime error during // We include the app code last so that if there is a runtime error during
@ -58,21 +58,21 @@ module.exports = {
// This does not produce a real file. It's just the virtual path that is // This does not produce a real file. It's just the virtual path that is
// served by WebpackDevServer in development. This is the JS bundle // served by WebpackDevServer in development. This is the JS bundle
// containing code from all our entry points, and the Webpack runtime. // containing code from all our entry points, and the Webpack runtime.
filename: 'static/js/bundle.js', filename: "static/js/bundle.js",
// There are also additional JS chunk files if you use code splitting. // There are also additional JS chunk files if you use code splitting.
chunkFilename: 'static/js/[name].chunk.js', chunkFilename: "static/js/[name].chunk.js",
// This is the URL that app is served from. We use "/" in development. // This is the URL that app is served from. We use "/" in development.
publicPath: publicPath, publicPath: publicPath,
// Point sourcemap entries to original disk location (format as URL on Windows) // Point sourcemap entries to original disk location (format as URL on Windows)
devtoolModuleFilenameTemplate: info => devtoolModuleFilenameTemplate: (info) =>
path.resolve(info.absoluteResourcePath).replace(/\\/g, '/'), path.resolve(info.absoluteResourcePath).replace(/\\/g, "/"),
}, },
resolve: { resolve: {
// This allows you to set a fallback for where Webpack should look for modules. // This allows you to set a fallback for where Webpack should look for modules.
// We placed these paths second because we want `node_modules` to "win" // We placed these paths second because we want `node_modules` to "win"
// if there are any conflicts. This matches Node resolution mechanism. // if there are any conflicts. This matches Node resolution mechanism.
// https://github.com/facebookincubator/create-react-app/issues/253 // https://github.com/facebookincubator/create-react-app/issues/253
modules: ['node_modules', paths.appNodeModules].concat( modules: ["node_modules", paths.appNodeModules].concat(
// It is guaranteed to exist because we tweak it in `env.js` // It is guaranteed to exist because we tweak it in `env.js`
process.env.NODE_PATH.split(path.delimiter).filter(Boolean) process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
), ),
@ -82,12 +82,11 @@ module.exports = {
// https://github.com/facebookincubator/create-react-app/issues/290 // https://github.com/facebookincubator/create-react-app/issues/290
// `web` extension prefixes have been added for better support // `web` extension prefixes have been added for better support
// for React Native Web. // for React Native Web.
extensions: ['.web.js', '.mjs', '.js', '.json', '.web.jsx', '.jsx'], extensions: [".web.js", ".mjs", ".js", ".json", ".web.jsx", ".jsx"],
alias: { alias: {
// Support React Native Web // Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/ // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
'react-native': 'react-native-web', "react-native": "react-native-web",
}, },
plugins: [ plugins: [
// Prevents users from importing files from outside of src/ (or node_modules/). // Prevents users from importing files from outside of src/ (or node_modules/).
@ -109,15 +108,14 @@ module.exports = {
// It's important to do this before Babel processes the JS. // It's important to do this before Babel processes the JS.
{ {
test: /\.(js|jsx|mjs)$/, test: /\.(js|jsx|mjs)$/,
enforce: 'pre', enforce: "pre",
use: [ use: [
{ {
options: { options: {
formatter: eslintFormatter, formatter: eslintFormatter,
eslintPath: require.resolve('eslint'), eslintPath: require.resolve("eslint"),
}, },
loader: require.resolve('eslint-loader'), loader: require.resolve("eslint-loader"),
}, },
], ],
include: paths.appSrc, include: paths.appSrc,
@ -132,19 +130,18 @@ module.exports = {
// A missing `test` is equivalent to a match. // A missing `test` is equivalent to a match.
{ {
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/], test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
loader: require.resolve('url-loader'), loader: require.resolve("url-loader"),
options: { options: {
limit: 10000, limit: 10000,
name: 'static/media/[name].[hash:8].[ext]', name: "static/media/[name].[hash:8].[ext]",
}, },
}, },
// Process JS with Babel. // Process JS with Babel.
{ {
test: /\.(js|jsx|mjs)$/, test: /\.(js|jsx|mjs)$/,
include: paths.appSrc, include: paths.appSrc,
loader: require.resolve('babel-loader'), loader: require.resolve("babel-loader"),
options: { options: {
// This is a feature of `babel-loader` for webpack (not Babel itself). // This is a feature of `babel-loader` for webpack (not Babel itself).
// It enables caching results in ./node_modules/.cache/babel-loader/ // It enables caching results in ./node_modules/.cache/babel-loader/
// directory for faster rebuilds. // directory for faster rebuilds.
@ -159,29 +156,29 @@ module.exports = {
{ {
test: /\.css$/, test: /\.css$/,
use: [ use: [
require.resolve('style-loader'), require.resolve("style-loader"),
{ {
loader: require.resolve('css-loader'), loader: require.resolve("css-loader"),
options: { options: {
importLoaders: 1, importLoaders: 1,
}, },
}, },
{ {
loader: require.resolve('postcss-loader'), loader: require.resolve("postcss-loader"),
options: { options: {
// Necessary for external CSS imports to work // Necessary for external CSS imports to work
// https://github.com/facebookincubator/create-react-app/issues/2677 // https://github.com/facebookincubator/create-react-app/issues/2677
ident: 'postcss', ident: "postcss",
plugins: () => [ plugins: () => [
require('postcss-flexbugs-fixes'), require("postcss-flexbugs-fixes"),
autoprefixer({ autoprefixer({
browsers: [ browsers: [
'>1%', ">1%",
'last 4 versions', "last 4 versions",
'Firefox ESR', "Firefox ESR",
'not ie < 9', // React doesn't support IE8 anyway "not ie < 9", // React doesn't support IE8 anyway
], ],
flexbox: 'no-2009', flexbox: "no-2009",
}), }),
], ],
}, },
@ -199,9 +196,9 @@ module.exports = {
// Also exclude `html` and `json` extensions so they get processed // Also exclude `html` and `json` extensions so they get processed
// by webpacks internal loaders. // by webpacks internal loaders.
exclude: [/\.(js|jsx|mjs)$/, /\.html$/, /\.json$/], exclude: [/\.(js|jsx|mjs)$/, /\.html$/, /\.json$/],
loader: require.resolve('file-loader'), loader: require.resolve("file-loader"),
options: { options: {
name: 'static/media/[name].[hash:8].[ext]', name: "static/media/[name].[hash:8].[ext]",
}, },
}, },
], ],
@ -247,11 +244,11 @@ module.exports = {
// Some libraries import Node modules but don't use them in the browser. // Some libraries import Node modules but don't use them in the browser.
// Tell Webpack to provide empty mocks for them so importing them works. // Tell Webpack to provide empty mocks for them so importing them works.
node: { node: {
dgram: 'empty', dgram: "empty",
fs: 'empty', fs: "empty",
net: 'empty', net: "empty",
tls: 'empty', tls: "empty",
child_process: 'empty', child_process: "empty",
}, },
// Turn off performance hints during development because we don't do any // Turn off performance hints during development because we don't do any
// splitting or minification in interest of speed. These warnings become // splitting or minification in interest of speed. These warnings become

View File

@ -1,26 +1,26 @@
'use strict'; "use strict";
const autoprefixer = require('autoprefixer'); const autoprefixer = require("autoprefixer");
const path = require('path'); const path = require("path");
const webpack = require('webpack'); const webpack = require("webpack");
const HtmlWebpackPlugin = require('html-webpack-plugin'); const HtmlWebpackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require('extract-text-webpack-plugin'); const ExtractTextPlugin = require("extract-text-webpack-plugin");
const ManifestPlugin = require('webpack-manifest-plugin'); const ManifestPlugin = require("webpack-manifest-plugin");
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin'); const InterpolateHtmlPlugin = require("react-dev-utils/InterpolateHtmlPlugin");
const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin'); const SWPrecacheWebpackPlugin = require("sw-precache-webpack-plugin");
const eslintFormatter = require('react-dev-utils/eslintFormatter'); const eslintFormatter = require("react-dev-utils/eslintFormatter");
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin'); const ModuleScopePlugin = require("react-dev-utils/ModuleScopePlugin");
const paths = require('./paths'); const paths = require("./paths");
const getClientEnvironment = require('./env'); const getClientEnvironment = require("./env");
// Webpack uses `publicPath` to determine where the app is being served from. // Webpack uses `publicPath` to determine where the app is being served from.
// It requires a trailing slash, or the file assets will get an incorrect path. // It requires a trailing slash, or the file assets will get an incorrect path.
const publicPath = paths.servedPath; const publicPath = paths.servedPath;
// Some apps do not use client-side routing with pushState. // Some apps do not use client-side routing with pushState.
// For these, "homepage" can be set to "." to enable relative asset paths. // For these, "homepage" can be set to "." to enable relative asset paths.
const shouldUseRelativeAssetPaths = publicPath === './'; const shouldUseRelativeAssetPaths = publicPath === "./";
// Source maps are resource heavy and can cause out of memory issue for large source files. // Source maps are resource heavy and can cause out of memory issue for large source files.
const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false'; const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== "false";
// `publicUrl` is just like `publicPath`, but we will provide it to our app // `publicUrl` is just like `publicPath`, but we will provide it to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript. // as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz. // Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
@ -30,12 +30,12 @@ const env = getClientEnvironment(publicUrl);
// Assert this just to be safe. // Assert this just to be safe.
// Development builds of React are slow and not intended for production. // Development builds of React are slow and not intended for production.
if (env.stringified['process.env'].NODE_ENV !== '"production"') { if (env.stringified["process.env"].NODE_ENV !== '"production"') {
throw new Error('Production builds must have NODE_ENV=production.'); throw new Error("Production builds must have NODE_ENV=production.");
} }
// Note: defined here because it will be used more than once. // Note: defined here because it will be used more than once.
const cssFilename = 'static/css/[name].[contenthash:8].css'; const cssFilename = "static/css/[name].[contenthash:8].css";
// ExtractTextPlugin expects the build output to be flat. // ExtractTextPlugin expects the build output to be flat.
// (See https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/27) // (See https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/27)
@ -43,7 +43,7 @@ const cssFilename = 'static/css/[name].[contenthash:8].css';
// To have this structure working with relative paths, we have to use custom options. // To have this structure working with relative paths, we have to use custom options.
const extractTextPluginOptions = shouldUseRelativeAssetPaths const extractTextPluginOptions = shouldUseRelativeAssetPaths
? // Making sure that the publicPath goes back to to build folder. ? // Making sure that the publicPath goes back to to build folder.
{ publicPath: Array(cssFilename.split('/').length).join('../') } {publicPath: Array(cssFilename.split("/").length).join("../")}
: {}; : {};
// This is the production configuration. // This is the production configuration.
@ -54,31 +54,31 @@ module.exports = {
bail: true, bail: true,
// We generate sourcemaps in production. This is slow but gives good results. // We generate sourcemaps in production. This is slow but gives good results.
// You can exclude the *.map files from the build during deployment. // You can exclude the *.map files from the build during deployment.
devtool: shouldUseSourceMap ? 'source-map' : false, devtool: shouldUseSourceMap ? "source-map" : false,
// In production, we only want to load the polyfills and the app code. // In production, we only want to load the polyfills and the app code.
entry: [require.resolve('./polyfills'), paths.appIndexJs], entry: [require.resolve("./polyfills"), paths.appIndexJs],
output: { output: {
// The build folder. // The build folder.
path: paths.appBuild, path: paths.appBuild,
// Generated JS file names (with nested folders). // Generated JS file names (with nested folders).
// There will be one main bundle, and one file per asynchronous chunk. // There will be one main bundle, and one file per asynchronous chunk.
// We don't currently advertise code splitting but Webpack supports it. // We don't currently advertise code splitting but Webpack supports it.
filename: 'static/js/[name].[chunkhash:8].js', filename: "static/js/[name].[chunkhash:8].js",
chunkFilename: 'static/js/[name].[chunkhash:8].chunk.js', chunkFilename: "static/js/[name].[chunkhash:8].chunk.js",
// We inferred the "public path" (such as / or /my-project) from homepage. // We inferred the "public path" (such as / or /my-project) from homepage.
publicPath: publicPath, publicPath: publicPath,
// Point sourcemap entries to original disk location (format as URL on Windows) // Point sourcemap entries to original disk location (format as URL on Windows)
devtoolModuleFilenameTemplate: info => devtoolModuleFilenameTemplate: (info) =>
path path
.relative(paths.appSrc, info.absoluteResourcePath) .relative(paths.appSrc, info.absoluteResourcePath)
.replace(/\\/g, '/'), .replace(/\\/g, "/"),
}, },
resolve: { resolve: {
// This allows you to set a fallback for where Webpack should look for modules. // This allows you to set a fallback for where Webpack should look for modules.
// We placed these paths second because we want `node_modules` to "win" // We placed these paths second because we want `node_modules` to "win"
// if there are any conflicts. This matches Node resolution mechanism. // if there are any conflicts. This matches Node resolution mechanism.
// https://github.com/facebookincubator/create-react-app/issues/253 // https://github.com/facebookincubator/create-react-app/issues/253
modules: ['node_modules', paths.appNodeModules].concat( modules: ["node_modules", paths.appNodeModules].concat(
// It is guaranteed to exist because we tweak it in `env.js` // It is guaranteed to exist because we tweak it in `env.js`
process.env.NODE_PATH.split(path.delimiter).filter(Boolean) process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
), ),
@ -88,12 +88,11 @@ module.exports = {
// https://github.com/facebookincubator/create-react-app/issues/290 // https://github.com/facebookincubator/create-react-app/issues/290
// `web` extension prefixes have been added for better support // `web` extension prefixes have been added for better support
// for React Native Web. // for React Native Web.
extensions: ['.web.js', '.mjs', '.js', '.json', '.web.jsx', '.jsx'], extensions: [".web.js", ".mjs", ".js", ".json", ".web.jsx", ".jsx"],
alias: { alias: {
// Support React Native Web // Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/ // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
'react-native': 'react-native-web', "react-native": "react-native-web",
}, },
plugins: [ plugins: [
// Prevents users from importing files from outside of src/ (or node_modules/). // Prevents users from importing files from outside of src/ (or node_modules/).
@ -115,15 +114,14 @@ module.exports = {
// It's important to do this before Babel processes the JS. // It's important to do this before Babel processes the JS.
{ {
test: /\.(js|jsx|mjs)$/, test: /\.(js|jsx|mjs)$/,
enforce: 'pre', enforce: "pre",
use: [ use: [
{ {
options: { options: {
formatter: eslintFormatter, formatter: eslintFormatter,
eslintPath: require.resolve('eslint'), eslintPath: require.resolve("eslint"),
}, },
loader: require.resolve('eslint-loader'), loader: require.resolve("eslint-loader"),
}, },
], ],
include: paths.appSrc, include: paths.appSrc,
@ -137,19 +135,18 @@ module.exports = {
// assets smaller than specified size as data URLs to avoid requests. // assets smaller than specified size as data URLs to avoid requests.
{ {
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/], test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
loader: require.resolve('url-loader'), loader: require.resolve("url-loader"),
options: { options: {
limit: 10000, limit: 10000,
name: 'static/media/[name].[hash:8].[ext]', name: "static/media/[name].[hash:8].[ext]",
}, },
}, },
// Process JS with Babel. // Process JS with Babel.
{ {
test: /\.(js|jsx|mjs)$/, test: /\.(js|jsx|mjs)$/,
include: paths.appSrc, include: paths.appSrc,
loader: require.resolve('babel-loader'), loader: require.resolve("babel-loader"),
options: { options: {
compact: true, compact: true,
}, },
}, },
@ -171,14 +168,14 @@ module.exports = {
Object.assign( Object.assign(
{ {
fallback: { fallback: {
loader: require.resolve('style-loader'), loader: require.resolve("style-loader"),
options: { options: {
hmr: false, hmr: false,
}, },
}, },
use: [ use: [
{ {
loader: require.resolve('css-loader'), loader: require.resolve("css-loader"),
options: { options: {
importLoaders: 1, importLoaders: 1,
minimize: true, minimize: true,
@ -186,21 +183,21 @@ module.exports = {
}, },
}, },
{ {
loader: require.resolve('postcss-loader'), loader: require.resolve("postcss-loader"),
options: { options: {
// Necessary for external CSS imports to work // Necessary for external CSS imports to work
// https://github.com/facebookincubator/create-react-app/issues/2677 // https://github.com/facebookincubator/create-react-app/issues/2677
ident: 'postcss', ident: "postcss",
plugins: () => [ plugins: () => [
require('postcss-flexbugs-fixes'), require("postcss-flexbugs-fixes"),
autoprefixer({ autoprefixer({
browsers: [ browsers: [
'>1%', ">1%",
'last 4 versions', "last 4 versions",
'Firefox ESR', "Firefox ESR",
'not ie < 9', // React doesn't support IE8 anyway "not ie < 9", // React doesn't support IE8 anyway
], ],
flexbox: 'no-2009', flexbox: "no-2009",
}), }),
], ],
}, },
@ -217,14 +214,14 @@ module.exports = {
// This loader doesn't use a "test" so it will catch all modules // This loader doesn't use a "test" so it will catch all modules
// that fall through the other loaders. // that fall through the other loaders.
{ {
loader: require.resolve('file-loader'), loader: require.resolve("file-loader"),
// Exclude `js` files to keep "css" loader working as it injects // Exclude `js` files to keep "css" loader working as it injects
// it's runtime that would otherwise processed through "file" loader. // it's runtime that would otherwise processed through "file" loader.
// Also exclude `html` and `json` extensions so they get processed // Also exclude `html` and `json` extensions so they get processed
// by webpacks internal loaders. // by webpacks internal loaders.
exclude: [/\.(js|jsx|mjs)$/, /\.html$/, /\.json$/], exclude: [/\.(js|jsx|mjs)$/, /\.html$/, /\.json$/],
options: { options: {
name: 'static/media/[name].[hash:8].[ext]', name: "static/media/[name].[hash:8].[ext]",
}, },
}, },
// ** STOP ** Are you adding a new loader? // ** STOP ** Are you adding a new loader?
@ -291,7 +288,7 @@ module.exports = {
// to their corresponding output file so that tools can pick it up without // to their corresponding output file so that tools can pick it up without
// having to parse `index.html`. // having to parse `index.html`.
new ManifestPlugin({ new ManifestPlugin({
fileName: 'asset-manifest.json', fileName: "asset-manifest.json",
}), }),
// Generate a service worker script that will precache, and keep up to date, // Generate a service worker script that will precache, and keep up to date,
// the HTML & assets that are part of the Webpack build. // the HTML & assets that are part of the Webpack build.
@ -301,13 +298,13 @@ module.exports = {
// If a URL is already hashed by Webpack, then there is no concern // If a URL is already hashed by Webpack, then there is no concern
// about it being stale, and the cache-busting can be skipped. // about it being stale, and the cache-busting can be skipped.
dontCacheBustUrlsMatching: /\.\w{8}\./, dontCacheBustUrlsMatching: /\.\w{8}\./,
filename: 'service-worker.js', filename: "service-worker.js",
logger(message) { logger(message) {
if (message.indexOf('Total precache size is') === 0) { if (message.indexOf("Total precache size is") === 0) {
// This message occurs for every build and is a bit too noisy. // This message occurs for every build and is a bit too noisy.
return; return;
} }
if (message.indexOf('Skipping static resource') === 0) { if (message.indexOf("Skipping static resource") === 0) {
// This message obscures real errors so we ignore it. // This message obscures real errors so we ignore it.
// https://github.com/facebookincubator/create-react-app/issues/2612 // https://github.com/facebookincubator/create-react-app/issues/2612
return; return;
@ -316,7 +313,7 @@ module.exports = {
}, },
minify: true, minify: true,
// For unknown URLs, fallback to the index page // For unknown URLs, fallback to the index page
navigateFallback: publicUrl + '/index.html', navigateFallback: publicUrl + "/index.html",
// Ignores URLs starting from /__ (useful for Firebase): // Ignores URLs starting from /__ (useful for Firebase):
// https://github.com/facebookincubator/create-react-app/issues/2237#issuecomment-302693219 // https://github.com/facebookincubator/create-react-app/issues/2237#issuecomment-302693219
navigateFallbackWhitelist: [/^(?!\/__).*/], navigateFallbackWhitelist: [/^(?!\/__).*/],
@ -333,10 +330,10 @@ module.exports = {
// Some libraries import Node modules but don't use them in the browser. // Some libraries import Node modules but don't use them in the browser.
// Tell Webpack to provide empty mocks for them so importing them works. // Tell Webpack to provide empty mocks for them so importing them works.
node: { node: {
dgram: 'empty', dgram: "empty",
fs: 'empty', fs: "empty",
net: 'empty', net: "empty",
tls: 'empty', tls: "empty",
child_process: 'empty', child_process: "empty",
}, },
}; };

View File

@ -1,13 +1,13 @@
'use strict'; "use strict";
const errorOverlayMiddleware = require('react-dev-utils/errorOverlayMiddleware'); const errorOverlayMiddleware = require("react-dev-utils/errorOverlayMiddleware");
const noopServiceWorkerMiddleware = require('react-dev-utils/noopServiceWorkerMiddleware'); const noopServiceWorkerMiddleware = require("react-dev-utils/noopServiceWorkerMiddleware");
const ignoredFiles = require('react-dev-utils/ignoredFiles'); const ignoredFiles = require("react-dev-utils/ignoredFiles");
const config = require('./webpack.config.dev'); const config = require("./webpack.config.dev");
const paths = require('./paths'); const paths = require("./paths");
const protocol = process.env.HTTPS === 'true' ? 'https' : 'http'; const protocol = process.env.HTTPS === "true" ? "https" : "http";
const host = process.env.HOST || '0.0.0.0'; const host = process.env.HOST || "0.0.0.0";
module.exports = function(proxy, allowedHost) { module.exports = function(proxy, allowedHost) {
return { return {
@ -28,12 +28,12 @@ module.exports = function(proxy, allowedHost) {
// specified the `proxy` setting. Finally, we let you override it if you // specified the `proxy` setting. Finally, we let you override it if you
// really know what you're doing with a special environment variable. // really know what you're doing with a special environment variable.
disableHostCheck: disableHostCheck:
!proxy || process.env.DANGEROUSLY_DISABLE_HOST_CHECK === 'true', !proxy || process.env.DANGEROUSLY_DISABLE_HOST_CHECK === "true",
// Enable gzip compression of generated files. // Enable gzip compression of generated files.
compress: true, compress: true,
// Silence WebpackDevServer's own logs since they're generally not useful. // Silence WebpackDevServer's own logs since they're generally not useful.
// It will still show compile warnings and errors with this setting. // It will still show compile warnings and errors with this setting.
clientLogLevel: 'none', clientLogLevel: "none",
// By default WebpackDevServer serves physical files from current directory // By default WebpackDevServer serves physical files from current directory
// in addition to all the virtual build products that it serves from memory. // in addition to all the virtual build products that it serves from memory.
// This is confusing because those files wont automatically be available in // This is confusing because those files wont automatically be available in
@ -71,7 +71,7 @@ module.exports = function(proxy, allowedHost) {
ignored: ignoredFiles(paths.appSrc), ignored: ignoredFiles(paths.appSrc),
}, },
// Enable HTTPS if the HTTPS environment variable is set to 'true' // Enable HTTPS if the HTTPS environment variable is set to 'true'
https: protocol === 'https', https: protocol === "https",
host: host, host: host,
overlay: false, overlay: false,
historyApiFallback: { historyApiFallback: {

View File

@ -1,30 +1,30 @@
'use strict'; "use strict";
// Do this as the first thing so that any code reading it knows the right env. // Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'production'; process.env.BABEL_ENV = "production";
process.env.NODE_ENV = 'production'; process.env.NODE_ENV = "production";
// Makes the script crash on unhandled rejections instead of silently // Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will // ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code. // terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => { process.on("unhandledRejection", (err) => {
throw err; throw err;
}); });
// Ensure environment variables are read. // Ensure environment variables are read.
require('../config/env'); require("../config/env");
const path = require('path'); const path = require("path");
const chalk = require('chalk'); const chalk = require("chalk");
const fs = require('fs-extra'); const fs = require("fs-extra");
const webpack = require('webpack'); const webpack = require("webpack");
const config = require('../config/webpack.config.prod'); const config = require("../config/webpack.config.prod");
const paths = require('../config/paths'); const paths = require("../config/paths");
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles'); const checkRequiredFiles = require("react-dev-utils/checkRequiredFiles");
const formatWebpackMessages = require('react-dev-utils/formatWebpackMessages'); const formatWebpackMessages = require("react-dev-utils/formatWebpackMessages");
const printHostingInstructions = require('react-dev-utils/printHostingInstructions'); const printHostingInstructions = require("react-dev-utils/printHostingInstructions");
const FileSizeReporter = require('react-dev-utils/FileSizeReporter'); const FileSizeReporter = require("react-dev-utils/FileSizeReporter");
const printBuildError = require('react-dev-utils/printBuildError'); const printBuildError = require("react-dev-utils/printBuildError");
const measureFileSizesBeforeBuild = const measureFileSizesBeforeBuild =
FileSizeReporter.measureFileSizesBeforeBuild; FileSizeReporter.measureFileSizesBeforeBuild;
@ -43,7 +43,7 @@ if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
// First, read the current file sizes in build directory. // First, read the current file sizes in build directory.
// This lets us display how much they changed later. // This lets us display how much they changed later.
measureFileSizesBeforeBuild(paths.appBuild) measureFileSizesBeforeBuild(paths.appBuild)
.then(previousFileSizes => { .then((previousFileSizes) => {
// Remove all content but keep the directory so that // Remove all content but keep the directory so that
// if you're in it, you don't end up in Trash // if you're in it, you don't end up in Trash
fs.emptyDirSync(paths.appBuild); fs.emptyDirSync(paths.appBuild);
@ -53,25 +53,25 @@ measureFileSizesBeforeBuild(paths.appBuild)
return build(previousFileSizes); return build(previousFileSizes);
}) })
.then( .then(
({ stats, previousFileSizes, warnings }) => { ({stats, previousFileSizes, warnings}) => {
if (warnings.length) { if (warnings.length) {
console.log(chalk.yellow('Compiled with warnings.\n')); console.log(chalk.yellow("Compiled with warnings.\n"));
console.log(warnings.join('\n\n')); console.log(warnings.join("\n\n"));
console.log( console.log(
'\nSearch for the ' + "\nSearch for the " +
chalk.underline(chalk.yellow('keywords')) + chalk.underline(chalk.yellow("keywords")) +
' to learn more about each warning.' " to learn more about each warning."
); );
console.log( console.log(
'To ignore, add ' + "To ignore, add " +
chalk.cyan('// eslint-disable-next-line') + chalk.cyan("// eslint-disable-next-line") +
' to the line before.\n' " to the line before.\n"
); );
} else { } else {
console.log(chalk.green('Compiled successfully.\n')); console.log(chalk.green("Compiled successfully.\n"));
} }
console.log('File sizes after gzip:\n'); console.log("File sizes after gzip:\n");
printFileSizesAfterBuild( printFileSizesAfterBuild(
stats, stats,
previousFileSizes, previousFileSizes,
@ -93,8 +93,8 @@ measureFileSizesBeforeBuild(paths.appBuild)
useYarn useYarn
); );
}, },
err => { (err) => {
console.log(chalk.red('Failed to compile.\n')); console.log(chalk.red("Failed to compile.\n"));
printBuildError(err); printBuildError(err);
process.exit(1); process.exit(1);
} }
@ -102,7 +102,7 @@ measureFileSizesBeforeBuild(paths.appBuild)
// Create the production build and print the deployment instructions. // Create the production build and print the deployment instructions.
function build(previousFileSizes) { function build(previousFileSizes) {
console.log('Creating an optimized production build...'); console.log("Creating an optimized production build...");
let compiler = webpack(config); let compiler = webpack(config);
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
@ -117,21 +117,21 @@ function build(previousFileSizes) {
if (messages.errors.length > 1) { if (messages.errors.length > 1) {
messages.errors.length = 1; messages.errors.length = 1;
} }
return reject(new Error(messages.errors.join('\n\n'))); return reject(new Error(messages.errors.join("\n\n")));
} }
if ( if (
process.env.CI && process.env.CI &&
(typeof process.env.CI !== 'string' || (typeof process.env.CI !== "string" ||
process.env.CI.toLowerCase() !== 'false') && process.env.CI.toLowerCase() !== "false") &&
messages.warnings.length messages.warnings.length
) { ) {
console.log( console.log(
chalk.yellow( chalk.yellow(
'\nTreating warnings as errors because process.env.CI = true.\n' + "\nTreating warnings as errors because process.env.CI = true.\n" +
'Most CI servers set it automatically.\n' "Most CI servers set it automatically.\n"
) )
); );
return reject(new Error(messages.warnings.join('\n\n'))); return reject(new Error(messages.warnings.join("\n\n")));
} }
return resolve({ return resolve({
stats, stats,
@ -145,6 +145,6 @@ function build(previousFileSizes) {
function copyPublicFolder() { function copyPublicFolder() {
fs.copySync(paths.appPublic, paths.appBuild, { fs.copySync(paths.appPublic, paths.appBuild, {
dereference: true, dereference: true,
filter: file => file !== paths.appHtml, filter: (file) => file !== paths.appHtml,
}); });
} }

View File

@ -1,35 +1,35 @@
'use strict'; "use strict";
// Do this as the first thing so that any code reading it knows the right env. // Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'development'; process.env.BABEL_ENV = "development";
process.env.NODE_ENV = 'development'; process.env.NODE_ENV = "development";
// Makes the script crash on unhandled rejections instead of silently // Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will // ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code. // terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => { process.on("unhandledRejection", (err) => {
throw err; throw err;
}); });
// Ensure environment variables are read. // Ensure environment variables are read.
require('../config/env'); require("../config/env");
const fs = require('fs'); const fs = require("fs");
const chalk = require('chalk'); const chalk = require("chalk");
const webpack = require('webpack'); const webpack = require("webpack");
const WebpackDevServer = require('webpack-dev-server'); const WebpackDevServer = require("webpack-dev-server");
const clearConsole = require('react-dev-utils/clearConsole'); const clearConsole = require("react-dev-utils/clearConsole");
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles'); const checkRequiredFiles = require("react-dev-utils/checkRequiredFiles");
const { const {
choosePort, choosePort,
createCompiler, createCompiler,
prepareProxy, prepareProxy,
prepareUrls, prepareUrls,
} = require('react-dev-utils/WebpackDevServerUtils'); } = require("react-dev-utils/WebpackDevServerUtils");
const openBrowser = require('react-dev-utils/openBrowser'); const openBrowser = require("react-dev-utils/openBrowser");
const paths = require('../config/paths'); const paths = require("../config/paths");
const config = require('../config/webpack.config.dev'); const config = require("../config/webpack.config.dev");
const createDevServerConfig = require('../config/webpackDevServer.config'); const createDevServerConfig = require("../config/webpackDevServer.config");
const useYarn = fs.existsSync(paths.yarnLockFile); const useYarn = fs.existsSync(paths.yarnLockFile);
const isInteractive = process.stdout.isTTY; const isInteractive = process.stdout.isTTY;
@ -41,7 +41,7 @@ if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
// Tools like Cloud9 rely on this. // Tools like Cloud9 rely on this.
const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000; const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000;
const HOST = process.env.HOST || '0.0.0.0'; const HOST = process.env.HOST || "0.0.0.0";
if (process.env.HOST) { if (process.env.HOST) {
console.log( console.log(
@ -54,19 +54,19 @@ if (process.env.HOST) {
console.log( console.log(
`If this was unintentional, check that you haven't mistakenly set it in your shell.` `If this was unintentional, check that you haven't mistakenly set it in your shell.`
); );
console.log(`Learn more here: ${chalk.yellow('http://bit.ly/2mwWSwH')}`); console.log(`Learn more here: ${chalk.yellow("http://bit.ly/2mwWSwH")}`);
console.log(); console.log();
} }
// We attempt to use the default port but if it is busy, we offer the user to // We attempt to use the default port but if it is busy, we offer the user to
// run on a different port. `choosePort()` Promise resolves to the next free port. // run on a different port. `choosePort()` Promise resolves to the next free port.
choosePort(HOST, DEFAULT_PORT) choosePort(HOST, DEFAULT_PORT)
.then(port => { .then((port) => {
if (port == null) { if (port == null) {
// We have not found a port. // We have not found a port.
return; return;
} }
const protocol = process.env.HTTPS === 'true' ? 'https' : 'http'; const protocol = process.env.HTTPS === "true" ? "https" : "http";
const appName = require(paths.appPackageJson).name; const appName = require(paths.appPackageJson).name;
const urls = prepareUrls(protocol, HOST, port); const urls = prepareUrls(protocol, HOST, port);
// Create a webpack compiler that is configured with custom messages. // Create a webpack compiler that is configured with custom messages.
@ -81,25 +81,25 @@ choosePort(HOST, DEFAULT_PORT)
); );
const devServer = new WebpackDevServer(compiler, serverConfig); const devServer = new WebpackDevServer(compiler, serverConfig);
// Launch WebpackDevServer. // Launch WebpackDevServer.
devServer.listen(port, HOST, err => { devServer.listen(port, HOST, (err) => {
if (err) { if (err) {
return console.log(err); return console.log(err);
} }
if (isInteractive) { if (isInteractive) {
clearConsole(); clearConsole();
} }
console.log(chalk.cyan('Starting the development server...\n')); console.log(chalk.cyan("Starting the development server...\n"));
openBrowser(urls.localUrlForBrowser); openBrowser(urls.localUrlForBrowser);
}); });
['SIGINT', 'SIGTERM'].forEach(function(sig) { ["SIGINT", "SIGTERM"].forEach(function(sig) {
process.on(sig, function() { process.on(sig, function() {
devServer.close(); devServer.close();
process.exit(); process.exit();
}); });
}); });
}) })
.catch(err => { .catch((err) => {
if (err && err.message) { if (err && err.message) {
console.log(err.message); console.log(err.message);
} }

View File

@ -1,27 +1,26 @@
'use strict'; "use strict";
// Do this as the first thing so that any code reading it knows the right env. // Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'test'; process.env.BABEL_ENV = "test";
process.env.NODE_ENV = 'test'; process.env.NODE_ENV = "test";
process.env.PUBLIC_URL = ''; process.env.PUBLIC_URL = "";
// Makes the script crash on unhandled rejections instead of silently // Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will // ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code. // terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => { process.on("unhandledRejection", (err) => {
throw err; throw err;
}); });
// Ensure environment variables are read. // Ensure environment variables are read.
require('../config/env'); require("../config/env");
const jest = require('jest'); const jest = require("jest");
const argv = process.argv.slice(2); const argv = process.argv.slice(2);
// Watch unless on CI or in coverage mode // Watch unless on CI or in coverage mode
if (!process.env.CI && argv.indexOf('--coverage') < 0) { if (!process.env.CI && argv.indexOf("--coverage") < 0) {
argv.push('--watch'); argv.push("--watch");
} }
jest.run(argv); jest.run(argv);

View File

@ -1,9 +1,9 @@
// @flow // @flow
import React, { Component } from 'react'; import React, {Component} from "react";
import data from './data.json'; import data from "./data.json";
import './App.css'; import "./App.css";
import { FileExplorer } from './FileExplorer.js'; import {FileExplorer} from "./FileExplorer.js";
import { UserExplorer } from './UserExplorer.js'; import {UserExplorer} from "./UserExplorer.js";
type AppState = {selectedPath: string, selectedUser: ?string}; type AppState = {selectedPath: string, selectedUser: ?string};
class App extends Component<{}, AppState> { class App extends Component<{}, AppState> {
@ -18,7 +18,6 @@ class App extends Component<{}, AppState> {
return ( return (
<div className="App" style={{backgroundColor: "#eeeeee"}}> <div className="App" style={{backgroundColor: "#eeeeee"}}>
<header <header
style={{ style={{
backgroundColor: "#01579B", backgroundColor: "#01579B",
color: "white", color: "white",
@ -26,11 +25,8 @@ class App extends Component<{}, AppState> {
textAlign: "center", textAlign: "center",
boxShadow: "0px 2px 2px #aeaeae", boxShadow: "0px 2px 2px #aeaeae",
}} }}
> >
<h1 <h1 style={{fontSize: "1.5em"}}>SourceCred Explorer</h1>
style={{fontSize: "1.5em"}}
>SourceCred Explorer
</h1>
</header> </header>
<FileExplorer <FileExplorer
className="file-explorer" className="file-explorer"

View File

@ -1,10 +1,10 @@
import React from 'react'; import React from "react";
import ReactDOM from 'react-dom'; import ReactDOM from "react-dom";
import App from './App'; import App from "./App";
// Check that PropTypes check out. // Check that PropTypes check out.
it('renders without crashing', () => { it("renders without crashing", () => {
const div = document.createElement('div'); const div = document.createElement("div");
ReactDOM.render(<App />, div); ReactDOM.render(<App />, div);
ReactDOM.unmountComponentAtNode(div); ReactDOM.unmountComponentAtNode(div);
}); });

View File

@ -1,12 +1,12 @@
// @flow // @flow
import React, { Component } from 'react'; import React, {Component} from "react";
import {buildTree} from './commitUtils'; import {buildTree} from "./commitUtils";
import type {CommitData, FileTree} from './commitUtils'; import type {CommitData, FileTree} from "./commitUtils";
export class FileExplorer extends Component<{ export class FileExplorer extends Component<{
selectedPath: string, selectedPath: string,
onSelectPath: (newPath: string) => void, onSelectPath: (newPath: string) => void,
data: CommitData, data: CommitData,
}> { }> {
render() { render() {
// within the FileExplorer, paths start with "./", outside they don't // within the FileExplorer, paths start with "./", outside they don't
@ -18,42 +18,46 @@ export class FileExplorer extends Component<{
path = path.slice(2); path = path.slice(2);
} }
this.props.onSelectPath(path); this.props.onSelectPath(path);
} };
return <div className="file-explorer plugin-pane"> return (
<h3 style={{textAlign: "center"}}>File Explorer</h3> <div className="file-explorer plugin-pane">
<div style={{fontFamily: "monospace"}}> <h3 style={{textAlign: "center"}}>File Explorer</h3>
<FileEntry <div style={{fontFamily: "monospace"}}>
alwaysExpand={true} <FileEntry
name="" alwaysExpand={true}
path="." name=""
tree={tree} path="."
onSelectPath={selectPath} tree={tree}
selectedPath={`./${this.props.selectedPath}`} onSelectPath={selectPath}
/> selectedPath={`./${this.props.selectedPath}`}
/>
</div>
</div> </div>
</div> );
} }
} }
class FileEntry extends Component<{ class FileEntry extends Component<
name: string, {
path: string, name: string,
alwaysExpand: bool, path: string,
tree: FileTree, alwaysExpand: boolean,
selectedPath: string, tree: FileTree,
onSelectPath: (newPath: string) => void, selectedPath: string,
}, { onSelectPath: (newPath: string) => void,
expanded: bool, },
}> { {
expanded: boolean,
}
> {
constructor() { constructor() {
super(); super();
this.state = {expanded: false,}; this.state = {expanded: false};
} }
render() { render() {
const topLevels = Object.keys(this.props.tree); const topLevels = Object.keys(this.props.tree);
const subEntries = topLevels.map((x) => const subEntries = topLevels.map((x) => (
<FileEntry <FileEntry
key={x} key={x}
name={x} name={x}
@ -63,25 +67,29 @@ class FileEntry extends Component<{
selectedPath={this.props.selectedPath} selectedPath={this.props.selectedPath}
onSelectPath={this.props.onSelectPath} onSelectPath={this.props.onSelectPath}
/> />
) ));
const isFolder = topLevels.length > 0 && !this.props.alwaysExpand; const isFolder = topLevels.length > 0 && !this.props.alwaysExpand;
const toggleExpand = () => this.setState({expanded: !this.state.expanded}); const toggleExpand = () => this.setState({expanded: !this.state.expanded});
const isSelected = this.props.path === this.props.selectedPath; const isSelected = this.props.path === this.props.selectedPath;
const selectTarget = isSelected ? "." : this.props.path; const selectTarget = isSelected ? "." : this.props.path;
const onClick = () => this.props.onSelectPath(selectTarget); const onClick = () => this.props.onSelectPath(selectTarget);
return <div return (
className={isSelected ? 'selected-path' : ''} <div
className={isSelected ? "selected-path" : ""}
style={{marginLeft: this.props.path === "." ? 0 : 25}} style={{marginLeft: this.props.path === "." ? 0 : 25}}
> >
<p>
<p> {isFolder && (
{isFolder && <button <button style={{marginRight: 3}} onClick={toggleExpand}>
style={{marginRight: 3}} »
onClick={toggleExpand}>»</button>} </button>
<a href="javascript: void 0" onClick={onClick}>{this.props.name}</a> )}
</p> <a href="javascript: void 0" onClick={onClick}>
{(this.state.expanded || this.props.alwaysExpand) && subEntries} {this.props.name}
</div> </a>
</p>
{(this.state.expanded || this.props.alwaysExpand) && subEntries}
</div>
);
} }
} }

View File

@ -1,7 +1,7 @@
// @flow // @flow
import React, { Component } from 'react'; import React, {Component} from "react";
import {commitWeight, userWeightForPath} from './commitUtils'; import {commitWeight, userWeightForPath} from "./commitUtils";
import type {CommitData, FileTree} from './commitUtils'; import type {CommitData, FileTree} from "./commitUtils";
export class UserExplorer extends Component<{ export class UserExplorer extends Component<{
selectedPath: string, selectedPath: string,
@ -9,42 +9,41 @@ export class UserExplorer extends Component<{
onSelectUser: (newUser: string) => void, onSelectUser: (newUser: string) => void,
data: CommitData, data: CommitData,
}> { }> {
render() { render() {
const weights = userWeightForPath(this.props.selectedPath, this.props.data, commitWeight); const weights = userWeightForPath(
const sortedUserWeightTuples = this.props.selectedPath,
Object.keys(weights) this.props.data,
.map(k => [k, weights[k]]) commitWeight
.sort((a,b) => b[1] - a[1]); );
const entries = sortedUserWeightTuples.map(authorWeight => { const sortedUserWeightTuples = Object.keys(weights)
.map((k) => [k, weights[k]])
.sort((a, b) => b[1] - a[1]);
const entries = sortedUserWeightTuples.map((authorWeight) => {
const [author, weight] = authorWeight; const [author, weight] = authorWeight;
return <UserEntry userId={author} weight={weight} key={author}/> return <UserEntry userId={author} weight={weight} key={author} />;
}); });
return <div return (
className="user-explorer plugin-pane" <div className="user-explorer plugin-pane">
> <h3 style={{textAlign: "center"}}> User Explorer </h3>
<h3 style={{textAlign: "center"}}> User Explorer </h3> <div style={{marginLeft: 8, marginRight: 8}}>{entries}</div>
<div style={{marginLeft: 8, marginRight: 8}}>
{entries}
</div> </div>
</div> );
} }
} }
/** /**
* Record the cred earned by the user in a given scope. * Record the cred earned by the user in a given scope.
*/ */
class UserEntry extends Component<{ class UserEntry extends Component<{
userId: string, userId: string,
weight: number, weight: number,
}> { }> {
render() { render() {
return <div className="user-entry"> return (
<span> {this.props.userId} </span> <div className="user-entry">
<span> {this.props.weight.toFixed(1)} </span> <span> {this.props.userId} </span>
</div> <span> {this.props.weight.toFixed(1)} </span>
</div>
);
} }
} }

View File

@ -1,27 +1,27 @@
// @flow // @flow
import PropTypes from 'prop-types'; import PropTypes from "prop-types";
export type CommitData = { export type CommitData = {
// TODO improve variable names // TODO improve variable names
fileToCommits: {[filename: string]: string[]}; fileToCommits: {[filename: string]: string[]},
commits: {[commithash: string]: Commit}; commits: {[commithash: string]: Commit},
} };
type Commit = { type Commit = {
author: string; author: string,
stats: {[filename: string]: FileStats}; stats: {[filename: string]: FileStats},
} };
type FileStats = { type FileStats = {
lines: number; lines: number,
added: number; added: number,
deleted: number; deleted: number,
} };
export function commitWeight(commit: Commit, filepath: string): number { export function commitWeight(commit: Commit, filepath: string): number {
// hack - GitPython encodes renames in the filepath. ignore for now. // hack - GitPython encodes renames in the filepath. ignore for now.
if (filepath.indexOf('=>') !== -1) { if (filepath.indexOf("=>") !== -1) {
return 0; return 0;
} }
return Math.sqrt(commit.stats[filepath].lines); return Math.sqrt(commit.stats[filepath].lines);
@ -29,10 +29,14 @@ export function commitWeight(commit: Commit, filepath: string): number {
function allSelectedFiles(filepath: string, data: CommitData): string[] { function allSelectedFiles(filepath: string, data: CommitData): string[] {
const fnames = Object.keys(data.fileToCommits); const fnames = Object.keys(data.fileToCommits);
return fnames.filter(x => x.startsWith(filepath)); return fnames.filter((x) => x.startsWith(filepath));
} }
function *userWeights(files: string[], data: CommitData, weightFn: WeightFn): Iterable<[string, number]> { function* userWeights(
files: string[],
data: CommitData,
weightFn: WeightFn
): Iterable<[string, number]> {
for (const file of files) { for (const file of files) {
for (const commitHash of data.fileToCommits[file]) { for (const commitHash of data.fileToCommits[file]) {
const commit = data.commits[commitHash]; const commit = data.commits[commitHash];
@ -48,15 +52,19 @@ function *userWeights(files: string[], data: CommitData, weightFn: WeightFn): It
} }
} }
/** /**
* A weight function determines how much commit contributes to the importance * A weight function determines how much commit contributes to the importance
* of a particular file. For instance, a weight function might be defined as, * of a particular file. For instance, a weight function might be defined as,
* the number of lines changed in filepath in commit commit, or 1 if * the number of lines changed in filepath in commit commit, or 1 if
* filepath was changed in commit, else 0. * filepath was changed in commit, else 0.
*/ */
type WeightFn = (commit: Commit, filepath: string) => number; type WeightFn = (commit: Commit, filepath: string) => number;
export function userWeightForPath(path: string, data: CommitData, weightFn: WeightFn): {[string]: number} { export function userWeightForPath(
path: string,
data: CommitData,
weightFn: WeightFn
): {[string]: number} {
const userWeightMap = {}; const userWeightMap = {};
const files = allSelectedFiles(path, data); const files = allSelectedFiles(path, data);
for (const [user, weight] of userWeights(files, data, weightFn)) { for (const [user, weight] of userWeights(files, data, weightFn)) {
@ -78,15 +86,15 @@ export function buildTree(fileNames: string[]): FileTree {
function _buildTree(sortedFileNames: string[]): FileTree { function _buildTree(sortedFileNames: string[]): FileTree {
const topLevelBuckets: {[root: string]: string[]} = {}; const topLevelBuckets: {[root: string]: string[]} = {};
for (const fileName of sortedFileNames) { for (const fileName of sortedFileNames) {
const topLevel = fileName.split('/')[0]; const topLevel = fileName.split("/")[0];
const remainder = fileName const remainder = fileName
.split('/') .split("/")
.slice(1) .slice(1)
.join('/'); .join("/");
if (topLevelBuckets[topLevel] == null) { if (topLevelBuckets[topLevel] == null) {
topLevelBuckets[topLevel] = []; topLevelBuckets[topLevel] = [];
} }
if (remainder !== '') { if (remainder !== "") {
topLevelBuckets[topLevel].push(remainder); topLevelBuckets[topLevel].push(remainder);
} }
} }

View File

@ -1,28 +1,28 @@
// @flow // @flow
import {userWeightForPath, buildTree} from './commitUtils'; import {userWeightForPath, buildTree} from "./commitUtils";
const exampleData = { const exampleData = {
fileToCommits: { fileToCommits: {
'foo.txt': ['1'], "foo.txt": ["1"],
'bar.txt': ['1', '2'] "bar.txt": ["1", "2"],
}, },
commits: { commits: {
'1': { "1": {
'author': 'dandelionmane', author: "dandelionmane",
'stats': { stats: {
'foo.txt': {'lines': 5, 'added': 3, 'deleted': 2}, "foo.txt": {lines: 5, added: 3, deleted: 2},
'bar.txt': {'lines': 100, 'added': 100, 'deleted': 0} "bar.txt": {lines: 100, added: 100, deleted: 0},
} },
}, },
'2': { "2": {
'author': 'wchargin', author: "wchargin",
'stats': { stats: {
'bar.txt': {'lines': 100, 'added': 50, 'deleted': 50}, "bar.txt": {lines: 100, added: 50, deleted: 50},
} },
}, },
}, },
authors: ['dandelionmane', 'wchargin'] authors: ["dandelionmane", "wchargin"],
} };
const emptyData = {fileToCommits: {}, commits: {}, authors: []}; const emptyData = {fileToCommits: {}, commits: {}, authors: []};
@ -30,41 +30,45 @@ function weightByNumFilesTouched(commit, filepath) {
return 1; return 1;
} }
describe('userWeightForPath', () => { describe("userWeightForPath", () => {
it('works on empty data', () => { it("works on empty data", () => {
const actual = userWeightForPath('', emptyData, weightByNumFilesTouched); const actual = userWeightForPath("", emptyData, weightByNumFilesTouched);
const expected = {}; const expected = {};
expect(actual).toEqual(expected); expect(actual).toEqual(expected);
}); });
it('works in simple case', () => { it("works in simple case", () => {
const actual = userWeightForPath('', exampleData, weightByNumFilesTouched); const actual = userWeightForPath("", exampleData, weightByNumFilesTouched);
const expected = {'dandelionmane': 2, 'wchargin': 1}; const expected = {dandelionmane: 2, wchargin: 1};
expect(actual).toEqual(expected); expect(actual).toEqual(expected);
}); });
it('respects file paths', () => { it("respects file paths", () => {
const actual = userWeightForPath('bar.txt', exampleData, weightByNumFilesTouched); const actual = userWeightForPath(
const expected = {'dandelionmane': 1, 'wchargin': 1}; "bar.txt",
exampleData,
weightByNumFilesTouched
);
const expected = {dandelionmane: 1, wchargin: 1};
expect(actual).toEqual(expected); expect(actual).toEqual(expected);
}); });
it('uses custom weight function', () => { it("uses custom weight function", () => {
const myWeight = (commit, filepath) => commit.stats[filepath].lines; const myWeight = (commit, filepath) => commit.stats[filepath].lines;
const actual = userWeightForPath('', exampleData, myWeight); const actual = userWeightForPath("", exampleData, myWeight);
const expected = {'dandelionmane': 105, 'wchargin': 100}; const expected = {dandelionmane: 105, wchargin: 100};
expect(actual).toEqual(expected); expect(actual).toEqual(expected);
}) });
}) });
describe('buildTree', () => { describe("buildTree", () => {
it('handles empty tree', () => { it("handles empty tree", () => {
expect(buildTree([])).toEqual({}); expect(buildTree([])).toEqual({});
}); });
it('handles trees', () => { it("handles trees", () => {
const names = ['foo', 'bar/zod', 'bar/zoink']; const names = ["foo", "bar/zod", "bar/zoink"];
const expected = {'foo': {}, 'bar': {'zod': {}, 'zoink': {}}}; const expected = {foo: {}, bar: {zod: {}, zoink: {}}};
expect(buildTree(names)).toEqual(expected); expect(buildTree(names)).toEqual(expected);
}); });
}); });

View File

@ -1,8 +1,8 @@
import React from 'react'; import React from "react";
import ReactDOM from 'react-dom'; import ReactDOM from "react-dom";
import './index.css'; import "./index.css";
import App from './App'; import App from "./App";
import registerServiceWorker from './registerServiceWorker'; import registerServiceWorker from "./registerServiceWorker";
ReactDOM.render(<App />, document.getElementById('root')); ReactDOM.render(<App />, document.getElementById("root"));
registerServiceWorker(); registerServiceWorker();

View File

@ -9,9 +9,9 @@
// This link also includes instructions on opting out of this behavior. // This link also includes instructions on opting out of this behavior.
const isLocalhost = Boolean( const isLocalhost = Boolean(
window.location.hostname === 'localhost' || window.location.hostname === "localhost" ||
// [::1] is the IPv6 localhost address. // [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' || window.location.hostname === "[::1]" ||
// 127.0.0.1/8 is considered localhost for IPv4. // 127.0.0.1/8 is considered localhost for IPv4.
window.location.hostname.match( window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
@ -19,7 +19,7 @@ const isLocalhost = Boolean(
); );
export default function register() { export default function register() {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { if (process.env.NODE_ENV === "production" && "serviceWorker" in navigator) {
// The URL constructor is available in all browsers that support SW. // The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location); const publicUrl = new URL(process.env.PUBLIC_URL, window.location);
if (publicUrl.origin !== window.location.origin) { if (publicUrl.origin !== window.location.origin) {
@ -29,7 +29,7 @@ export default function register() {
return; return;
} }
window.addEventListener('load', () => { window.addEventListener("load", () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) { if (isLocalhost) {
@ -40,8 +40,8 @@ export default function register() {
// service worker/PWA documentation. // service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => { navigator.serviceWorker.ready.then(() => {
console.log( console.log(
'This web app is being served cache-first by a service ' + "This web app is being served cache-first by a service " +
'worker. To learn more, visit https://goo.gl/SC7cgQ' "worker. To learn more, visit https://goo.gl/SC7cgQ"
); );
}); });
} else { } else {
@ -55,43 +55,43 @@ export default function register() {
function registerValidSW(swUrl) { function registerValidSW(swUrl) {
navigator.serviceWorker navigator.serviceWorker
.register(swUrl) .register(swUrl)
.then(registration => { .then((registration) => {
registration.onupdatefound = () => { registration.onupdatefound = () => {
const installingWorker = registration.installing; const installingWorker = registration.installing;
installingWorker.onstatechange = () => { installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') { if (installingWorker.state === "installed") {
if (navigator.serviceWorker.controller) { if (navigator.serviceWorker.controller) {
// At this point, the old content will have been purged and // At this point, the old content will have been purged and
// the fresh content will have been added to the cache. // the fresh content will have been added to the cache.
// It's the perfect time to display a "New content is // It's the perfect time to display a "New content is
// available; please refresh." message in your web app. // available; please refresh." message in your web app.
console.log('New content is available; please refresh.'); console.log("New content is available; please refresh.");
} else { } else {
// At this point, everything has been precached. // At this point, everything has been precached.
// It's the perfect time to display a // It's the perfect time to display a
// "Content is cached for offline use." message. // "Content is cached for offline use." message.
console.log('Content is cached for offline use.'); console.log("Content is cached for offline use.");
} }
} }
}; };
}; };
}) })
.catch(error => { .catch((error) => {
console.error('Error during service worker registration:', error); console.error("Error during service worker registration:", error);
}); });
} }
function checkValidServiceWorker(swUrl) { function checkValidServiceWorker(swUrl) {
// Check if the service worker can be found. If it can't reload the page. // Check if the service worker can be found. If it can't reload the page.
fetch(swUrl) fetch(swUrl)
.then(response => { .then((response) => {
// Ensure service worker exists, and that we really are getting a JS file. // Ensure service worker exists, and that we really are getting a JS file.
if ( if (
response.status === 404 || response.status === 404 ||
response.headers.get('content-type').indexOf('javascript') === -1 response.headers.get("content-type").indexOf("javascript") === -1
) { ) {
// No service worker found. Probably a different app. Reload the page. // No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => { navigator.serviceWorker.ready.then((registration) => {
registration.unregister().then(() => { registration.unregister().then(() => {
window.location.reload(); window.location.reload();
}); });
@ -103,14 +103,14 @@ function checkValidServiceWorker(swUrl) {
}) })
.catch(() => { .catch(() => {
console.log( console.log(
'No internet connection found. App is running in offline mode.' "No internet connection found. App is running in offline mode."
); );
}); });
} }
export function unregister() { export function unregister() {
if ('serviceWorker' in navigator) { if ("serviceWorker" in navigator) {
navigator.serviceWorker.ready.then(registration => { navigator.serviceWorker.ready.then((registration) => {
registration.unregister(); registration.unregister();
}); });
} }