This commit is contained in:
MICHAEL JACKSON
2017-11-25 21:19:55 -08:00
parent 758b420297
commit 51f3bca3fb
13 changed files with 476 additions and 448 deletions

View File

@ -1,38 +1,38 @@
'use strict'; "use strict"
// 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
// injected into the application via DefinePlugin in Webpack configuration. // injected into the application via DefinePlugin in Webpack configuration.
var REACT_APP = /^REACT_APP_/i; var REACT_APP = /^REACT_APP_/i
function getClientEnvironment(publicUrl) { function getClientEnvironment(publicUrl) {
var raw = Object var raw = Object.keys(process.env)
.keys(process.env)
.filter(key => REACT_APP.test(key)) .filter(key => REACT_APP.test(key))
.reduce((env, key) => { .reduce(
env[key] = process.env[key]; (env, key) => {
return env; env[key] = process.env[key]
}, { return env
// Useful for determining whether were running in production mode. },
// Most importantly, it switches React into the correct mode. {
'NODE_ENV': process.env.NODE_ENV || 'development', // Useful for determining whether were running in production mode.
// Useful for resolving the correct path to static assets in `public`. // Most importantly, it switches React into the correct mode.
// For example, <img src={process.env.PUBLIC_URL + '/img/logo.png'} />. NODE_ENV: process.env.NODE_ENV || "development",
// This should only be used as an escape hatch. Normally you would put // Useful for resolving the correct path to static assets in `public`.
// images into the `src` and `import` them in code to get their paths. // For example, <img src={process.env.PUBLIC_URL + '/img/logo.png'} />.
'PUBLIC_URL': publicUrl // This should only be used as an escape hatch. Normally you would put
}); // images into the `src` and `import` them in code to get their paths.
PUBLIC_URL: publicUrl
}
)
// Stringify all values so we can feed into Webpack DefinePlugin // Stringify all values so we can feed into Webpack DefinePlugin
var stringified = { var stringified = {
'process.env': Object "process.env": Object.keys(raw).reduce((env, key) => {
.keys(raw) env[key] = JSON.stringify(raw[key])
.reduce((env, key) => { return env
env[key] = JSON.stringify(raw[key]); }, {})
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/tutorial-webpack.html // http://facebook.github.io/jest/docs/tutorial-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,12 +1,12 @@
'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/tutorial-webpack.html // http://facebook.github.io/jest/docs/tutorial-webpack.html
module.exports = { module.exports = {
process(src, filename) { process(src, filename) {
return 'module.exports = ' + JSON.stringify(path.basename(filename)) + ';'; return "module.exports = " + JSON.stringify(path.basename(filename)) + ";"
}, }
}; }

View File

@ -1,14 +1,14 @@
'use strict'; "use strict"
var path = require('path'); var path = require("path")
var fs = require('fs'); var fs = require("fs")
var url = require('url'); var 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
var appDirectory = fs.realpathSync(process.cwd()); var appDirectory = fs.realpathSync(process.cwd())
function resolveApp(relativePath) { function resolveApp(relativePath) {
return path.resolve(appDirectory, relativePath); return path.resolve(appDirectory, relativePath)
} }
// We support resolving modules according to `NODE_PATH`. // We support resolving modules according to `NODE_PATH`.
@ -26,27 +26,27 @@ function resolveApp(relativePath) {
// Otherwise, we risk importing Node.js core modules into an app instead of Webpack shims. // Otherwise, we risk importing Node.js core modules into an app instead of Webpack shims.
// https://github.com/facebookincubator/create-react-app/issues/1023#issuecomment-265344421 // https://github.com/facebookincubator/create-react-app/issues/1023#issuecomment-265344421
var nodePaths = (process.env.NODE_PATH || '') var nodePaths = (process.env.NODE_PATH || "")
.split(process.platform === 'win32' ? ';' : ':') .split(process.platform === "win32" ? ";" : ":")
.filter(Boolean) .filter(Boolean)
.filter(folder => !path.isAbsolute(folder)) .filter(folder => !path.isAbsolute(folder))
.map(resolveApp); .map(resolveApp)
var envPublicUrl = process.env.PUBLIC_URL; var envPublicUrl = process.env.PUBLIC_URL
function ensureSlash(path, needsSlash) { function ensureSlash(path, needsSlash) {
var hasSlash = path.endsWith('/'); var 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) {
return path + '/'; return path + "/"
} else { } else {
return path; return path
} }
} }
function getPublicUrl(appPackageJson) { function getPublicUrl(appPackageJson) {
return envPublicUrl || require(appPackageJson).homepage; return 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
@ -56,25 +56,23 @@ function getPublicUrl(appPackageJson) {
// We can't use a relative path in HTML because we don't want to load something // We can't use a relative path in HTML because we don't want to load something
// like /todos/42/static/js/bundle.7289d.js. We have to know the root. // like /todos/42/static/js/bundle.7289d.js. We have to know the root.
function getServedPath(appPackageJson) { function getServedPath(appPackageJson) {
var publicUrl = getPublicUrl(appPackageJson); var publicUrl = getPublicUrl(appPackageJson)
var servedUrl = envPublicUrl || ( var servedUrl = envPublicUrl || (publicUrl ? url.parse(publicUrl).pathname : "/")
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 = {
appBuild: resolveApp('build'), appBuild: resolveApp("build"),
appPublic: resolveApp('public'), appPublic: resolveApp("public"),
appHtml: resolveApp('public/index.html'), appHtml: resolveApp("public/index.html"),
appIndexJs: resolveApp('client/index.js'), appIndexJs: resolveApp("client/index.js"),
appPackageJson: resolveApp('package.json'), appPackageJson: resolveApp("package.json"),
appSrc: resolveApp('client'), appSrc: resolveApp("client"),
yarnLockFile: resolveApp('yarn.lock'), yarnLockFile: resolveApp("yarn.lock"),
testsSetup: resolveApp('client/setupTests.js'), testsSetup: resolveApp("client/setupTests.js"),
appNodeModules: resolveApp('node_modules'), appNodeModules: resolveApp("node_modules"),
nodePaths: nodePaths, nodePaths: nodePaths,
publicUrl: getPublicUrl(resolveApp('package.json')), publicUrl: getPublicUrl(resolveApp("package.json")),
servedPath: getServedPath(resolveApp('package.json')) servedPath: getServedPath(resolveApp("package.json"))
}; }

View File

@ -1,16 +1,16 @@
'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")

View File

@ -1,25 +1,23 @@
'use strict'; "use strict"
var autoprefixer = require('autoprefixer');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
var InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
var WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
var getClientEnvironment = require('./env');
var paths = require('./paths');
var autoprefixer = require("autoprefixer")
var webpack = require("webpack")
var HtmlWebpackPlugin = require("html-webpack-plugin")
var CaseSensitivePathsPlugin = require("case-sensitive-paths-webpack-plugin")
var InterpolateHtmlPlugin = require("react-dev-utils/InterpolateHtmlPlugin")
var WatchMissingNodeModulesPlugin = require("react-dev-utils/WatchMissingNodeModulesPlugin")
var getClientEnvironment = require("./env")
var 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.
var publicPath = '/'; var 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.
var publicUrl = ''; var publicUrl = ""
// Get environment variables to inject into our app. // Get environment variables to inject into our app.
var env = getClientEnvironment(publicUrl); var env = getClientEnvironment(publicUrl)
// This is the development configuration. // This is the development configuration.
// It is focused on developer experience and fast rebuilds. // It is focused on developer experience and fast rebuilds.
@ -27,7 +25,7 @@ var 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.
@ -42,9 +40,9 @@ 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"),
// We ship a few polyfills by default: // We ship a few polyfills by default:
require.resolve('./polyfills'), require.resolve("./polyfills"),
// 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
@ -59,7 +57,7 @@ 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",
// 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
}, },
@ -74,22 +72,22 @@ module.exports = {
// We also include JSX as a common component filename extension to support // We also include JSX as a common component filename extension to support
// some tools, although we do not recommend using it, see: // some tools, although we do not recommend using it, see:
// https://github.com/facebookincubator/create-react-app/issues/290 // https://github.com/facebookincubator/create-react-app/issues/290
extensions: ['.js', '.json', '.jsx', ''], extensions: [".js", ".json", ".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"
} }
}, },
module: { module: {
// First, run the linter. // First, run the linter.
// It's important to do this before Babel processes the JS. // It's important to do this before Babel processes the JS.
preLoaders: [ preLoaders: [
{ {
test: /\.(js|jsx)$/, test: /\.(js|jsx)$/,
loader: 'eslint', loader: "eslint",
include: paths.appSrc, include: paths.appSrc
} }
], ],
loaders: [ loaders: [
@ -116,19 +114,18 @@ module.exports = {
/\.svg$/, /\.svg$/,
/\.md$/ /\.md$/
], ],
loader: 'url', loader: "url",
query: { query: {
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)$/, test: /\.(js|jsx)$/,
include: paths.appSrc, include: paths.appSrc,
loader: 'babel', loader: "babel",
query: { query: {
// 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.
@ -142,44 +139,44 @@ module.exports = {
// in development "style" loader enables hot editing of CSS. // in development "style" loader enables hot editing of CSS.
{ {
test: /\.css$/, test: /\.css$/,
loader: 'style!css?importLoaders=1!postcss' loader: "style!css?importLoaders=1!postcss"
}, },
// JSON is not enabled by default in Webpack but both Node and Browserify // JSON is not enabled by default in Webpack but both Node and Browserify
// allow it implicitly so we also enable it. // allow it implicitly so we also enable it.
{ {
test: /\.json$/, test: /\.json$/,
loader: 'json' loader: "json"
}, },
// "file" loader for svg // "file" loader for svg
{ {
test: /\.svg$/, test: /\.svg$/,
loader: 'file', loader: "file",
query: { query: {
name: '_static/media/[name].[hash:8].[ext]' name: "_static/media/[name].[hash:8].[ext]"
} }
}, },
// HTML loader for Markdown files. // HTML loader for Markdown files.
{ {
test: /\.md$/, test: /\.md$/,
loader: 'html!markdown' loader: "html!markdown"
} }
// ** STOP ** Are you adding a new loader? // ** STOP ** Are you adding a new loader?
// Remember to add the new extension(s) to the "url" loader exclusion list. // Remember to add the new extension(s) to the "url" loader exclusion list.
] ]
}, },
// We use PostCSS for autoprefixing only. // We use PostCSS for autoprefixing only.
postcss: function() { postcss: function() {
return [ return [
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
] ]
}), })
]; ]
}, },
plugins: [ plugins: [
// Makes some environment variables available in index.html. // Makes some environment variables available in index.html.
@ -190,7 +187,7 @@ module.exports = {
// Generates an `index.html` file with the <script> injected. // Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin({ new HtmlWebpackPlugin({
inject: true, inject: true,
template: paths.appHtml, template: paths.appHtml
}), }),
// Makes some environment variables available to the JS code, for example: // Makes some environment variables available to the JS code, for example:
// if (process.env.NODE_ENV === 'development') { ... }. See `./env.js`. // if (process.env.NODE_ENV === 'development') { ... }. See `./env.js`.
@ -210,8 +207,8 @@ 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: {
fs: 'empty', fs: "empty",
net: 'empty', net: "empty",
tls: 'empty' tls: "empty"
} }
}; }

View File

@ -1,46 +1,44 @@
'use strict'; "use strict"
var autoprefixer = require('autoprefixer');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var ManifestPlugin = require('webpack-manifest-plugin');
var InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
var paths = require('./paths');
var getClientEnvironment = require('./env');
var autoprefixer = require("autoprefixer")
var webpack = require("webpack")
var HtmlWebpackPlugin = require("html-webpack-plugin")
var ExtractTextPlugin = require("extract-text-webpack-plugin")
var ManifestPlugin = require("webpack-manifest-plugin")
var InterpolateHtmlPlugin = require("react-dev-utils/InterpolateHtmlPlugin")
var paths = require("./paths")
var 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.
var publicPath = paths.servedPath; var 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.
var shouldUseRelativeAssetPaths = publicPath === './'; var shouldUseRelativeAssetPaths = 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_URL%/xyz looks better than %PUBLIC_URL%xyz. // Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
var publicUrl = publicPath.slice(0, -1); var publicUrl = publicPath.slice(0, -1)
// Get environment variables to inject into our app. // Get environment variables to inject into our app.
var env = getClientEnvironment(publicUrl); var 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)
// However, our output is structured with css, js and media folders. // However, our output is structured with css, js and media folders.
// 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("../") }
: undefined; : undefined
// This is the production configuration. // This is the production configuration.
// It compiles slowly and is focused on producing a fast and minimal bundle. // It compiles slowly and is focused on producing a fast and minimal bundle.
@ -50,20 +48,17 @@ 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: 'source-map', devtool: "source-map",
// 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: [ entry: [require.resolve("./polyfills"), paths.appIndexJs],
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
}, },
@ -78,21 +73,21 @@ module.exports = {
// We also include JSX as a common component filename extension to support // We also include JSX as a common component filename extension to support
// some tools, although we do not recommend using it, see: // some tools, although we do not recommend using it, see:
// https://github.com/facebookincubator/create-react-app/issues/290 // https://github.com/facebookincubator/create-react-app/issues/290
extensions: ['.js', '.json', '.jsx', ''], extensions: [".js", ".json", ".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"
} }
}, },
module: { module: {
// First, run the linter. // First, run the linter.
// It's important to do this before Babel processes the JS. // It's important to do this before Babel processes the JS.
preLoaders: [ preLoaders: [
{ {
test: /\.(js|jsx)$/, test: /\.(js|jsx)$/,
loader: 'eslint', loader: "eslint",
include: paths.appSrc include: paths.appSrc
} }
], ],
@ -106,26 +101,18 @@ module.exports = {
// "url" loader embeds assets smaller than specified size as data URLs to avoid requests. // "url" loader embeds assets smaller than specified size as data URLs to avoid requests.
// Otherwise, it acts like the "file" loader. // Otherwise, it acts like the "file" loader.
{ {
exclude: [ exclude: [/\.html$/, /\.(js|jsx)$/, /\.css$/, /\.json$/, /\.svg$/, /\.md$/],
/\.html$/, loader: "url",
/\.(js|jsx)$/,
/\.css$/,
/\.json$/,
/\.svg$/,
/\.md$/
],
loader: 'url',
query: { query: {
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)$/, test: /\.(js|jsx)$/,
include: paths.appSrc, include: paths.appSrc,
loader: 'babel', loader: "babel"
}, },
// The notation here is somewhat confusing. // The notation here is somewhat confusing.
// "postcss" loader applies autoprefixer to our CSS. // "postcss" loader applies autoprefixer to our CSS.
@ -142,8 +129,8 @@ module.exports = {
{ {
test: /\.css$/, test: /\.css$/,
loader: ExtractTextPlugin.extract( loader: ExtractTextPlugin.extract(
'style', "style",
'css?importLoaders=1!postcss', "css?importLoaders=1!postcss",
extractTextPluginOptions extractTextPluginOptions
) )
// Note: this won't work without `new ExtractTextPlugin()` in `plugins`. // Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
@ -152,38 +139,38 @@ module.exports = {
// allow it implicitly so we also enable it. // allow it implicitly so we also enable it.
{ {
test: /\.json$/, test: /\.json$/,
loader: 'json' loader: "json"
}, },
// "file" loader for svg // "file" loader for svg
{ {
test: /\.svg$/, test: /\.svg$/,
loader: 'file', loader: "file",
query: { query: {
name: '_static/media/[name].[hash:8].[ext]' name: "_static/media/[name].[hash:8].[ext]"
} }
}, },
// HTML loader for Markdown files. // HTML loader for Markdown files.
{ {
test: /\.md$/, test: /\.md$/,
loader: 'html!markdown' loader: "html!markdown"
} }
// ** STOP ** Are you adding a new loader? // ** STOP ** Are you adding a new loader?
// Remember to add the new extension(s) to the "url" loader exclusion list. // Remember to add the new extension(s) to the "url" loader exclusion list.
] ]
}, },
// We use PostCSS for autoprefixing only. // We use PostCSS for autoprefixing only.
postcss: function() { postcss: function() {
return [ return [
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
] ]
}), })
]; ]
}, },
plugins: [ plugins: [
// Makes some environment variables available in index.html. // Makes some environment variables available in index.html.
@ -238,14 +225,14 @@ 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"
}) })
], ],
// 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: {
fs: 'empty', fs: "empty",
net: 'empty', net: "empty",
tls: 'empty' tls: "empty"
} }
}; }

View File

@ -1,31 +1,31 @@
'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.NODE_ENV = 'production'; process.env.NODE_ENV = "production"
// Load environment variables from .env file. Suppress warnings using silent // Load environment variables from .env file. Suppress warnings using silent
// if this file is missing. dotenv will never modify any environment variables // if this file is missing. dotenv will never modify any environment variables
// that have already been set. // that have already been set.
// https://github.com/motdotla/dotenv // https://github.com/motdotla/dotenv
require('dotenv').config({silent: true}); require("dotenv").config({ silent: true })
var chalk = require('chalk'); var chalk = require("chalk")
var fs = require('fs-extra'); var fs = require("fs-extra")
var path = require('path'); var path = require("path")
var url = require('url'); var url = require("url")
var webpack = require('webpack'); var webpack = require("webpack")
var config = require('../config/webpack.config.prod'); var config = require("../config/webpack.config.prod")
var paths = require('../config/paths'); var paths = require("../config/paths")
var checkRequiredFiles = require('react-dev-utils/checkRequiredFiles'); var checkRequiredFiles = require("react-dev-utils/checkRequiredFiles")
var FileSizeReporter = require('react-dev-utils/FileSizeReporter'); var FileSizeReporter = require("react-dev-utils/FileSizeReporter")
var measureFileSizesBeforeBuild = FileSizeReporter.measureFileSizesBeforeBuild; var measureFileSizesBeforeBuild = FileSizeReporter.measureFileSizesBeforeBuild
var printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild; var printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild
var useYarn = fs.existsSync(paths.yarnLockFile); var useYarn = fs.existsSync(paths.yarnLockFile)
// Warn and crash if required files are missing // Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) { if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
process.exit(1); process.exit(1)
} }
// First, read the current file sizes in build directory. // First, read the current file sizes in build directory.
@ -33,126 +33,167 @@ if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
measureFileSizesBeforeBuild(paths.appBuild).then(previousFileSizes => { measureFileSizesBeforeBuild(paths.appBuild).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)
// Start the webpack build // Start the webpack build
build(previousFileSizes); build(previousFileSizes)
// Merge with the public folder // Merge with the public folder
copyPublicFolder(); copyPublicFolder()
}); })
// Print out errors // Print out errors
function printErrors(summary, errors) { function printErrors(summary, errors) {
console.log(chalk.red(summary)); console.log(chalk.red(summary))
console.log(); console.log()
errors.forEach(err => { errors.forEach(err => {
console.log(err.message || err); console.log(err.message || err)
console.log(); console.log()
}); })
} }
// 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...")
webpack(config).run((err, stats) => { webpack(config).run((err, stats) => {
if (err) { if (err) {
printErrors('Failed to compile.', [err]); printErrors("Failed to compile.", [err])
process.exit(1); process.exit(1)
} }
if (stats.compilation.errors.length) { if (stats.compilation.errors.length) {
printErrors('Failed to compile.', stats.compilation.errors); printErrors("Failed to compile.", stats.compilation.errors)
process.exit(1); process.exit(1)
} }
if (process.env.CI && stats.compilation.warnings.length) { if (process.env.CI && stats.compilation.warnings.length) {
printErrors('Failed to compile. When process.env.CI = true, warnings are treated as failures. Most CI servers set this automatically.', stats.compilation.warnings); printErrors(
process.exit(1); "Failed to compile. When process.env.CI = true, warnings are treated as failures. Most CI servers set this automatically.",
} stats.compilation.warnings
)
process.exit(1)
}
console.log(chalk.green('Compiled successfully.')); console.log(chalk.green("Compiled successfully."))
console.log(); console.log()
console.log('File sizes after gzip:'); console.log("File sizes after gzip:")
console.log(); console.log()
printFileSizesAfterBuild(stats, previousFileSizes); printFileSizesAfterBuild(stats, previousFileSizes)
console.log(); console.log()
var appPackage = require(paths.appPackageJson); var appPackage = require(paths.appPackageJson)
var publicUrl = paths.publicUrl; var publicUrl = paths.publicUrl
var publicPath = config.output.publicPath; var publicPath = config.output.publicPath
var publicPathname = url.parse(publicPath).pathname; var publicPathname = url.parse(publicPath).pathname
if (publicUrl && publicUrl.indexOf('.github.io/') !== -1) { if (publicUrl && publicUrl.indexOf(".github.io/") !== -1) {
// "homepage": "http://user.github.io/project" // "homepage": "http://user.github.io/project"
console.log('The project was built assuming it is hosted at ' + chalk.green(publicPathname) + '.'); console.log(
console.log('You can control this with the ' + chalk.green('homepage') + ' field in your ' + chalk.cyan('package.json') + '.'); "The project was built assuming it is hosted at " + chalk.green(publicPathname) + "."
console.log(); )
console.log('The ' + chalk.cyan('build') + ' folder is ready to be deployed.'); console.log(
console.log('To publish it at ' + chalk.green(publicUrl) + ', run:'); "You can control this with the " +
chalk.green("homepage") +
" field in your " +
chalk.cyan("package.json") +
"."
)
console.log()
console.log("The " + chalk.cyan("build") + " folder is ready to be deployed.")
console.log("To publish it at " + chalk.green(publicUrl) + ", run:")
// If script deploy has been added to package.json, skip the instructions // If script deploy has been added to package.json, skip the instructions
if (typeof appPackage.scripts.deploy === 'undefined') { if (typeof appPackage.scripts.deploy === "undefined") {
console.log(); console.log()
if (useYarn) { if (useYarn) {
console.log(' ' + chalk.cyan('yarn') + ' add --dev gh-pages'); console.log(" " + chalk.cyan("yarn") + " add --dev gh-pages")
} else { } else {
console.log(' ' + chalk.cyan('npm') + ' install --save-dev gh-pages'); console.log(" " + chalk.cyan("npm") + " install --save-dev gh-pages")
} }
console.log(); console.log()
console.log('Add the following script in your ' + chalk.cyan('package.json') + '.'); console.log("Add the following script in your " + chalk.cyan("package.json") + ".")
console.log(); console.log()
console.log(' ' + chalk.dim('// ...')); console.log(" " + chalk.dim("// ..."))
console.log(' ' + chalk.yellow('"scripts"') + ': {'); console.log(" " + chalk.yellow('"scripts"') + ": {")
console.log(' ' + chalk.dim('// ...')); console.log(" " + chalk.dim("// ..."))
console.log(' ' + chalk.yellow('"predeploy"') + ': ' + chalk.yellow('"npm run build",')); console.log(
console.log(' ' + chalk.yellow('"deploy"') + ': ' + chalk.yellow('"gh-pages -d build"')); " " + chalk.yellow('"predeploy"') + ": " + chalk.yellow('"npm run build",')
console.log(' }'); )
console.log(); console.log(
console.log('Then run:'); " " + chalk.yellow('"deploy"') + ": " + chalk.yellow('"gh-pages -d build"')
)
console.log(" }")
console.log()
console.log("Then run:")
} }
console.log(); console.log()
console.log(' ' + chalk.cyan(useYarn ? 'yarn' : 'npm') + ' run deploy'); console.log(" " + chalk.cyan(useYarn ? "yarn" : "npm") + " run deploy")
console.log(); console.log()
} else if (publicPath !== '/') { } else if (publicPath !== "/") {
// "homepage": "http://mywebsite.com/project" // "homepage": "http://mywebsite.com/project"
console.log('The project was built assuming it is hosted at ' + chalk.green(publicPath) + '.'); console.log("The project was built assuming it is hosted at " + chalk.green(publicPath) + ".")
console.log('You can control this with the ' + chalk.green('homepage') + ' field in your ' + chalk.cyan('package.json') + '.'); console.log(
console.log(); "You can control this with the " +
console.log('The ' + chalk.cyan('build') + ' folder is ready to be deployed.'); chalk.green("homepage") +
console.log(); " field in your " +
chalk.cyan("package.json") +
"."
)
console.log()
console.log("The " + chalk.cyan("build") + " folder is ready to be deployed.")
console.log()
} else { } else {
if (publicUrl) { if (publicUrl) {
// "homepage": "http://mywebsite.com" // "homepage": "http://mywebsite.com"
console.log('The project was built assuming it is hosted at ' + chalk.green(publicUrl) + '.'); console.log(
console.log('You can control this with the ' + chalk.green('homepage') + ' field in your ' + chalk.cyan('package.json') + '.'); "The project was built assuming it is hosted at " + chalk.green(publicUrl) + "."
console.log(); )
console.log(
"You can control this with the " +
chalk.green("homepage") +
" field in your " +
chalk.cyan("package.json") +
"."
)
console.log()
} else { } else {
// no homepage // no homepage
console.log('The project was built assuming it is hosted at the server root.'); console.log("The project was built assuming it is hosted at the server root.")
console.log('To override this, specify the ' + chalk.green('homepage') + ' in your ' + chalk.cyan('package.json') + '.'); console.log(
console.log('For example, add this to build it for GitHub Pages:') "To override this, specify the " +
console.log(); chalk.green("homepage") +
console.log(' ' + chalk.green('"homepage"') + chalk.cyan(': ') + chalk.green('"http://myname.github.io/myapp"') + chalk.cyan(',')); " in your " +
console.log(); chalk.cyan("package.json") +
"."
)
console.log("For example, add this to build it for GitHub Pages:")
console.log()
console.log(
" " +
chalk.green('"homepage"') +
chalk.cyan(": ") +
chalk.green('"http://myname.github.io/myapp"') +
chalk.cyan(",")
)
console.log()
} }
var build = path.relative(process.cwd(), paths.appBuild); var build = path.relative(process.cwd(), paths.appBuild)
console.log('The ' + chalk.cyan(build) + ' folder is ready to be deployed.'); console.log("The " + chalk.cyan(build) + " folder is ready to be deployed.")
console.log('You may serve it with a static server:'); console.log("You may serve it with a static server:")
console.log(); console.log()
if (useYarn) { if (useYarn) {
console.log(` ${chalk.cyan('yarn')} global add serve`); console.log(` ${chalk.cyan("yarn")} global add serve`)
} else { } else {
console.log(` ${chalk.cyan('npm')} install -g serve`); console.log(` ${chalk.cyan("npm")} install -g serve`)
} }
console.log(` ${chalk.cyan('serve')} -s build`); console.log(` ${chalk.cyan("serve")} -s build`)
console.log(); console.log()
} }
}); })
} }
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,4 +1,4 @@
const AuthAPI = require('../server/AuthAPI') const AuthAPI = require("../server/AuthAPI")
const scopes = { const scopes = {
blacklist: { blacklist: {
@ -10,8 +10,8 @@ AuthAPI.createToken(scopes).then(
token => { token => {
// Verify it, just to be sure. // Verify it, just to be sure.
AuthAPI.verifyToken(token).then(payload => { AuthAPI.verifyToken(token).then(payload => {
console.log(token, '\n') console.log(token, "\n")
console.log(JSON.stringify(payload, null, 2), '\n') console.log(JSON.stringify(payload, null, 2), "\n")
console.log(AuthAPI.getPublicKey()) console.log(AuthAPI.getPublicKey())
process.exit() process.exit()
}) })

View File

@ -1,25 +1,22 @@
require('isomorphic-fetch') require("isomorphic-fetch")
const invariant = require('invariant') const invariant = require("invariant")
const CloudflareEmail = process.env.CLOUDFLARE_EMAIL const CloudflareEmail = process.env.CLOUDFLARE_EMAIL
const CloudflareKey = process.env.CLOUDFLARE_KEY const CloudflareKey = process.env.CLOUDFLARE_KEY
const RayID = process.argv[2] const RayID = process.argv[2]
invariant(CloudflareEmail, 'Missing the $CLOUDFLARE_EMAIL environment variable') invariant(CloudflareEmail, "Missing the $CLOUDFLARE_EMAIL environment variable")
invariant(CloudflareKey, 'Missing the $CLOUDFLARE_KEY environment variable') invariant(CloudflareKey, "Missing the $CLOUDFLARE_KEY environment variable")
invariant( invariant(RayID, "Missing the RAY_ID argument; use `heroku run node show-log.js RAY_ID`")
RayID,
'Missing the RAY_ID argument; use `heroku run node show-log.js RAY_ID`'
)
function getZones(domain) { function getZones(domain) {
return fetch(`https://api.cloudflare.com/client/v4/zones?name=${domain}`, { return fetch(`https://api.cloudflare.com/client/v4/zones?name=${domain}`, {
method: 'GET', method: "GET",
headers: { headers: {
'X-Auth-Email': CloudflareEmail, "X-Auth-Email": CloudflareEmail,
'X-Auth-Key': CloudflareKey "X-Auth-Key": CloudflareKey
} }
}) })
.then(res => res.json()) .then(res => res.json())
@ -27,19 +24,16 @@ function getZones(domain) {
} }
function getLog(zoneId, rayId) { function getLog(zoneId, rayId) {
return fetch( return fetch(`https://api.cloudflare.com/client/v4/zones/${zoneId}/logs/requests/${rayId}`, {
`https://api.cloudflare.com/client/v4/zones/${zoneId}/logs/requests/${rayId}`, method: "GET",
{ headers: {
method: 'GET', "X-Auth-Email": CloudflareEmail,
headers: { "X-Auth-Key": CloudflareKey
'X-Auth-Email': CloudflareEmail,
'X-Auth-Key': CloudflareKey
}
} }
).then(res => (res.status === 404 ? 'NOT FOUND' : res.json())) }).then(res => (res.status === 404 ? "NOT FOUND" : res.json()))
} }
getZones('unpkg.com').then(zones => { getZones("unpkg.com").then(zones => {
getLog(zones[0].id, RayID).then(entry => { getLog(zones[0].id, RayID).then(entry => {
console.log(entry) console.log(entry)
}) })

View File

@ -1,8 +1,8 @@
const subDays = require('date-fns/sub_days') const subDays = require("date-fns/sub_days")
const prettyBytes = require('pretty-bytes') const prettyBytes = require("pretty-bytes")
const table = require('text-table') const table = require("text-table")
const StatsAPI = require('../server/StatsAPI') const StatsAPI = require("../server/StatsAPI")
const now = new Date() const now = new Date()
function createRange(start, end) { function createRange(start, end) {
@ -21,31 +21,21 @@ const pastSevenDays = createPastDays(7)
const pastThirtyDays = createPastDays(30) const pastThirtyDays = createPastDays(30)
Promise.all([ Promise.all([
StatsAPI.sumKeys( StatsAPI.sumKeys(pastSevenDays.map(date => `stats-requests-${StatsAPI.createDayKey(date)}`)),
pastSevenDays.map(date => `stats-requests-${StatsAPI.createDayKey(date)}`) StatsAPI.sumKeys(pastSevenDays.map(date => `stats-bandwidth-${StatsAPI.createDayKey(date)}`)),
), StatsAPI.sumKeys(pastThirtyDays.map(date => `stats-requests-${StatsAPI.createDayKey(date)}`)),
StatsAPI.sumKeys( StatsAPI.sumKeys(pastThirtyDays.map(date => `stats-bandwidth-${StatsAPI.createDayKey(date)}`))
pastSevenDays.map(date => `stats-bandwidth-${StatsAPI.createDayKey(date)}`)
),
StatsAPI.sumKeys(
pastThirtyDays.map(date => `stats-requests-${StatsAPI.createDayKey(date)}`)
),
StatsAPI.sumKeys(
pastThirtyDays.map(date => `stats-bandwidth-${StatsAPI.createDayKey(date)}`)
)
]).then(results => { ]).then(results => {
console.log('\n## Summary') console.log("\n## Summary")
console.log('Requests this week: %s', results[0].toLocaleString()) console.log("Requests this week: %s", results[0].toLocaleString())
console.log('Bandwidth this week: %s', prettyBytes(results[1])) console.log("Bandwidth this week: %s", prettyBytes(results[1]))
console.log('Requests this month: %s', results[2].toLocaleString()) console.log("Requests this month: %s", results[2].toLocaleString())
console.log('Bandwidth this month: %s', prettyBytes(results[3])) console.log("Bandwidth this month: %s", prettyBytes(results[3]))
StatsAPI.sumTopScores( StatsAPI.sumTopScores(
pastSevenDays.map( pastSevenDays.map(date => `stats-packageRequests-${StatsAPI.createDayKey(date)}`)
date => `stats-packageRequests-${StatsAPI.createDayKey(date)}`
)
).then(topPackages => { ).then(topPackages => {
console.log('\n## Top Packages This Week') console.log("\n## Top Packages This Week")
topPackages.forEach(result => { topPackages.forEach(result => {
result[1] = result[1].toLocaleString() result[1] = result[1].toLocaleString()

View File

@ -1,161 +1,180 @@
'use strict'; "use strict"
process.env.NODE_ENV = 'development'; process.env.NODE_ENV = "development"
// Load environment variables from .env file. Suppress warnings using silent // Load environment variables from .env file. Suppress warnings using silent
// if this file is missing. dotenv will never modify any environment variables // if this file is missing. dotenv will never modify any environment variables
// that have already been set. // that have already been set.
// https://github.com/motdotla/dotenv // https://github.com/motdotla/dotenv
require('dotenv').config({silent: true}); require("dotenv").config({ silent: true })
var chalk = require('chalk'); var chalk = require("chalk")
var webpack = require('webpack'); var webpack = require("webpack")
var WebpackDevServer = require('webpack-dev-server'); var WebpackDevServer = require("webpack-dev-server")
var historyApiFallback = require('connect-history-api-fallback'); var historyApiFallback = require("connect-history-api-fallback")
var httpProxyMiddleware = require('http-proxy-middleware'); var httpProxyMiddleware = require("http-proxy-middleware")
var detect = require('detect-port'); var detect = require("detect-port")
var clearConsole = require('react-dev-utils/clearConsole'); var clearConsole = require("react-dev-utils/clearConsole")
var checkRequiredFiles = require('react-dev-utils/checkRequiredFiles'); var checkRequiredFiles = require("react-dev-utils/checkRequiredFiles")
var formatWebpackMessages = require('react-dev-utils/formatWebpackMessages'); var formatWebpackMessages = require("react-dev-utils/formatWebpackMessages")
var getProcessForPort = require('react-dev-utils/getProcessForPort'); var getProcessForPort = require("react-dev-utils/getProcessForPort")
var openBrowser = require('react-dev-utils/openBrowser'); var openBrowser = require("react-dev-utils/openBrowser")
var prompt = require('react-dev-utils/prompt'); var prompt = require("react-dev-utils/prompt")
var fs = require('fs'); var fs = require("fs")
var config = require('../config/webpack.config.dev'); var config = require("../config/webpack.config.dev")
var paths = require('../config/paths'); var paths = require("../config/paths")
var useYarn = fs.existsSync(paths.yarnLockFile); var useYarn = fs.existsSync(paths.yarnLockFile)
var cli = useYarn ? 'yarn' : 'npm'; var cli = useYarn ? "yarn" : "npm"
var isInteractive = process.stdout.isTTY; var isInteractive = process.stdout.isTTY
// Warn and crash if required files are missing // Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) { if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
process.exit(1); process.exit(1)
} }
// Tools like Cloud9 rely on this. // Tools like Cloud9 rely on this.
var DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000; var DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000
var compiler; var compiler
var handleCompile; var handleCompile
// You can safely remove this after ejecting. // You can safely remove this after ejecting.
// We only use this block for testing of Create React App itself: // We only use this block for testing of Create React App itself:
var isSmokeTest = process.argv.some(arg => arg.indexOf('--smoke-test') > -1); var isSmokeTest = process.argv.some(arg => arg.indexOf("--smoke-test") > -1)
if (isSmokeTest) { if (isSmokeTest) {
handleCompile = function (err, stats) { handleCompile = function(err, stats) {
if (err || stats.hasErrors() || stats.hasWarnings()) { if (err || stats.hasErrors() || stats.hasWarnings()) {
process.exit(1); process.exit(1)
} else { } else {
process.exit(0); process.exit(0)
} }
}; }
} }
function setupCompiler(host, port, protocol) { function setupCompiler(host, port, protocol) {
// "Compiler" is a low-level interface to Webpack. // "Compiler" is a low-level interface to Webpack.
// It lets us listen to some events and provide our own custom messages. // It lets us listen to some events and provide our own custom messages.
compiler = webpack(config, handleCompile); compiler = webpack(config, handleCompile)
// "invalid" event fires when you have changed a file, and Webpack is // "invalid" event fires when you have changed a file, and Webpack is
// recompiling a bundle. WebpackDevServer takes care to pause serving the // recompiling a bundle. WebpackDevServer takes care to pause serving the
// bundle, so if you refresh, it'll wait instead of serving the old one. // bundle, so if you refresh, it'll wait instead of serving the old one.
// "invalid" is short for "bundle invalidated", it doesn't imply any errors. // "invalid" is short for "bundle invalidated", it doesn't imply any errors.
compiler.plugin('invalid', function() { compiler.plugin("invalid", function() {
if (isInteractive) { if (isInteractive) {
clearConsole(); clearConsole()
} }
console.log('Compiling...'); console.log("Compiling...")
}); })
var isFirstCompile = true; var isFirstCompile = true
// "done" event fires when Webpack has finished recompiling the bundle. // "done" event fires when Webpack has finished recompiling the bundle.
// Whether or not you have warnings or errors, you will get this event. // Whether or not you have warnings or errors, you will get this event.
compiler.plugin('done', function(stats) { compiler.plugin("done", function(stats) {
if (isInteractive) { if (isInteractive) {
clearConsole(); clearConsole()
} }
// We have switched off the default Webpack output in WebpackDevServer // We have switched off the default Webpack output in WebpackDevServer
// options so we are going to "massage" the warnings and errors and present // options so we are going to "massage" the warnings and errors and present
// them in a readable focused way. // them in a readable focused way.
var messages = formatWebpackMessages(stats.toJson({}, true)); var messages = formatWebpackMessages(stats.toJson({}, true))
var isSuccessful = !messages.errors.length && !messages.warnings.length; var isSuccessful = !messages.errors.length && !messages.warnings.length
var showInstructions = isSuccessful && (isInteractive || isFirstCompile); var showInstructions = isSuccessful && (isInteractive || isFirstCompile)
if (isSuccessful) { if (isSuccessful) {
console.log(chalk.green('Compiled successfully!')); console.log(chalk.green("Compiled successfully!"))
} }
if (showInstructions) { if (showInstructions) {
console.log(); console.log()
console.log('The app is running at:'); console.log("The app is running at:")
console.log(); console.log()
console.log(' ' + chalk.cyan(protocol + '://' + host + ':' + port + '/')); console.log(" " + chalk.cyan(protocol + "://" + host + ":" + port + "/"))
console.log(); console.log()
console.log('Note that the development build is not optimized.'); console.log("Note that the development build is not optimized.")
console.log('To create a production build, use ' + chalk.cyan(cli + ' run build') + '.'); console.log("To create a production build, use " + chalk.cyan(cli + " run build") + ".")
console.log(); console.log()
isFirstCompile = false; isFirstCompile = false
} }
// If errors exist, only show errors. // If errors exist, only show errors.
if (messages.errors.length) { if (messages.errors.length) {
console.log(chalk.red('Failed to compile.')); console.log(chalk.red("Failed to compile."))
console.log(); console.log()
messages.errors.forEach(message => { messages.errors.forEach(message => {
console.log(message); console.log(message)
console.log(); console.log()
}); })
return; return
} }
// Show warnings if no errors were found. // Show warnings if no errors were found.
if (messages.warnings.length) { if (messages.warnings.length) {
console.log(chalk.yellow('Compiled with warnings.')); console.log(chalk.yellow("Compiled with warnings."))
console.log(); console.log()
messages.warnings.forEach(message => { messages.warnings.forEach(message => {
console.log(message); console.log(message)
console.log(); console.log()
}); })
// Teach some ESLint tricks. // Teach some ESLint tricks.
console.log('You may use special comments to disable some warnings.'); console.log("You may use special comments to disable some warnings.")
console.log('Use ' + chalk.yellow('// eslint-disable-next-line') + ' to ignore the next line.'); console.log(
console.log('Use ' + chalk.yellow('/* eslint-disable */') + ' to ignore all warnings in a file.'); "Use " + chalk.yellow("// eslint-disable-next-line") + " to ignore the next line."
)
console.log(
"Use " + chalk.yellow("/* eslint-disable */") + " to ignore all warnings in a file."
)
} }
}); })
} }
// We need to provide a custom onError function for httpProxyMiddleware. // We need to provide a custom onError function for httpProxyMiddleware.
// It allows us to log custom error messages on the console. // It allows us to log custom error messages on the console.
function onProxyError(proxy) { function onProxyError(proxy) {
return function(err, req, res){ return function(err, req, res) {
var host = req.headers && req.headers.host; var host = req.headers && req.headers.host
console.log( console.log(
chalk.red('Proxy error:') + ' Could not proxy request ' + chalk.cyan(req.url) + chalk.red("Proxy error:") +
' from ' + chalk.cyan(host) + ' to ' + chalk.cyan(proxy) + '.' " Could not proxy request " +
); chalk.cyan(req.url) +
" from " +
chalk.cyan(host) +
" to " +
chalk.cyan(proxy) +
"."
)
console.log( console.log(
'See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (' + "See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (" +
chalk.cyan(err.code) + ').' chalk.cyan(err.code) +
); ")."
console.log(); )
console.log()
// And immediately send the proper error response to the client. // And immediately send the proper error response to the client.
// Otherwise, the request will eventually timeout with ERR_EMPTY_RESPONSE on the client side. // Otherwise, the request will eventually timeout with ERR_EMPTY_RESPONSE on the client side.
if (res.writeHead && !res.headersSent) { if (res.writeHead && !res.headersSent) {
res.writeHead(500); res.writeHead(500)
} }
res.end('Proxy error: Could not proxy request ' + req.url + ' from ' + res.end(
host + ' to ' + proxy + ' (' + err.code + ').' "Proxy error: Could not proxy request " +
); req.url +
" from " +
host +
" to " +
proxy +
" (" +
err.code +
")."
)
} }
} }
function addMiddleware(devServer) { function addMiddleware(devServer) {
// `proxy` lets you to specify a fallback server during development. // `proxy` lets you to specify a fallback server during development.
// Every unrecognized request will be forwarded to it. // Every unrecognized request will be forwarded to it.
var proxy = require(paths.appPackageJson).proxy; var proxy = require(paths.appPackageJson).proxy
//devServer.use(historyApiFallback({ //devServer.use(historyApiFallback({
// // Paths with dots should still use the history fallback. // // Paths with dots should still use the history fallback.
// // See https://github.com/facebookincubator/create-react-app/issues/387. // // See https://github.com/facebookincubator/create-react-app/issues/387.
@ -172,11 +191,11 @@ function addMiddleware(devServer) {
// ['text/html', '*/*'] // ['text/html', '*/*']
//})); //}));
if (proxy) { if (proxy) {
if (typeof proxy !== 'string') { if (typeof proxy !== "string") {
console.log(chalk.red('When specified, "proxy" in package.json must be a string.')); console.log(chalk.red('When specified, "proxy" in package.json must be a string.'))
console.log(chalk.red('Instead, the type of "proxy" was "' + typeof proxy + '".')); console.log(chalk.red('Instead, the type of "proxy" was "' + typeof proxy + '".'))
console.log(chalk.red('Either remove "proxy" from package.json, or make it a string.')); console.log(chalk.red('Either remove "proxy" from package.json, or make it a string.'))
process.exit(1); process.exit(1)
} }
// Otherwise, if proxy is specified, we will let it handle any request. // Otherwise, if proxy is specified, we will let it handle any request.
@ -185,19 +204,19 @@ function addMiddleware(devServer) {
// - /*.hot-update.json (WebpackDevServer uses this too for hot reloading) // - /*.hot-update.json (WebpackDevServer uses this too for hot reloading)
// - /sockjs-node/* (WebpackDevServer uses this for hot reloading) // - /sockjs-node/* (WebpackDevServer uses this for hot reloading)
// Tip: use https://jex.im/regulex/ to visualize the regex // Tip: use https://jex.im/regulex/ to visualize the regex
var mayProxy = /^(?!\/(index\.html$|.*\.hot-update\.json$|sockjs-node\/)).*$/; var mayProxy = /^(?!\/(index\.html$|.*\.hot-update\.json$|sockjs-node\/)).*$/
// Pass the scope regex both to Express and to the middleware for proxying // Pass the scope regex both to Express and to the middleware for proxying
// of both HTTP and WebSockets to work without false positives. // of both HTTP and WebSockets to work without false positives.
var hpm = httpProxyMiddleware(pathname => mayProxy.test(pathname), { var hpm = httpProxyMiddleware(pathname => mayProxy.test(pathname), {
target: proxy, target: proxy,
logLevel: 'silent', logLevel: "silent",
onProxyReq: function(proxyReq) { onProxyReq: function(proxyReq) {
// Browers may send Origin headers even with same-origin // Browers may send Origin headers even with same-origin
// requests. To prevent CORS issues, we have to change // requests. To prevent CORS issues, we have to change
// the Origin to match the target URL. // the Origin to match the target URL.
if (proxyReq.getHeader('origin')) { if (proxyReq.getHeader("origin")) {
proxyReq.setHeader('origin', proxy); proxyReq.setHeader("origin", proxy)
} }
}, },
onError: onProxyError(proxy), onError: onProxyError(proxy),
@ -205,18 +224,18 @@ function addMiddleware(devServer) {
changeOrigin: true, changeOrigin: true,
ws: true, ws: true,
xfwd: true xfwd: true
}); })
devServer.use(mayProxy, hpm); devServer.use(mayProxy, hpm)
// Listen for the websocket 'upgrade' event and upgrade the connection. // Listen for the websocket 'upgrade' event and upgrade the connection.
// If this is not done, httpProxyMiddleware will not try to upgrade until // If this is not done, httpProxyMiddleware will not try to upgrade until
// an initial plain HTTP request is made. // an initial plain HTTP request is made.
devServer.listeningApp.on('upgrade', hpm.upgrade); devServer.listeningApp.on("upgrade", hpm.upgrade)
} }
// Finally, by now we have certainly resolved the URL. // Finally, by now we have certainly resolved the URL.
// It may be /index.html, so let the dev server try serving it again. // It may be /index.html, so let the dev server try serving it again.
devServer.use(devServer.middleware); devServer.use(devServer.middleware)
} }
function runDevServer(host, port, protocol) { function runDevServer(host, port, protocol) {
@ -225,7 +244,7 @@ function runDevServer(host, port, protocol) {
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
@ -261,56 +280,59 @@ function runDevServer(host, port, protocol) {
// 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
}); })
// Our custom middleware proxies requests to /index.html or a remote API. // Our custom middleware proxies requests to /index.html or a remote API.
addMiddleware(devServer); addMiddleware(devServer)
// Launch WebpackDevServer. // Launch WebpackDevServer.
devServer.listen(port, err => { devServer.listen(port, 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...')); console.log(chalk.cyan("Starting the development server..."))
console.log(); console.log()
openBrowser(protocol + '://' + host + ':' + port + '/'); openBrowser(protocol + "://" + host + ":" + port + "/")
}); })
} }
function run(port) { function run(port) {
var protocol = process.env.HTTPS === 'true' ? "https" : "http"; var protocol = process.env.HTTPS === "true" ? "https" : "http"
var host = process.env.HOST || 'localhost'; var host = process.env.HOST || "localhost"
setupCompiler(host, port, protocol); setupCompiler(host, port, protocol)
runDevServer(host, port, protocol); runDevServer(host, port, protocol)
} }
// 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. `detect()` Promise resolves to the next free port. // run on a different port. `detect()` Promise resolves to the next free port.
detect(DEFAULT_PORT).then(port => { detect(DEFAULT_PORT).then(port => {
if (port === DEFAULT_PORT) { if (port === DEFAULT_PORT) {
run(port); run(port)
return; return
} }
if (isInteractive) { if (isInteractive) {
clearConsole(); clearConsole()
var existingProcess = getProcessForPort(DEFAULT_PORT); var existingProcess = getProcessForPort(DEFAULT_PORT)
var question = var question =
chalk.yellow('Something is already running on port ' + DEFAULT_PORT + '.' + chalk.yellow(
((existingProcess) ? ' Probably:\n ' + existingProcess : '')) + "Something is already running on port " +
'\n\nWould you like to run the app on another port instead?'; DEFAULT_PORT +
"." +
(existingProcess ? " Probably:\n " + existingProcess : "")
) + "\n\nWould you like to run the app on another port instead?"
prompt(question, true).then(shouldChangePort => { prompt(question, true).then(shouldChangePort => {
if (shouldChangePort) { if (shouldChangePort) {
run(port); run(port)
} }
}); })
} else { } else {
console.log(chalk.red('Something is already running on port ' + DEFAULT_PORT + '.')); console.log(chalk.red("Something is already running on port " + DEFAULT_PORT + "."))
} }
}); })

View File

@ -1,21 +1,20 @@
'use strict'; "use strict"
process.env.NODE_ENV = 'test'; process.env.NODE_ENV = "test"
process.env.PUBLIC_URL = ''; process.env.PUBLIC_URL = ""
// Load environment variables from .env file. Suppress warnings using silent // Load environment variables from .env file. Suppress warnings using silent
// if this file is missing. dotenv will never modify any environment variables // if this file is missing. dotenv will never modify any environment variables
// that have already been set. // that have already been set.
// https://github.com/motdotla/dotenv // https://github.com/motdotla/dotenv
require('dotenv').config({silent: true}); require("dotenv").config({ silent: true })
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);