Browse Source

feat: build lib

node 6 years ago
parent
commit
b2f9b8e64e

+ 1
- 1
.gitignore View File

@@ -7,7 +7,7 @@
7 7
 /coverage
8 8
 
9 9
 # production
10
-/build
10
+# /build
11 11
 
12 12
 # misc
13 13
 .DS_Store

+ 6
- 0
build/asset-manifest.json View File

@@ -0,0 +1,6 @@
1
+{
2
+  "main.css": "lib/css/main.css",
3
+  "main.css.map": "lib/css/main.css.map",
4
+  "main.js": "lib/js/main.js",
5
+  "main.js.map": "lib/js/main.js.map"
6
+}

BIN
build/favicon.ico View File


+ 1
- 0
build/index.html View File

@@ -0,0 +1 @@
1
+<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no"><meta name="theme-color" content="#000000"><link rel="manifest" href="/manifest.json"><link rel="shortcut icon" href="/favicon.ico"><title>React App</title><link href="/lib/css/main.css" rel="stylesheet"></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div><script type="text/javascript" src="/lib/js/main.js"></script></body></html>

+ 2
- 0
build/lib/css/main.css
File diff suppressed because it is too large
View File


+ 1
- 0
build/lib/css/main.css.map
File diff suppressed because it is too large
View File


+ 2
- 0
build/lib/js/main.js
File diff suppressed because it is too large
View File


+ 1
- 0
build/lib/js/main.js.map
File diff suppressed because it is too large
View File


+ 15
- 0
build/manifest.json View File

@@ -0,0 +1,15 @@
1
+{
2
+  "short_name": "React App",
3
+  "name": "Create React App Sample",
4
+  "icons": [
5
+    {
6
+      "src": "favicon.ico",
7
+      "sizes": "64x64 32x32 24x24 16x16",
8
+      "type": "image/x-icon"
9
+    }
10
+  ],
11
+  "start_url": "./index.html",
12
+  "display": "standalone",
13
+  "theme_color": "#000000",
14
+  "background_color": "#ffffff"
15
+}

+ 1
- 0
build/service-worker.js View File

@@ -0,0 +1 @@
1
+"use strict";var precacheConfig=[["/index.html","48052400c08cf5f6351fc116a510ec4b"],["/lib/css/main.css","13c5173a695f1fecbe06c8c66443819c"],["/lib/js/main.js","597f24450ca69734896612349faaad73"]],cacheName="sw-precache-v3-sw-precache-webpack-plugin-"+(self.registration?self.registration.scope:""),ignoreUrlParametersMatching=[/^utm_/],addDirectoryIndex=function(e,t){var n=new URL(e);return"/"===n.pathname.slice(-1)&&(n.pathname+=t),n.toString()},cleanResponse=function(t){return t.redirected?("body"in t?Promise.resolve(t.body):t.blob()).then(function(e){return new Response(e,{headers:t.headers,status:t.status,statusText:t.statusText})}):Promise.resolve(t)},createCacheKey=function(e,t,n,r){var a=new URL(e);return r&&a.pathname.match(r)||(a.search+=(a.search?"&":"")+encodeURIComponent(t)+"="+encodeURIComponent(n)),a.toString()},isPathWhitelisted=function(e,t){if(0===e.length)return!0;var n=new URL(t).pathname;return e.some(function(e){return n.match(e)})},stripIgnoredUrlParameters=function(e,n){var t=new URL(e);return t.hash="",t.search=t.search.slice(1).split("&").map(function(e){return e.split("=")}).filter(function(t){return n.every(function(e){return!e.test(t[0])})}).map(function(e){return e.join("=")}).join("&"),t.toString()},hashParamName="_sw-precache",urlsToCacheKeys=new Map(precacheConfig.map(function(e){var t=e[0],n=e[1],r=new URL(t,self.location),a=createCacheKey(r,hashParamName,n,/\.\w{8}\./);return[r.toString(),a]}));function setOfCachedUrls(e){return e.keys().then(function(e){return e.map(function(e){return e.url})}).then(function(e){return new Set(e)})}self.addEventListener("install",function(e){e.waitUntil(caches.open(cacheName).then(function(r){return setOfCachedUrls(r).then(function(n){return Promise.all(Array.from(urlsToCacheKeys.values()).map(function(t){if(!n.has(t)){var e=new Request(t,{credentials:"same-origin"});return fetch(e).then(function(e){if(!e.ok)throw new Error("Request for "+t+" returned a response with status "+e.status);return cleanResponse(e).then(function(e){return r.put(t,e)})})}}))})}).then(function(){return self.skipWaiting()}))}),self.addEventListener("activate",function(e){var n=new Set(urlsToCacheKeys.values());e.waitUntil(caches.open(cacheName).then(function(t){return t.keys().then(function(e){return Promise.all(e.map(function(e){if(!n.has(e.url))return t.delete(e)}))})}).then(function(){return self.clients.claim()}))}),self.addEventListener("fetch",function(t){if("GET"===t.request.method){var e,n=stripIgnoredUrlParameters(t.request.url,ignoreUrlParametersMatching),r="index.html";(e=urlsToCacheKeys.has(n))||(n=addDirectoryIndex(n,r),e=urlsToCacheKeys.has(n));var a="/index.html";!e&&"navigate"===t.request.mode&&isPathWhitelisted(["^(?!\\/__).*"],t.request.url)&&(n=new URL(a,self.location).toString(),e=urlsToCacheKeys.has(n)),e&&t.respondWith(caches.open(cacheName).then(function(e){return e.match(urlsToCacheKeys.get(n)).then(function(e){if(e)return e;throw Error("The cached response that was expected is missing.")})}).catch(function(e){return console.warn('Couldn\'t serve response for "%s" from cache: %O',t.request.url,e),fetch(t.request)}))}});

+ 93
- 0
config/env.js View File

@@ -0,0 +1,93 @@
1
+'use strict';
2
+
3
+const fs = require('fs');
4
+const path = require('path');
5
+const paths = require('./paths');
6
+
7
+// Make sure that including paths.js after env.js will read .env variables.
8
+delete require.cache[require.resolve('./paths')];
9
+
10
+const NODE_ENV = process.env.NODE_ENV;
11
+if (!NODE_ENV) {
12
+  throw new Error(
13
+    'The NODE_ENV environment variable is required but was not specified.'
14
+  );
15
+}
16
+
17
+// https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use
18
+var dotenvFiles = [
19
+  `${paths.dotenv}.${NODE_ENV}.local`,
20
+  `${paths.dotenv}.${NODE_ENV}`,
21
+  // Don't include `.env.local` for `test` environment
22
+  // since normally you expect tests to produce the same
23
+  // results for everyone
24
+  NODE_ENV !== 'test' && `${paths.dotenv}.local`,
25
+  paths.dotenv,
26
+].filter(Boolean);
27
+
28
+// Load environment variables from .env* files. Suppress warnings using silent
29
+// if this file is missing. dotenv will never modify any environment variables
30
+// that have already been set.  Variable expansion is supported in .env files.
31
+// https://github.com/motdotla/dotenv
32
+// https://github.com/motdotla/dotenv-expand
33
+dotenvFiles.forEach(dotenvFile => {
34
+  if (fs.existsSync(dotenvFile)) {
35
+    require('dotenv-expand')(
36
+      require('dotenv').config({
37
+        path: dotenvFile,
38
+      })
39
+    );
40
+  }
41
+});
42
+
43
+// We support resolving modules according to `NODE_PATH`.
44
+// This lets you use absolute paths in imports inside large monorepos:
45
+// https://github.com/facebookincubator/create-react-app/issues/253.
46
+// It works similar to `NODE_PATH` in Node itself:
47
+// https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders
48
+// Note that unlike in Node, only *relative* paths from `NODE_PATH` are honored.
49
+// Otherwise, we risk importing Node.js core modules into an app instead of Webpack shims.
50
+// https://github.com/facebookincubator/create-react-app/issues/1023#issuecomment-265344421
51
+// We also resolve them to make sure all tools using them work consistently.
52
+const appDirectory = fs.realpathSync(process.cwd());
53
+process.env.NODE_PATH = (process.env.NODE_PATH || '')
54
+  .split(path.delimiter)
55
+  .filter(folder => folder && !path.isAbsolute(folder))
56
+  .map(folder => path.resolve(appDirectory, folder))
57
+  .join(path.delimiter);
58
+
59
+// Grab NODE_ENV and REACT_APP_* environment variables and prepare them to be
60
+// injected into the application via DefinePlugin in Webpack configuration.
61
+const REACT_APP = /^REACT_APP_/i;
62
+
63
+function getClientEnvironment(publicUrl) {
64
+  const raw = Object.keys(process.env)
65
+    .filter(key => REACT_APP.test(key))
66
+    .reduce(
67
+      (env, key) => {
68
+        env[key] = process.env[key];
69
+        return env;
70
+      },
71
+      {
72
+        // Useful for determining whether we’re running in production mode.
73
+        // Most importantly, it switches React into the correct mode.
74
+        NODE_ENV: process.env.NODE_ENV || 'development',
75
+        // Useful for resolving the correct path to static assets in `public`.
76
+        // For example, <img src={process.env.PUBLIC_URL + '/img/logo.png'} />.
77
+        // This should only be used as an escape hatch. Normally you would put
78
+        // images into the `src` and `import` them in code to get their paths.
79
+        PUBLIC_URL: publicUrl,
80
+      }
81
+    );
82
+  // Stringify all values so we can feed into Webpack DefinePlugin
83
+  const stringified = {
84
+    'process.env': Object.keys(raw).reduce((env, key) => {
85
+      env[key] = JSON.stringify(raw[key]);
86
+      return env;
87
+    }, {}),
88
+  };
89
+
90
+  return { raw, stringified };
91
+}
92
+
93
+module.exports = getClientEnvironment;

+ 14
- 0
config/jest/cssTransform.js View File

@@ -0,0 +1,14 @@
1
+'use strict';
2
+
3
+// This is a custom Jest transformer turning style imports into empty objects.
4
+// http://facebook.github.io/jest/docs/en/webpack.html
5
+
6
+module.exports = {
7
+  process() {
8
+    return 'module.exports = {};';
9
+  },
10
+  getCacheKey() {
11
+    // The output is always the same.
12
+    return 'cssTransform';
13
+  },
14
+};

+ 12
- 0
config/jest/fileTransform.js View File

@@ -0,0 +1,12 @@
1
+'use strict';
2
+
3
+const path = require('path');
4
+
5
+// This is a custom Jest transformer turning file imports into filenames.
6
+// http://facebook.github.io/jest/docs/en/webpack.html
7
+
8
+module.exports = {
9
+  process(src, filename) {
10
+    return `module.exports = ${JSON.stringify(path.basename(filename))};`;
11
+  },
12
+};

+ 55
- 0
config/paths.js View File

@@ -0,0 +1,55 @@
1
+'use strict';
2
+
3
+const path = require('path');
4
+const fs = require('fs');
5
+const url = require('url');
6
+
7
+// Make sure any symlinks in the project folder are resolved:
8
+// https://github.com/facebookincubator/create-react-app/issues/637
9
+const appDirectory = fs.realpathSync(process.cwd());
10
+const resolveApp = relativePath => path.resolve(appDirectory, relativePath);
11
+
12
+const envPublicUrl = process.env.PUBLIC_URL;
13
+
14
+function ensureSlash(path, needsSlash) {
15
+  const hasSlash = path.endsWith('/');
16
+  if (hasSlash && !needsSlash) {
17
+    return path.substr(path, path.length - 1);
18
+  } else if (!hasSlash && needsSlash) {
19
+    return `${path}/`;
20
+  } else {
21
+    return path;
22
+  }
23
+}
24
+
25
+const getPublicUrl = appPackageJson =>
26
+  envPublicUrl || require(appPackageJson).homepage;
27
+
28
+// We use `PUBLIC_URL` environment variable or "homepage" field to infer
29
+// "public path" at which the app is served.
30
+// Webpack needs to know it to put the right <script> hrefs into HTML even in
31
+// single-page apps that may serve index.html for nested URLs like /todos/42.
32
+// We can't use a relative path in HTML because we don't want to load something
33
+// like /todos/42/static/js/bundle.7289d.js. We have to know the root.
34
+function getServedPath(appPackageJson) {
35
+  const publicUrl = getPublicUrl(appPackageJson);
36
+  const servedUrl =
37
+    envPublicUrl || (publicUrl ? url.parse(publicUrl).pathname : '/');
38
+  return ensureSlash(servedUrl, true);
39
+}
40
+
41
+// config after eject: we're in ./config/
42
+module.exports = {
43
+  dotenv: resolveApp('.env'),
44
+  appBuild: resolveApp('build'),
45
+  appPublic: resolveApp('public'),
46
+  appHtml: resolveApp('public/index.html'),
47
+  appIndexJs: resolveApp('src/index.js'),
48
+  appPackageJson: resolveApp('package.json'),
49
+  appSrc: resolveApp('src'),
50
+  yarnLockFile: resolveApp('yarn.lock'),
51
+  testsSetup: resolveApp('src/setupTests.js'),
52
+  appNodeModules: resolveApp('node_modules'),
53
+  publicUrl: getPublicUrl(resolveApp('package.json')),
54
+  servedPath: getServedPath(resolveApp('package.json')),
55
+};

+ 22
- 0
config/polyfills.js View File

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

+ 262
- 0
config/webpack.config.dev.js View File

@@ -0,0 +1,262 @@
1
+'use strict';
2
+
3
+const autoprefixer = require('autoprefixer');
4
+const path = require('path');
5
+const webpack = require('webpack');
6
+const HtmlWebpackPlugin = require('html-webpack-plugin');
7
+const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
8
+const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
9
+const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
10
+const eslintFormatter = require('react-dev-utils/eslintFormatter');
11
+const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
12
+const getClientEnvironment = require('./env');
13
+const paths = require('./paths');
14
+
15
+// Webpack uses `publicPath` to determine where the app is being served from.
16
+// In development, we always serve from the root. This makes config easier.
17
+const publicPath = '/';
18
+// `publicUrl` is just like `publicPath`, but we will provide it to our app
19
+// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
20
+// Omit trailing slash as %PUBLIC_PATH%/xyz looks better than %PUBLIC_PATH%xyz.
21
+const publicUrl = '';
22
+// Get environment variables to inject into our app.
23
+const env = getClientEnvironment(publicUrl);
24
+
25
+// This is the development configuration.
26
+// It is focused on developer experience and fast rebuilds.
27
+// The production configuration is different and lives in a separate file.
28
+module.exports = {
29
+  // You may want 'eval' instead if you prefer to see the compiled output in DevTools.
30
+  // See the discussion in https://github.com/facebookincubator/create-react-app/issues/343.
31
+  devtool: 'cheap-module-source-map',
32
+  // These are the "entry points" to our application.
33
+  // This means they will be the "root" imports that are included in JS bundle.
34
+  // The first two entry points enable "hot" CSS and auto-refreshes for JS.
35
+  entry: [
36
+    // We ship a few polyfills by default:
37
+    require.resolve('./polyfills'),
38
+    // Include an alternative client for WebpackDevServer. A client's job is to
39
+    // connect to WebpackDevServer by a socket and get notified about changes.
40
+    // When you save a file, the client will either apply hot updates (in case
41
+    // of CSS changes), or refresh the page (in case of JS changes). When you
42
+    // make a syntax error, this client will display a syntax error overlay.
43
+    // Note: instead of the default WebpackDevServer client, we use a custom one
44
+    // to bring better experience for Create React App users. You can replace
45
+    // the line below with these two lines if you prefer the stock client:
46
+    // require.resolve('webpack-dev-server/client') + '?/',
47
+    // require.resolve('webpack/hot/dev-server'),
48
+    require.resolve('react-dev-utils/webpackHotDevClient'),
49
+    // Finally, this is your app's code:
50
+    paths.appIndexJs,
51
+    // We include the app code last so that if there is a runtime error during
52
+    // initialization, it doesn't blow up the WebpackDevServer client, and
53
+    // changing JS code would still trigger a refresh.
54
+  ],
55
+  output: {
56
+    // Add /* filename */ comments to generated require()s in the output.
57
+    pathinfo: true,
58
+    // This does not produce a real file. It's just the virtual path that is
59
+    // served by WebpackDevServer in development. This is the JS bundle
60
+    // containing code from all our entry points, and the Webpack runtime.
61
+    filename: 'static/js/bundle.js',
62
+    // There are also additional JS chunk files if you use code splitting.
63
+    chunkFilename: 'static/js/[name].chunk.js',
64
+    // This is the URL that app is served from. We use "/" in development.
65
+    publicPath: publicPath,
66
+    // Point sourcemap entries to original disk location (format as URL on Windows)
67
+    devtoolModuleFilenameTemplate: info =>
68
+      path.resolve(info.absoluteResourcePath).replace(/\\/g, '/'),
69
+  },
70
+  resolve: {
71
+    // This allows you to set a fallback for where Webpack should look for modules.
72
+    // We placed these paths second because we want `node_modules` to "win"
73
+    // if there are any conflicts. This matches Node resolution mechanism.
74
+    // https://github.com/facebookincubator/create-react-app/issues/253
75
+    modules: ['node_modules', paths.appNodeModules].concat(
76
+      // It is guaranteed to exist because we tweak it in `env.js`
77
+      process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
78
+    ),
79
+    // These are the reasonable defaults supported by the Node ecosystem.
80
+    // We also include JSX as a common component filename extension to support
81
+    // some tools, although we do not recommend using it, see:
82
+    // https://github.com/facebookincubator/create-react-app/issues/290
83
+    // `web` extension prefixes have been added for better support
84
+    // for React Native Web.
85
+    extensions: ['.web.js', '.mjs', '.js', '.json', '.web.jsx', '.jsx'],
86
+    alias: {
87
+      
88
+      // Support React Native Web
89
+      // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
90
+      'react-native': 'react-native-web',
91
+    },
92
+    plugins: [
93
+      // Prevents users from importing files from outside of src/ (or node_modules/).
94
+      // This often causes confusion because we only process files within src/ with babel.
95
+      // To fix this, we prevent you from importing files out of src/ -- if you'd like to,
96
+      // please link the files into your node_modules/ and let module-resolution kick in.
97
+      // Make sure your source files are compiled, as they will not be processed in any way.
98
+      new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
99
+    ],
100
+  },
101
+  module: {
102
+    strictExportPresence: true,
103
+    rules: [
104
+      // TODO: Disable require.ensure as it's not a standard language feature.
105
+      // We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176.
106
+      // { parser: { requireEnsure: false } },
107
+
108
+      // First, run the linter.
109
+      // It's important to do this before Babel processes the JS.
110
+      {
111
+        test: /\.(js|jsx|mjs)$/,
112
+        enforce: 'pre',
113
+        use: [
114
+          {
115
+            options: {
116
+              formatter: eslintFormatter,
117
+              eslintPath: require.resolve('eslint'),
118
+              
119
+            },
120
+            loader: require.resolve('eslint-loader'),
121
+          },
122
+        ],
123
+        include: paths.appSrc,
124
+      },
125
+      {
126
+        // "oneOf" will traverse all following loaders until one will
127
+        // match the requirements. When no loader matches it will fall
128
+        // back to the "file" loader at the end of the loader list.
129
+        oneOf: [
130
+          // "url" loader works like "file" loader except that it embeds assets
131
+          // smaller than specified limit in bytes as data URLs to avoid requests.
132
+          // A missing `test` is equivalent to a match.
133
+          {
134
+            test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
135
+            loader: require.resolve('url-loader'),
136
+            options: {
137
+              limit: 10000,
138
+              name: 'static/media/[name].[hash:8].[ext]',
139
+            },
140
+          },
141
+          // Process JS with Babel.
142
+          {
143
+            test: /\.(js|jsx|mjs)$/,
144
+            include: paths.appSrc,
145
+            loader: require.resolve('babel-loader'),
146
+            options: {
147
+              
148
+              // This is a feature of `babel-loader` for webpack (not Babel itself).
149
+              // It enables caching results in ./node_modules/.cache/babel-loader/
150
+              // directory for faster rebuilds.
151
+              cacheDirectory: true,
152
+            },
153
+          },
154
+          // "postcss" loader applies autoprefixer to our CSS.
155
+          // "css" loader resolves paths in CSS and adds assets as dependencies.
156
+          // "style" loader turns CSS into JS modules that inject <style> tags.
157
+          // In production, we use a plugin to extract that CSS to a file, but
158
+          // in development "style" loader enables hot editing of CSS.
159
+          {
160
+            test: /\.css$/,
161
+            use: [
162
+              require.resolve('style-loader'),
163
+              {
164
+                loader: require.resolve('css-loader'),
165
+                options: {
166
+                  importLoaders: 1,
167
+                },
168
+              },
169
+              {
170
+                loader: require.resolve('postcss-loader'),
171
+                options: {
172
+                  // Necessary for external CSS imports to work
173
+                  // https://github.com/facebookincubator/create-react-app/issues/2677
174
+                  ident: 'postcss',
175
+                  plugins: () => [
176
+                    require('postcss-flexbugs-fixes'),
177
+                    autoprefixer({
178
+                      browsers: [
179
+                        '>1%',
180
+                        'last 4 versions',
181
+                        'Firefox ESR',
182
+                        'not ie < 9', // React doesn't support IE8 anyway
183
+                      ],
184
+                      flexbox: 'no-2009',
185
+                    }),
186
+                  ],
187
+                },
188
+              },
189
+            ],
190
+          },
191
+          // "file" loader makes sure those assets get served by WebpackDevServer.
192
+          // When you `import` an asset, you get its (virtual) filename.
193
+          // In production, they would get copied to the `build` folder.
194
+          // This loader doesn't use a "test" so it will catch all modules
195
+          // that fall through the other loaders.
196
+          {
197
+            // Exclude `js` files to keep "css" loader working as it injects
198
+            // its runtime that would otherwise processed through "file" loader.
199
+            // Also exclude `html` and `json` extensions so they get processed
200
+            // by webpacks internal loaders.
201
+            exclude: [/\.(js|jsx|mjs)$/, /\.html$/, /\.json$/],
202
+            loader: require.resolve('file-loader'),
203
+            options: {
204
+              name: 'static/media/[name].[hash:8].[ext]',
205
+            },
206
+          },
207
+        ],
208
+      },
209
+      // ** STOP ** Are you adding a new loader?
210
+      // Make sure to add the new loader(s) before the "file" loader.
211
+    ],
212
+  },
213
+  plugins: [
214
+    // Makes some environment variables available in index.html.
215
+    // The public URL is available as %PUBLIC_URL% in index.html, e.g.:
216
+    // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
217
+    // In development, this will be an empty string.
218
+    new InterpolateHtmlPlugin(env.raw),
219
+    // Generates an `index.html` file with the <script> injected.
220
+    new HtmlWebpackPlugin({
221
+      inject: true,
222
+      template: paths.appHtml,
223
+    }),
224
+    // Add module names to factory functions so they appear in browser profiler.
225
+    new webpack.NamedModulesPlugin(),
226
+    // Makes some environment variables available to the JS code, for example:
227
+    // if (process.env.NODE_ENV === 'development') { ... }. See `./env.js`.
228
+    new webpack.DefinePlugin(env.stringified),
229
+    // This is necessary to emit hot updates (currently CSS only):
230
+    new webpack.HotModuleReplacementPlugin(),
231
+    // Watcher doesn't work well if you mistype casing in a path so we use
232
+    // a plugin that prints an error when you attempt to do this.
233
+    // See https://github.com/facebookincubator/create-react-app/issues/240
234
+    new CaseSensitivePathsPlugin(),
235
+    // If you require a missing module and then `npm install` it, you still have
236
+    // to restart the development server for Webpack to discover it. This plugin
237
+    // makes the discovery automatic so you don't have to restart.
238
+    // See https://github.com/facebookincubator/create-react-app/issues/186
239
+    new WatchMissingNodeModulesPlugin(paths.appNodeModules),
240
+    // Moment.js is an extremely popular library that bundles large locale files
241
+    // by default due to how Webpack interprets its code. This is a practical
242
+    // solution that requires the user to opt into importing specific locales.
243
+    // https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
244
+    // You can remove this if you don't use Moment.js:
245
+    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
246
+  ],
247
+  // Some libraries import Node modules but don't use them in the browser.
248
+  // Tell Webpack to provide empty mocks for them so importing them works.
249
+  node: {
250
+    dgram: 'empty',
251
+    fs: 'empty',
252
+    net: 'empty',
253
+    tls: 'empty',
254
+    child_process: 'empty',
255
+  },
256
+  // Turn off performance hints during development because we don't do any
257
+  // splitting or minification in interest of speed. These warnings become
258
+  // cumbersome.
259
+  performance: {
260
+    hints: false,
261
+  },
262
+};

+ 342
- 0
config/webpack.config.lib.prod.js View File

@@ -0,0 +1,342 @@
1
+
2
+
3
+const autoprefixer = require('autoprefixer');
4
+const path = require('path');
5
+const webpack = require('webpack');
6
+const HtmlWebpackPlugin = require('html-webpack-plugin');
7
+const ExtractTextPlugin = require('extract-text-webpack-plugin');
8
+const ManifestPlugin = require('webpack-manifest-plugin');
9
+const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
10
+const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin');
11
+const eslintFormatter = require('react-dev-utils/eslintFormatter');
12
+const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
13
+const paths = require('./paths');
14
+const getClientEnvironment = require('./env');
15
+
16
+// Webpack uses `publicPath` to determine where the app is being served from.
17
+// It requires a trailing slash, or the file assets will get an incorrect path.
18
+const publicPath = paths.servedPath;
19
+// Some apps do not use client-side routing with pushState.
20
+// For these, "homepage" can be set to "." to enable relative asset paths.
21
+const shouldUseRelativeAssetPaths = publicPath === './';
22
+// Source maps are resource heavy and can cause out of memory issue for large source files.
23
+const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';
24
+// `publicUrl` is just like `publicPath`, but we will provide it to our app
25
+// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
26
+// Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
27
+const publicUrl = publicPath.slice(0, -1);
28
+// Get environment variables to inject into our app.
29
+const env = getClientEnvironment(publicUrl);
30
+
31
+// Assert this just to be safe.
32
+// Development builds of React are slow and not intended for production.
33
+if (env.stringified['process.env'].NODE_ENV !== '"production"') {
34
+  throw new Error('Production builds must have NODE_ENV=production.');
35
+}
36
+
37
+// Note: defined here because it will be used more than once.
38
+const cssFilename = 'lib/css/[name].css';
39
+
40
+// ExtractTextPlugin expects the build output to be flat.
41
+// (See https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/27)
42
+// However, our output is structured with css, js and media folders.
43
+// To have this structure working with relative paths, we have to use custom options.
44
+const extractTextPluginOptions = shouldUseRelativeAssetPaths
45
+  ? // Making sure that the publicPath goes back to to build folder.
46
+    { publicPath: Array(cssFilename.split('/').length).join('../') }
47
+  : {};
48
+
49
+// This is the production configuration.
50
+// It compiles slowly and is focused on producing a fast and minimal bundle.
51
+// The development configuration is different and lives in a separate file.
52
+module.exports = {
53
+  // Don't attempt to continue if there are any errors.
54
+  bail: true,
55
+  // We generate sourcemaps in production. This is slow but gives good results.
56
+  // You can exclude the *.map files from the build during deployment.
57
+  devtool: shouldUseSourceMap ? 'source-map' : false,
58
+  // In production, we only want to load the polyfills and the app code.
59
+  entry: [require.resolve('./polyfills'), paths.appIndexJs],
60
+  output: {
61
+    // The build folder.
62
+    path: paths.appBuild,
63
+    // Generated JS file names (with nested folders).
64
+    // There will be one main bundle, and one file per asynchronous chunk.
65
+    // We don't currently advertise code splitting but Webpack supports it.
66
+    filename: 'lib/js/[name].js',
67
+    chunkFilename: 'lib/js/[name].chunk.js',
68
+    // We inferred the "public path" (such as / or /my-project) from homepage.
69
+    publicPath: publicPath,
70
+    // Point sourcemap entries to original disk location (format as URL on Windows)
71
+    devtoolModuleFilenameTemplate: info =>
72
+      path
73
+        .relative(paths.appSrc, info.absoluteResourcePath)
74
+        .replace(/\\/g, '/'),
75
+  },
76
+  resolve: {
77
+    // This allows you to set a fallback for where Webpack should look for modules.
78
+    // We placed these paths second because we want `node_modules` to "win"
79
+    // if there are any conflicts. This matches Node resolution mechanism.
80
+    // https://github.com/facebookincubator/create-react-app/issues/253
81
+    modules: ['node_modules', paths.appNodeModules].concat(
82
+      // It is guaranteed to exist because we tweak it in `env.js`
83
+      process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
84
+    ),
85
+    // These are the reasonable defaults supported by the Node ecosystem.
86
+    // We also include JSX as a common component filename extension to support
87
+    // some tools, although we do not recommend using it, see:
88
+    // https://github.com/facebookincubator/create-react-app/issues/290
89
+    // `web` extension prefixes have been added for better support
90
+    // for React Native Web.
91
+    extensions: ['.web.js', '.mjs', '.js', '.json', '.web.jsx', '.jsx'],
92
+    alias: {
93
+      
94
+      // Support React Native Web
95
+      // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
96
+      'react-native': 'react-native-web',
97
+    },
98
+    plugins: [
99
+      // Prevents users from importing files from outside of src/ (or node_modules/).
100
+      // This often causes confusion because we only process files within src/ with babel.
101
+      // To fix this, we prevent you from importing files out of src/ -- if you'd like to,
102
+      // please link the files into your node_modules/ and let module-resolution kick in.
103
+      // Make sure your source files are compiled, as they will not be processed in any way.
104
+      new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
105
+    ],
106
+  },
107
+  module: {
108
+    strictExportPresence: true,
109
+    rules: [
110
+      // TODO: Disable require.ensure as it's not a standard language feature.
111
+      // We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176.
112
+      // { parser: { requireEnsure: false } },
113
+
114
+      // First, run the linter.
115
+      // It's important to do this before Babel processes the JS.
116
+      {
117
+        test: /\.(js|jsx|mjs)$/,
118
+        enforce: 'pre',
119
+        use: [
120
+          {
121
+            options: {
122
+              formatter: eslintFormatter,
123
+              eslintPath: require.resolve('eslint'),
124
+              
125
+            },
126
+            loader: require.resolve('eslint-loader'),
127
+          },
128
+        ],
129
+        include: paths.appSrc,
130
+      },
131
+      {
132
+        // "oneOf" will traverse all following loaders until one will
133
+        // match the requirements. When no loader matches it will fall
134
+        // back to the "file" loader at the end of the loader list.
135
+        oneOf: [
136
+          // "url" loader works just like "file" loader but it also embeds
137
+          // assets smaller than specified size as data URLs to avoid requests.
138
+          {
139
+            test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
140
+            loader: require.resolve('url-loader'),
141
+            options: {
142
+              limit: 10000,
143
+              name: 'static/media/[name].[hash:8].[ext]',
144
+            },
145
+          },
146
+          // Process JS with Babel.
147
+          {
148
+            test: /\.(js|jsx|mjs)$/,
149
+            include: paths.appSrc,
150
+            loader: require.resolve('babel-loader'),
151
+            options: {
152
+              
153
+              compact: true,
154
+            },
155
+          },
156
+          // The notation here is somewhat confusing.
157
+          // "postcss" loader applies autoprefixer to our CSS.
158
+          // "css" loader resolves paths in CSS and adds assets as dependencies.
159
+          // "style" loader normally turns CSS into JS modules injecting <style>,
160
+          // but unlike in development configuration, we do something different.
161
+          // `ExtractTextPlugin` first applies the "postcss" and "css" loaders
162
+          // (second argument), then grabs the result CSS and puts it into a
163
+          // separate file in our build process. This way we actually ship
164
+          // a single CSS file in production instead of JS code injecting <style>
165
+          // tags. If you use code splitting, however, any async bundles will still
166
+          // use the "style" loader inside the async code so CSS from them won't be
167
+          // in the main CSS file.
168
+          {
169
+            test: /\.css$/,
170
+            loader: ExtractTextPlugin.extract(
171
+              Object.assign(
172
+                {
173
+                  fallback: {
174
+                    loader: require.resolve('style-loader'),
175
+                    options: {
176
+                      hmr: false,
177
+                    },
178
+                  },
179
+                  use: [
180
+                    {
181
+                      loader: require.resolve('css-loader'),
182
+                      options: {
183
+                        importLoaders: 1,
184
+                        minimize: true,
185
+                        sourceMap: shouldUseSourceMap,
186
+                      },
187
+                    },
188
+                    {
189
+                      loader: require.resolve('postcss-loader'),
190
+                      options: {
191
+                        // Necessary for external CSS imports to work
192
+                        // https://github.com/facebookincubator/create-react-app/issues/2677
193
+                        ident: 'postcss',
194
+                        plugins: () => [
195
+                          require('postcss-flexbugs-fixes'),
196
+                          autoprefixer({
197
+                            browsers: [
198
+                              '>1%',
199
+                              'last 4 versions',
200
+                              'Firefox ESR',
201
+                              'not ie < 9', // React doesn't support IE8 anyway
202
+                            ],
203
+                            flexbox: 'no-2009',
204
+                          }),
205
+                        ],
206
+                      },
207
+                    },
208
+                  ],
209
+                },
210
+                extractTextPluginOptions
211
+              )
212
+            ),
213
+            // Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
214
+          },
215
+          // "file" loader makes sure assets end up in the `build` folder.
216
+          // When you `import` an asset, you get its filename.
217
+          // This loader doesn't use a "test" so it will catch all modules
218
+          // that fall through the other loaders.
219
+          {
220
+            loader: require.resolve('file-loader'),
221
+            // Exclude `js` files to keep "css" loader working as it injects
222
+            // it's runtime that would otherwise processed through "file" loader.
223
+            // Also exclude `html` and `json` extensions so they get processed
224
+            // by webpacks internal loaders.
225
+            exclude: [/\.(js|jsx|mjs)$/, /\.html$/, /\.json$/],
226
+            options: {
227
+              name: 'static/media/[name].[hash:8].[ext]',
228
+            },
229
+          },
230
+          // ** STOP ** Are you adding a new loader?
231
+          // Make sure to add the new loader(s) before the "file" loader.
232
+        ],
233
+      },
234
+    ],
235
+  },
236
+  plugins: [
237
+    // Makes some environment variables available in index.html.
238
+    // The public URL is available as %PUBLIC_URL% in index.html, e.g.:
239
+    // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
240
+    // In production, it will be an empty string unless you specify "homepage"
241
+    // in `package.json`, in which case it will be the pathname of that URL.
242
+    new InterpolateHtmlPlugin(env.raw),
243
+    // Generates an `index.html` file with the <script> injected.
244
+    new HtmlWebpackPlugin({
245
+      inject: true,
246
+      template: paths.appHtml,
247
+      minify: {
248
+        removeComments: true,
249
+        collapseWhitespace: true,
250
+        removeRedundantAttributes: true,
251
+        useShortDoctype: true,
252
+        removeEmptyAttributes: true,
253
+        removeStyleLinkTypeAttributes: true,
254
+        keepClosingSlash: true,
255
+        minifyJS: true,
256
+        minifyCSS: true,
257
+        minifyURLs: true,
258
+      },
259
+    }),
260
+    // Makes some environment variables available to the JS code, for example:
261
+    // if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
262
+    // It is absolutely essential that NODE_ENV was set to production here.
263
+    // Otherwise React will be compiled in the very slow development mode.
264
+    new webpack.DefinePlugin(env.stringified),
265
+    // Minify the code.
266
+    new webpack.optimize.UglifyJsPlugin({
267
+      compress: {
268
+        warnings: false,
269
+        // Disabled because of an issue with Uglify breaking seemingly valid code:
270
+        // https://github.com/facebookincubator/create-react-app/issues/2376
271
+        // Pending further investigation:
272
+        // https://github.com/mishoo/UglifyJS2/issues/2011
273
+        comparisons: false,
274
+      },
275
+      mangle: {
276
+        safari10: true,
277
+      },
278
+      output: {
279
+        comments: false,
280
+        // Turned on because emoji and regex is not minified properly using default
281
+        // https://github.com/facebookincubator/create-react-app/issues/2488
282
+        ascii_only: true,
283
+      },
284
+      sourceMap: shouldUseSourceMap,
285
+    }),
286
+    // Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`.
287
+    new ExtractTextPlugin({
288
+      filename: cssFilename,
289
+    }),
290
+    // Generate a manifest file which contains a mapping of all asset filenames
291
+    // to their corresponding output file so that tools can pick it up without
292
+    // having to parse `index.html`.
293
+    new ManifestPlugin({
294
+      fileName: 'asset-manifest.json',
295
+    }),
296
+    // Generate a service worker script that will precache, and keep up to date,
297
+    // the HTML & assets that are part of the Webpack build.
298
+    new SWPrecacheWebpackPlugin({
299
+      // By default, a cache-busting query parameter is appended to requests
300
+      // used to populate the caches, to ensure the responses are fresh.
301
+      // If a URL is already hashed by Webpack, then there is no concern
302
+      // about it being stale, and the cache-busting can be skipped.
303
+      dontCacheBustUrlsMatching: /\.\w{8}\./,
304
+      filename: 'service-worker.js',
305
+      logger(message) {
306
+        if (message.indexOf('Total precache size is') === 0) {
307
+          // This message occurs for every build and is a bit too noisy.
308
+          return;
309
+        }
310
+        if (message.indexOf('Skipping static resource') === 0) {
311
+          // This message obscures real errors so we ignore it.
312
+          // https://github.com/facebookincubator/create-react-app/issues/2612
313
+          return;
314
+        }
315
+        console.log(message);
316
+      },
317
+      minify: true,
318
+      // For unknown URLs, fallback to the index page
319
+      navigateFallback: publicUrl + '/index.html',
320
+      // Ignores URLs starting from /__ (useful for Firebase):
321
+      // https://github.com/facebookincubator/create-react-app/issues/2237#issuecomment-302693219
322
+      navigateFallbackWhitelist: [/^(?!\/__).*/],
323
+      // Don't precache sourcemaps (they're large) and build asset manifest:
324
+      staticFileGlobsIgnorePatterns: [/\.map$/, /asset-manifest\.json$/],
325
+    }),
326
+    // Moment.js is an extremely popular library that bundles large locale files
327
+    // by default due to how Webpack interprets its code. This is a practical
328
+    // solution that requires the user to opt into importing specific locales.
329
+    // https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
330
+    // You can remove this if you don't use Moment.js:
331
+    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
332
+  ],
333
+  // Some libraries import Node modules but don't use them in the browser.
334
+  // Tell Webpack to provide empty mocks for them so importing them works.
335
+  node: {
336
+    dgram: 'empty',
337
+    fs: 'empty',
338
+    net: 'empty',
339
+    tls: 'empty',
340
+    child_process: 'empty',
341
+  },
342
+};

+ 342
- 0
config/webpack.config.prod.js View File

@@ -0,0 +1,342 @@
1
+
2
+
3
+const autoprefixer = require('autoprefixer');
4
+const path = require('path');
5
+const webpack = require('webpack');
6
+const HtmlWebpackPlugin = require('html-webpack-plugin');
7
+const ExtractTextPlugin = require('extract-text-webpack-plugin');
8
+const ManifestPlugin = require('webpack-manifest-plugin');
9
+const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
10
+const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin');
11
+const eslintFormatter = require('react-dev-utils/eslintFormatter');
12
+const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
13
+const paths = require('./paths');
14
+const getClientEnvironment = require('./env');
15
+
16
+// Webpack uses `publicPath` to determine where the app is being served from.
17
+// It requires a trailing slash, or the file assets will get an incorrect path.
18
+const publicPath = paths.servedPath;
19
+// Some apps do not use client-side routing with pushState.
20
+// For these, "homepage" can be set to "." to enable relative asset paths.
21
+const shouldUseRelativeAssetPaths = publicPath === './';
22
+// Source maps are resource heavy and can cause out of memory issue for large source files.
23
+const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';
24
+// `publicUrl` is just like `publicPath`, but we will provide it to our app
25
+// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
26
+// Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
27
+const publicUrl = publicPath.slice(0, -1);
28
+// Get environment variables to inject into our app.
29
+const env = getClientEnvironment(publicUrl);
30
+
31
+// Assert this just to be safe.
32
+// Development builds of React are slow and not intended for production.
33
+if (env.stringified['process.env'].NODE_ENV !== '"production"') {
34
+  throw new Error('Production builds must have NODE_ENV=production.');
35
+}
36
+
37
+// Note: defined here because it will be used more than once.
38
+const cssFilename = 'static/css/[name].[contenthash:8].css';
39
+
40
+// ExtractTextPlugin expects the build output to be flat.
41
+// (See https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/27)
42
+// However, our output is structured with css, js and media folders.
43
+// To have this structure working with relative paths, we have to use custom options.
44
+const extractTextPluginOptions = shouldUseRelativeAssetPaths
45
+  ? // Making sure that the publicPath goes back to to build folder.
46
+    { publicPath: Array(cssFilename.split('/').length).join('../') }
47
+  : {};
48
+
49
+// This is the production configuration.
50
+// It compiles slowly and is focused on producing a fast and minimal bundle.
51
+// The development configuration is different and lives in a separate file.
52
+module.exports = {
53
+  // Don't attempt to continue if there are any errors.
54
+  bail: true,
55
+  // We generate sourcemaps in production. This is slow but gives good results.
56
+  // You can exclude the *.map files from the build during deployment.
57
+  devtool: shouldUseSourceMap ? 'source-map' : false,
58
+  // In production, we only want to load the polyfills and the app code.
59
+  entry: [require.resolve('./polyfills'), paths.appIndexJs],
60
+  output: {
61
+    // The build folder.
62
+    path: paths.appBuild,
63
+    // Generated JS file names (with nested folders).
64
+    // There will be one main bundle, and one file per asynchronous chunk.
65
+    // We don't currently advertise code splitting but Webpack supports it.
66
+    filename: 'static/js/[name].[chunkhash:8].js',
67
+    chunkFilename: 'static/js/[name].[chunkhash:8].chunk.js',
68
+    // We inferred the "public path" (such as / or /my-project) from homepage.
69
+    publicPath: publicPath,
70
+    // Point sourcemap entries to original disk location (format as URL on Windows)
71
+    devtoolModuleFilenameTemplate: info =>
72
+      path
73
+        .relative(paths.appSrc, info.absoluteResourcePath)
74
+        .replace(/\\/g, '/'),
75
+  },
76
+  resolve: {
77
+    // This allows you to set a fallback for where Webpack should look for modules.
78
+    // We placed these paths second because we want `node_modules` to "win"
79
+    // if there are any conflicts. This matches Node resolution mechanism.
80
+    // https://github.com/facebookincubator/create-react-app/issues/253
81
+    modules: ['node_modules', paths.appNodeModules].concat(
82
+      // It is guaranteed to exist because we tweak it in `env.js`
83
+      process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
84
+    ),
85
+    // These are the reasonable defaults supported by the Node ecosystem.
86
+    // We also include JSX as a common component filename extension to support
87
+    // some tools, although we do not recommend using it, see:
88
+    // https://github.com/facebookincubator/create-react-app/issues/290
89
+    // `web` extension prefixes have been added for better support
90
+    // for React Native Web.
91
+    extensions: ['.web.js', '.mjs', '.js', '.json', '.web.jsx', '.jsx'],
92
+    alias: {
93
+      
94
+      // Support React Native Web
95
+      // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
96
+      'react-native': 'react-native-web',
97
+    },
98
+    plugins: [
99
+      // Prevents users from importing files from outside of src/ (or node_modules/).
100
+      // This often causes confusion because we only process files within src/ with babel.
101
+      // To fix this, we prevent you from importing files out of src/ -- if you'd like to,
102
+      // please link the files into your node_modules/ and let module-resolution kick in.
103
+      // Make sure your source files are compiled, as they will not be processed in any way.
104
+      new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
105
+    ],
106
+  },
107
+  module: {
108
+    strictExportPresence: true,
109
+    rules: [
110
+      // TODO: Disable require.ensure as it's not a standard language feature.
111
+      // We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176.
112
+      // { parser: { requireEnsure: false } },
113
+
114
+      // First, run the linter.
115
+      // It's important to do this before Babel processes the JS.
116
+      {
117
+        test: /\.(js|jsx|mjs)$/,
118
+        enforce: 'pre',
119
+        use: [
120
+          {
121
+            options: {
122
+              formatter: eslintFormatter,
123
+              eslintPath: require.resolve('eslint'),
124
+              
125
+            },
126
+            loader: require.resolve('eslint-loader'),
127
+          },
128
+        ],
129
+        include: paths.appSrc,
130
+      },
131
+      {
132
+        // "oneOf" will traverse all following loaders until one will
133
+        // match the requirements. When no loader matches it will fall
134
+        // back to the "file" loader at the end of the loader list.
135
+        oneOf: [
136
+          // "url" loader works just like "file" loader but it also embeds
137
+          // assets smaller than specified size as data URLs to avoid requests.
138
+          {
139
+            test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
140
+            loader: require.resolve('url-loader'),
141
+            options: {
142
+              limit: 10000,
143
+              name: 'static/media/[name].[hash:8].[ext]',
144
+            },
145
+          },
146
+          // Process JS with Babel.
147
+          {
148
+            test: /\.(js|jsx|mjs)$/,
149
+            include: paths.appSrc,
150
+            loader: require.resolve('babel-loader'),
151
+            options: {
152
+              
153
+              compact: true,
154
+            },
155
+          },
156
+          // The notation here is somewhat confusing.
157
+          // "postcss" loader applies autoprefixer to our CSS.
158
+          // "css" loader resolves paths in CSS and adds assets as dependencies.
159
+          // "style" loader normally turns CSS into JS modules injecting <style>,
160
+          // but unlike in development configuration, we do something different.
161
+          // `ExtractTextPlugin` first applies the "postcss" and "css" loaders
162
+          // (second argument), then grabs the result CSS and puts it into a
163
+          // separate file in our build process. This way we actually ship
164
+          // a single CSS file in production instead of JS code injecting <style>
165
+          // tags. If you use code splitting, however, any async bundles will still
166
+          // use the "style" loader inside the async code so CSS from them won't be
167
+          // in the main CSS file.
168
+          {
169
+            test: /\.css$/,
170
+            loader: ExtractTextPlugin.extract(
171
+              Object.assign(
172
+                {
173
+                  fallback: {
174
+                    loader: require.resolve('style-loader'),
175
+                    options: {
176
+                      hmr: false,
177
+                    },
178
+                  },
179
+                  use: [
180
+                    {
181
+                      loader: require.resolve('css-loader'),
182
+                      options: {
183
+                        importLoaders: 1,
184
+                        minimize: true,
185
+                        sourceMap: shouldUseSourceMap,
186
+                      },
187
+                    },
188
+                    {
189
+                      loader: require.resolve('postcss-loader'),
190
+                      options: {
191
+                        // Necessary for external CSS imports to work
192
+                        // https://github.com/facebookincubator/create-react-app/issues/2677
193
+                        ident: 'postcss',
194
+                        plugins: () => [
195
+                          require('postcss-flexbugs-fixes'),
196
+                          autoprefixer({
197
+                            browsers: [
198
+                              '>1%',
199
+                              'last 4 versions',
200
+                              'Firefox ESR',
201
+                              'not ie < 9', // React doesn't support IE8 anyway
202
+                            ],
203
+                            flexbox: 'no-2009',
204
+                          }),
205
+                        ],
206
+                      },
207
+                    },
208
+                  ],
209
+                },
210
+                extractTextPluginOptions
211
+              )
212
+            ),
213
+            // Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
214
+          },
215
+          // "file" loader makes sure assets end up in the `build` folder.
216
+          // When you `import` an asset, you get its filename.
217
+          // This loader doesn't use a "test" so it will catch all modules
218
+          // that fall through the other loaders.
219
+          {
220
+            loader: require.resolve('file-loader'),
221
+            // Exclude `js` files to keep "css" loader working as it injects
222
+            // it's runtime that would otherwise processed through "file" loader.
223
+            // Also exclude `html` and `json` extensions so they get processed
224
+            // by webpacks internal loaders.
225
+            exclude: [/\.(js|jsx|mjs)$/, /\.html$/, /\.json$/],
226
+            options: {
227
+              name: 'static/media/[name].[hash:8].[ext]',
228
+            },
229
+          },
230
+          // ** STOP ** Are you adding a new loader?
231
+          // Make sure to add the new loader(s) before the "file" loader.
232
+        ],
233
+      },
234
+    ],
235
+  },
236
+  plugins: [
237
+    // Makes some environment variables available in index.html.
238
+    // The public URL is available as %PUBLIC_URL% in index.html, e.g.:
239
+    // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
240
+    // In production, it will be an empty string unless you specify "homepage"
241
+    // in `package.json`, in which case it will be the pathname of that URL.
242
+    new InterpolateHtmlPlugin(env.raw),
243
+    // Generates an `index.html` file with the <script> injected.
244
+    new HtmlWebpackPlugin({
245
+      inject: true,
246
+      template: paths.appHtml,
247
+      minify: {
248
+        removeComments: true,
249
+        collapseWhitespace: true,
250
+        removeRedundantAttributes: true,
251
+        useShortDoctype: true,
252
+        removeEmptyAttributes: true,
253
+        removeStyleLinkTypeAttributes: true,
254
+        keepClosingSlash: true,
255
+        minifyJS: true,
256
+        minifyCSS: true,
257
+        minifyURLs: true,
258
+      },
259
+    }),
260
+    // Makes some environment variables available to the JS code, for example:
261
+    // if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
262
+    // It is absolutely essential that NODE_ENV was set to production here.
263
+    // Otherwise React will be compiled in the very slow development mode.
264
+    new webpack.DefinePlugin(env.stringified),
265
+    // Minify the code.
266
+    new webpack.optimize.UglifyJsPlugin({
267
+      compress: {
268
+        warnings: false,
269
+        // Disabled because of an issue with Uglify breaking seemingly valid code:
270
+        // https://github.com/facebookincubator/create-react-app/issues/2376
271
+        // Pending further investigation:
272
+        // https://github.com/mishoo/UglifyJS2/issues/2011
273
+        comparisons: false,
274
+      },
275
+      mangle: {
276
+        safari10: true,
277
+      },
278
+      output: {
279
+        comments: false,
280
+        // Turned on because emoji and regex is not minified properly using default
281
+        // https://github.com/facebookincubator/create-react-app/issues/2488
282
+        ascii_only: true,
283
+      },
284
+      sourceMap: shouldUseSourceMap,
285
+    }),
286
+    // Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`.
287
+    new ExtractTextPlugin({
288
+      filename: cssFilename,
289
+    }),
290
+    // Generate a manifest file which contains a mapping of all asset filenames
291
+    // to their corresponding output file so that tools can pick it up without
292
+    // having to parse `index.html`.
293
+    new ManifestPlugin({
294
+      fileName: 'asset-manifest.json',
295
+    }),
296
+    // Generate a service worker script that will precache, and keep up to date,
297
+    // the HTML & assets that are part of the Webpack build.
298
+    new SWPrecacheWebpackPlugin({
299
+      // By default, a cache-busting query parameter is appended to requests
300
+      // used to populate the caches, to ensure the responses are fresh.
301
+      // If a URL is already hashed by Webpack, then there is no concern
302
+      // about it being stale, and the cache-busting can be skipped.
303
+      dontCacheBustUrlsMatching: /\.\w{8}\./,
304
+      filename: 'service-worker.js',
305
+      logger(message) {
306
+        if (message.indexOf('Total precache size is') === 0) {
307
+          // This message occurs for every build and is a bit too noisy.
308
+          return;
309
+        }
310
+        if (message.indexOf('Skipping static resource') === 0) {
311
+          // This message obscures real errors so we ignore it.
312
+          // https://github.com/facebookincubator/create-react-app/issues/2612
313
+          return;
314
+        }
315
+        console.log(message);
316
+      },
317
+      minify: true,
318
+      // For unknown URLs, fallback to the index page
319
+      navigateFallback: publicUrl + '/index.html',
320
+      // Ignores URLs starting from /__ (useful for Firebase):
321
+      // https://github.com/facebookincubator/create-react-app/issues/2237#issuecomment-302693219
322
+      navigateFallbackWhitelist: [/^(?!\/__).*/],
323
+      // Don't precache sourcemaps (they're large) and build asset manifest:
324
+      staticFileGlobsIgnorePatterns: [/\.map$/, /asset-manifest\.json$/],
325
+    }),
326
+    // Moment.js is an extremely popular library that bundles large locale files
327
+    // by default due to how Webpack interprets its code. This is a practical
328
+    // solution that requires the user to opt into importing specific locales.
329
+    // https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
330
+    // You can remove this if you don't use Moment.js:
331
+    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
332
+  ],
333
+  // Some libraries import Node modules but don't use them in the browser.
334
+  // Tell Webpack to provide empty mocks for them so importing them works.
335
+  node: {
336
+    dgram: 'empty',
337
+    fs: 'empty',
338
+    net: 'empty',
339
+    tls: 'empty',
340
+    child_process: 'empty',
341
+  },
342
+};

+ 95
- 0
config/webpackDevServer.config.js View File

@@ -0,0 +1,95 @@
1
+'use strict';
2
+
3
+const errorOverlayMiddleware = require('react-dev-utils/errorOverlayMiddleware');
4
+const noopServiceWorkerMiddleware = require('react-dev-utils/noopServiceWorkerMiddleware');
5
+const ignoredFiles = require('react-dev-utils/ignoredFiles');
6
+const config = require('./webpack.config.dev');
7
+const paths = require('./paths');
8
+
9
+const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
10
+const host = process.env.HOST || '0.0.0.0';
11
+
12
+module.exports = function(proxy, allowedHost) {
13
+  return {
14
+    // WebpackDevServer 2.4.3 introduced a security fix that prevents remote
15
+    // websites from potentially accessing local content through DNS rebinding:
16
+    // https://github.com/webpack/webpack-dev-server/issues/887
17
+    // https://medium.com/webpack/webpack-dev-server-middleware-security-issues-1489d950874a
18
+    // However, it made several existing use cases such as development in cloud
19
+    // environment or subdomains in development significantly more complicated:
20
+    // https://github.com/facebookincubator/create-react-app/issues/2271
21
+    // https://github.com/facebookincubator/create-react-app/issues/2233
22
+    // While we're investigating better solutions, for now we will take a
23
+    // compromise. Since our WDS configuration only serves files in the `public`
24
+    // folder we won't consider accessing them a vulnerability. However, if you
25
+    // use the `proxy` feature, it gets more dangerous because it can expose
26
+    // remote code execution vulnerabilities in backends like Django and Rails.
27
+    // So we will disable the host check normally, but enable it if you have
28
+    // specified the `proxy` setting. Finally, we let you override it if you
29
+    // really know what you're doing with a special environment variable.
30
+    disableHostCheck:
31
+      !proxy || process.env.DANGEROUSLY_DISABLE_HOST_CHECK === 'true',
32
+    // Enable gzip compression of generated files.
33
+    compress: true,
34
+    // Silence WebpackDevServer's own logs since they're generally not useful.
35
+    // It will still show compile warnings and errors with this setting.
36
+    clientLogLevel: 'none',
37
+    // By default WebpackDevServer serves physical files from current directory
38
+    // in addition to all the virtual build products that it serves from memory.
39
+    // This is confusing because those files won’t automatically be available in
40
+    // production build folder unless we copy them. However, copying the whole
41
+    // project directory is dangerous because we may expose sensitive files.
42
+    // Instead, we establish a convention that only files in `public` directory
43
+    // get served. Our build script will copy `public` into the `build` folder.
44
+    // In `index.html`, you can get URL of `public` folder with %PUBLIC_URL%:
45
+    // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
46
+    // In JavaScript code, you can access it with `process.env.PUBLIC_URL`.
47
+    // Note that we only recommend to use `public` folder as an escape hatch
48
+    // for files like `favicon.ico`, `manifest.json`, and libraries that are
49
+    // for some reason broken when imported through Webpack. If you just want to
50
+    // use an image, put it in `src` and `import` it from JavaScript instead.
51
+    contentBase: paths.appPublic,
52
+    // By default files from `contentBase` will not trigger a page reload.
53
+    watchContentBase: true,
54
+    // Enable hot reloading server. It will provide /sockjs-node/ endpoint
55
+    // for the WebpackDevServer client so it can learn when the files were
56
+    // updated. The WebpackDevServer client is included as an entry point
57
+    // in the Webpack development configuration. Note that only changes
58
+    // to CSS are currently hot reloaded. JS changes will refresh the browser.
59
+    hot: true,
60
+    // It is important to tell WebpackDevServer to use the same "root" path
61
+    // as we specified in the config. In development, we always serve from /.
62
+    publicPath: config.output.publicPath,
63
+    // WebpackDevServer is noisy by default so we emit custom message instead
64
+    // by listening to the compiler events with `compiler.plugin` calls above.
65
+    quiet: true,
66
+    // Reportedly, this avoids CPU overload on some systems.
67
+    // https://github.com/facebookincubator/create-react-app/issues/293
68
+    // src/node_modules is not ignored to support absolute imports
69
+    // https://github.com/facebookincubator/create-react-app/issues/1065
70
+    watchOptions: {
71
+      ignored: ignoredFiles(paths.appSrc),
72
+    },
73
+    // Enable HTTPS if the HTTPS environment variable is set to 'true'
74
+    https: protocol === 'https',
75
+    host: host,
76
+    overlay: false,
77
+    historyApiFallback: {
78
+      // Paths with dots should still use the history fallback.
79
+      // See https://github.com/facebookincubator/create-react-app/issues/387.
80
+      disableDotRule: true,
81
+    },
82
+    public: allowedHost,
83
+    proxy,
84
+    before(app) {
85
+      // This lets us open files from the runtime error overlay.
86
+      app.use(errorOverlayMiddleware());
87
+      // This service worker file is effectively a 'no-op' that will reset any
88
+      // previous service worker registered for the same host:port combination.
89
+      // We do this in development to avoid hitting the production cache if
90
+      // it used the same host and port.
91
+      // https://github.com/facebookincubator/create-react-app/issues/2272#issuecomment-302832432
92
+      app.use(noopServiceWorkerMiddleware());
93
+    },
94
+  };
95
+};

+ 86
- 7
package.json View File

@@ -2,22 +2,101 @@
2 2
   "name": "editor",
3 3
   "version": "0.1.0",
4 4
   "private": true,
5
-  "main": "src/index.js",
5
+  "main": "build/lib/js/index.js",
6 6
   "dependencies": {
7 7
     "@fortawesome/fontawesome-svg-core": "^1.2.4",
8 8
     "@fortawesome/free-solid-svg-icons": "^5.3.1",
9 9
     "@fortawesome/react-fontawesome": "^0.1.3",
10
+    "autoprefixer": "7.1.6",
11
+    "babel-core": "6.26.0",
12
+    "babel-eslint": "7.2.3",
13
+    "babel-jest": "20.0.3",
14
+    "babel-loader": "7.1.2",
15
+    "babel-preset-react-app": "^3.1.2",
16
+    "babel-runtime": "6.26.0",
10 17
     "braft-editor": "^2.0.5",
18
+    "case-sensitive-paths-webpack-plugin": "2.1.1",
19
+    "chalk": "1.1.3",
20
+    "css-loader": "0.28.7",
21
+    "dotenv": "4.0.0",
22
+    "dotenv-expand": "4.2.0",
23
+    "eslint": "4.10.0",
24
+    "eslint-config-react-app": "^2.1.0",
25
+    "eslint-loader": "1.9.0",
26
+    "eslint-plugin-flowtype": "2.39.1",
27
+    "eslint-plugin-import": "2.8.0",
28
+    "eslint-plugin-jsx-a11y": "5.1.1",
29
+    "eslint-plugin-react": "7.4.0",
30
+    "extract-text-webpack-plugin": "3.0.2",
31
+    "file-loader": "1.1.5",
32
+    "fs-extra": "3.0.1",
33
+    "html-webpack-plugin": "2.29.0",
34
+    "jest": "20.0.4",
35
+    "object-assign": "4.1.1",
36
+    "postcss-flexbugs-fixes": "3.2.0",
37
+    "postcss-loader": "2.0.8",
38
+    "promise": "8.0.1",
39
+    "raf": "3.4.0",
11 40
     "react": "^16.5.0",
41
+    "react-dev-utils": "^5.0.2",
12 42
     "react-dom": "^16.5.0",
13 43
     "react-mde": "^5.8.0",
14
-    "react-scripts": "1.1.5",
15
-    "showdown": "^1.8.6"
44
+    "resolve": "1.6.0",
45
+    "showdown": "^1.8.6",
46
+    "style-loader": "0.19.0",
47
+    "sw-precache-webpack-plugin": "0.11.4",
48
+    "url-loader": "0.6.2",
49
+    "webpack": "3.8.1",
50
+    "webpack-dev-server": "2.11.3",
51
+    "webpack-manifest-plugin": "1.3.2",
52
+    "whatwg-fetch": "2.0.3"
16 53
   },
17 54
   "scripts": {
18
-    "start": "react-scripts start",
19
-    "build": "react-scripts build",
20
-    "test": "react-scripts test --env=jsdom",
21
-    "eject": "react-scripts eject"
55
+    "start": "node scripts/start.js",
56
+    "build": "node scripts/build.js",
57
+    "build:lib": "node scripts/build.lib.js",
58
+    "test": "node scripts/test.js --env=jsdom"
59
+  },
60
+  "jest": {
61
+    "collectCoverageFrom": [
62
+      "src/**/*.{js,jsx,mjs}"
63
+    ],
64
+    "setupFiles": [
65
+      "<rootDir>/config/polyfills.js"
66
+    ],
67
+    "testMatch": [
68
+      "<rootDir>/src/**/__tests__/**/*.{js,jsx,mjs}",
69
+      "<rootDir>/src/**/?(*.)(spec|test).{js,jsx,mjs}"
70
+    ],
71
+    "testEnvironment": "node",
72
+    "testURL": "http://localhost",
73
+    "transform": {
74
+      "^.+\\.(js|jsx|mjs)$": "<rootDir>/node_modules/babel-jest",
75
+      "^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
76
+      "^(?!.*\\.(js|jsx|mjs|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
77
+    },
78
+    "transformIgnorePatterns": [
79
+      "[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs)$"
80
+    ],
81
+    "moduleNameMapper": {
82
+      "^react-native$": "react-native-web"
83
+    },
84
+    "moduleFileExtensions": [
85
+      "web.js",
86
+      "js",
87
+      "json",
88
+      "web.jsx",
89
+      "jsx",
90
+      "node",
91
+      "mjs"
92
+    ]
93
+  },
94
+  "babel": {
95
+    "presets": [
96
+      "react-app"
97
+    ]
98
+  },
99
+  "eslintConfig": {
100
+    "extends": "react-app"
22 101
   }
23 102
 }

+ 150
- 0
scripts/build.js View File

@@ -0,0 +1,150 @@
1
+'use strict';
2
+
3
+// Do this as the first thing so that any code reading it knows the right env.
4
+process.env.BABEL_ENV = 'production';
5
+process.env.NODE_ENV = 'production';
6
+
7
+// Makes the script crash on unhandled rejections instead of silently
8
+// ignoring them. In the future, promise rejections that are not handled will
9
+// terminate the Node.js process with a non-zero exit code.
10
+process.on('unhandledRejection', err => {
11
+  throw err;
12
+});
13
+
14
+// Ensure environment variables are read.
15
+require('../config/env');
16
+
17
+const path = require('path');
18
+const chalk = require('chalk');
19
+const fs = require('fs-extra');
20
+const webpack = require('webpack');
21
+const config = require('../config/webpack.config.prod');
22
+const paths = require('../config/paths');
23
+const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
24
+const formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
25
+const printHostingInstructions = require('react-dev-utils/printHostingInstructions');
26
+const FileSizeReporter = require('react-dev-utils/FileSizeReporter');
27
+const printBuildError = require('react-dev-utils/printBuildError');
28
+
29
+const measureFileSizesBeforeBuild =
30
+  FileSizeReporter.measureFileSizesBeforeBuild;
31
+const printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild;
32
+const useYarn = fs.existsSync(paths.yarnLockFile);
33
+
34
+// These sizes are pretty large. We'll warn for bundles exceeding them.
35
+const WARN_AFTER_BUNDLE_GZIP_SIZE = 512 * 1024;
36
+const WARN_AFTER_CHUNK_GZIP_SIZE = 1024 * 1024;
37
+
38
+// Warn and crash if required files are missing
39
+if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
40
+  process.exit(1);
41
+}
42
+
43
+// First, read the current file sizes in build directory.
44
+// This lets us display how much they changed later.
45
+measureFileSizesBeforeBuild(paths.appBuild)
46
+  .then(previousFileSizes => {
47
+    // Remove all content but keep the directory so that
48
+    // if you're in it, you don't end up in Trash
49
+    fs.emptyDirSync(paths.appBuild);
50
+    // Merge with the public folder
51
+    copyPublicFolder();
52
+    // Start the webpack build
53
+    return build(previousFileSizes);
54
+  })
55
+  .then(
56
+    ({ stats, previousFileSizes, warnings }) => {
57
+      if (warnings.length) {
58
+        console.log(chalk.yellow('Compiled with warnings.\n'));
59
+        console.log(warnings.join('\n\n'));
60
+        console.log(
61
+          '\nSearch for the ' +
62
+            chalk.underline(chalk.yellow('keywords')) +
63
+            ' to learn more about each warning.'
64
+        );
65
+        console.log(
66
+          'To ignore, add ' +
67
+            chalk.cyan('// eslint-disable-next-line') +
68
+            ' to the line before.\n'
69
+        );
70
+      } else {
71
+        console.log(chalk.green('Compiled successfully.\n'));
72
+      }
73
+
74
+      console.log('File sizes after gzip:\n');
75
+      printFileSizesAfterBuild(
76
+        stats,
77
+        previousFileSizes,
78
+        paths.appBuild,
79
+        WARN_AFTER_BUNDLE_GZIP_SIZE,
80
+        WARN_AFTER_CHUNK_GZIP_SIZE
81
+      );
82
+      console.log();
83
+
84
+      const appPackage = require(paths.appPackageJson);
85
+      const publicUrl = paths.publicUrl;
86
+      const publicPath = config.output.publicPath;
87
+      const buildFolder = path.relative(process.cwd(), paths.appBuild);
88
+      printHostingInstructions(
89
+        appPackage,
90
+        publicUrl,
91
+        publicPath,
92
+        buildFolder,
93
+        useYarn
94
+      );
95
+    },
96
+    err => {
97
+      console.log(chalk.red('Failed to compile.\n'));
98
+      printBuildError(err);
99
+      process.exit(1);
100
+    }
101
+  );
102
+
103
+// Create the production build and print the deployment instructions.
104
+function build(previousFileSizes) {
105
+  console.log('Creating an optimized production build...');
106
+
107
+  let compiler = webpack(config);
108
+  return new Promise((resolve, reject) => {
109
+    compiler.run((err, stats) => {
110
+      if (err) {
111
+        return reject(err);
112
+      }
113
+      const messages = formatWebpackMessages(stats.toJson({}, true));
114
+      if (messages.errors.length) {
115
+        // Only keep the first error. Others are often indicative
116
+        // of the same problem, but confuse the reader with noise.
117
+        if (messages.errors.length > 1) {
118
+          messages.errors.length = 1;
119
+        }
120
+        return reject(new Error(messages.errors.join('\n\n')));
121
+      }
122
+      if (
123
+        process.env.CI &&
124
+        (typeof process.env.CI !== 'string' ||
125
+          process.env.CI.toLowerCase() !== 'false') &&
126
+        messages.warnings.length
127
+      ) {
128
+        console.log(
129
+          chalk.yellow(
130
+            '\nTreating warnings as errors because process.env.CI = true.\n' +
131
+              'Most CI servers set it automatically.\n'
132
+          )
133
+        );
134
+        return reject(new Error(messages.warnings.join('\n\n')));
135
+      }
136
+      return resolve({
137
+        stats,
138
+        previousFileSizes,
139
+        warnings: messages.warnings,
140
+      });
141
+    });
142
+  });
143
+}
144
+
145
+function copyPublicFolder() {
146
+  fs.copySync(paths.appPublic, paths.appBuild, {
147
+    dereference: true,
148
+    filter: file => file !== paths.appHtml,
149
+  });
150
+}

+ 150
- 0
scripts/build.lib.js View File

@@ -0,0 +1,150 @@
1
+
2
+
3
+// Do this as the first thing so that any code reading it knows the right env.
4
+process.env.BABEL_ENV = 'production';
5
+process.env.NODE_ENV = 'production';
6
+
7
+// Makes the script crash on unhandled rejections instead of silently
8
+// ignoring them. In the future, promise rejections that are not handled will
9
+// terminate the Node.js process with a non-zero exit code.
10
+process.on('unhandledRejection', err => {
11
+  throw err;
12
+});
13
+
14
+// Ensure environment variables are read.
15
+require('../config/env');
16
+
17
+const path = require('path');
18
+const chalk = require('chalk');
19
+const fs = require('fs-extra');
20
+const webpack = require('webpack');
21
+const config = require('../config/webpack.config.lib.prod');
22
+const paths = require('../config/paths');
23
+const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
24
+const formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
25
+const printHostingInstructions = require('react-dev-utils/printHostingInstructions');
26
+const FileSizeReporter = require('react-dev-utils/FileSizeReporter');
27
+const printBuildError = require('react-dev-utils/printBuildError');
28
+
29
+const measureFileSizesBeforeBuild =
30
+  FileSizeReporter.measureFileSizesBeforeBuild;
31
+const printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild;
32
+const useYarn = fs.existsSync(paths.yarnLockFile);
33
+
34
+// These sizes are pretty large. We'll warn for bundles exceeding them.
35
+const WARN_AFTER_BUNDLE_GZIP_SIZE = 512 * 1024;
36
+const WARN_AFTER_CHUNK_GZIP_SIZE = 1024 * 1024;
37
+
38
+// Warn and crash if required files are missing
39
+if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
40
+  process.exit(1);
41
+}
42
+
43
+// First, read the current file sizes in build directory.
44
+// This lets us display how much they changed later.
45
+measureFileSizesBeforeBuild(paths.appBuild)
46
+  .then(previousFileSizes => {
47
+    // Remove all content but keep the directory so that
48
+    // if you're in it, you don't end up in Trash
49
+    fs.emptyDirSync(paths.appBuild);
50
+    // Merge with the public folder
51
+    copyPublicFolder();
52
+    // Start the webpack build
53
+    return build(previousFileSizes);
54
+  })
55
+  .then(
56
+    ({ stats, previousFileSizes, warnings }) => {
57
+      if (warnings.length) {
58
+        console.log(chalk.yellow('Compiled with warnings.\n'));
59
+        console.log(warnings.join('\n\n'));
60
+        console.log(
61
+          '\nSearch for the ' +
62
+            chalk.underline(chalk.yellow('keywords')) +
63
+            ' to learn more about each warning.'
64
+        );
65
+        console.log(
66
+          'To ignore, add ' +
67
+            chalk.cyan('// eslint-disable-next-line') +
68
+            ' to the line before.\n'
69
+        );
70
+      } else {
71
+        console.log(chalk.green('Compiled successfully.\n'));
72
+      }
73
+
74
+      console.log('File sizes after gzip:\n');
75
+      printFileSizesAfterBuild(
76
+        stats,
77
+        previousFileSizes,
78
+        paths.appBuild,
79
+        WARN_AFTER_BUNDLE_GZIP_SIZE,
80
+        WARN_AFTER_CHUNK_GZIP_SIZE
81
+      );
82
+      console.log();
83
+
84
+      const appPackage = require(paths.appPackageJson);
85
+      const publicUrl = paths.publicUrl;
86
+      const publicPath = config.output.publicPath;
87
+      const buildFolder = path.relative(process.cwd(), paths.appBuild);
88
+      printHostingInstructions(
89
+        appPackage,
90
+        publicUrl,
91
+        publicPath,
92
+        buildFolder,
93
+        useYarn
94
+      );
95
+    },
96
+    err => {
97
+      console.log(chalk.red('Failed to compile.\n'));
98
+      printBuildError(err);
99
+      process.exit(1);
100
+    }
101
+  );
102
+
103
+// Create the production build and print the deployment instructions.
104
+function build(previousFileSizes) {
105
+  console.log('Creating an optimized production build...');
106
+
107
+  let compiler = webpack(config);
108
+  return new Promise((resolve, reject) => {
109
+    compiler.run((err, stats) => {
110
+      if (err) {
111
+        return reject(err);
112
+      }
113
+      const messages = formatWebpackMessages(stats.toJson({}, true));
114
+      if (messages.errors.length) {
115
+        // Only keep the first error. Others are often indicative
116
+        // of the same problem, but confuse the reader with noise.
117
+        if (messages.errors.length > 1) {
118
+          messages.errors.length = 1;
119
+        }
120
+        return reject(new Error(messages.errors.join('\n\n')));
121
+      }
122
+      if (
123
+        process.env.CI &&
124
+        (typeof process.env.CI !== 'string' ||
125
+          process.env.CI.toLowerCase() !== 'false') &&
126
+        messages.warnings.length
127
+      ) {
128
+        console.log(
129
+          chalk.yellow(
130
+            '\nTreating warnings as errors because process.env.CI = true.\n' +
131
+              'Most CI servers set it automatically.\n'
132
+          )
133
+        );
134
+        return reject(new Error(messages.warnings.join('\n\n')));
135
+      }
136
+      return resolve({
137
+        stats,
138
+        previousFileSizes,
139
+        warnings: messages.warnings,
140
+      });
141
+    });
142
+  });
143
+}
144
+
145
+function copyPublicFolder() {
146
+  fs.copySync(paths.appPublic, paths.appBuild, {
147
+    dereference: true,
148
+    filter: file => file !== paths.appHtml,
149
+  });
150
+}

+ 107
- 0
scripts/start.js View File

@@ -0,0 +1,107 @@
1
+'use strict';
2
+
3
+// Do this as the first thing so that any code reading it knows the right env.
4
+process.env.BABEL_ENV = 'development';
5
+process.env.NODE_ENV = 'development';
6
+
7
+// Makes the script crash on unhandled rejections instead of silently
8
+// ignoring them. In the future, promise rejections that are not handled will
9
+// terminate the Node.js process with a non-zero exit code.
10
+process.on('unhandledRejection', err => {
11
+  throw err;
12
+});
13
+
14
+// Ensure environment variables are read.
15
+require('../config/env');
16
+
17
+const fs = require('fs');
18
+const chalk = require('chalk');
19
+const webpack = require('webpack');
20
+const WebpackDevServer = require('webpack-dev-server');
21
+const clearConsole = require('react-dev-utils/clearConsole');
22
+const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
23
+const {
24
+  choosePort,
25
+  createCompiler,
26
+  prepareProxy,
27
+  prepareUrls,
28
+} = require('react-dev-utils/WebpackDevServerUtils');
29
+const openBrowser = require('react-dev-utils/openBrowser');
30
+const paths = require('../config/paths');
31
+const config = require('../config/webpack.config.dev');
32
+const createDevServerConfig = require('../config/webpackDevServer.config');
33
+
34
+const useYarn = fs.existsSync(paths.yarnLockFile);
35
+const isInteractive = process.stdout.isTTY;
36
+
37
+// Warn and crash if required files are missing
38
+if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
39
+  process.exit(1);
40
+}
41
+
42
+// Tools like Cloud9 rely on this.
43
+const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000;
44
+const HOST = process.env.HOST || '0.0.0.0';
45
+
46
+if (process.env.HOST) {
47
+  console.log(
48
+    chalk.cyan(
49
+      `Attempting to bind to HOST environment variable: ${chalk.yellow(
50
+        chalk.bold(process.env.HOST)
51
+      )}`
52
+    )
53
+  );
54
+  console.log(
55
+    `If this was unintentional, check that you haven't mistakenly set it in your shell.`
56
+  );
57
+  console.log(`Learn more here: ${chalk.yellow('http://bit.ly/2mwWSwH')}`);
58
+  console.log();
59
+}
60
+
61
+// We attempt to use the default port but if it is busy, we offer the user to
62
+// run on a different port. `choosePort()` Promise resolves to the next free port.
63
+choosePort(HOST, DEFAULT_PORT)
64
+  .then(port => {
65
+    if (port == null) {
66
+      // We have not found a port.
67
+      return;
68
+    }
69
+    const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
70
+    const appName = require(paths.appPackageJson).name;
71
+    const urls = prepareUrls(protocol, HOST, port);
72
+    // Create a webpack compiler that is configured with custom messages.
73
+    const compiler = createCompiler(webpack, config, appName, urls, useYarn);
74
+    // Load proxy config
75
+    const proxySetting = require(paths.appPackageJson).proxy;
76
+    const proxyConfig = prepareProxy(proxySetting, paths.appPublic);
77
+    // Serve webpack assets generated by the compiler over a web sever.
78
+    const serverConfig = createDevServerConfig(
79
+      proxyConfig,
80
+      urls.lanUrlForConfig
81
+    );
82
+    const devServer = new WebpackDevServer(compiler, serverConfig);
83
+    // Launch WebpackDevServer.
84
+    devServer.listen(port, HOST, err => {
85
+      if (err) {
86
+        return console.log(err);
87
+      }
88
+      if (isInteractive) {
89
+        clearConsole();
90
+      }
91
+      console.log(chalk.cyan('Starting the development server...\n'));
92
+      openBrowser(urls.localUrlForBrowser);
93
+    });
94
+
95
+    ['SIGINT', 'SIGTERM'].forEach(function(sig) {
96
+      process.on(sig, function() {
97
+        devServer.close();
98
+        process.exit();
99
+      });
100
+    });
101
+  })
102
+  .catch(err => {
103
+    if (err && err.message) {
104
+      console.log(err.message);
105
+    }
106
+    process.exit(1);
107
+  });

+ 27
- 0
scripts/test.js View File

@@ -0,0 +1,27 @@
1
+'use strict';
2
+
3
+// Do this as the first thing so that any code reading it knows the right env.
4
+process.env.BABEL_ENV = 'test';
5
+process.env.NODE_ENV = 'test';
6
+process.env.PUBLIC_URL = '';
7
+
8
+// Makes the script crash on unhandled rejections instead of silently
9
+// ignoring them. In the future, promise rejections that are not handled will
10
+// terminate the Node.js process with a non-zero exit code.
11
+process.on('unhandledRejection', err => {
12
+  throw err;
13
+});
14
+
15
+// Ensure environment variables are read.
16
+require('../config/env');
17
+
18
+const jest = require('jest');
19
+let argv = process.argv.slice(2);
20
+
21
+// Watch unless on CI or in coverage mode
22
+if (!process.env.CI && argv.indexOf('--coverage') < 0) {
23
+  argv.push('--watch');
24
+}
25
+
26
+
27
+jest.run(argv);

+ 1
- 46
yarn.lock View File

@@ -3193,7 +3193,7 @@ fs.realpath@^1.0.0:
3193 3193
   version "1.0.0"
3194 3194
   resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f"
3195 3195
 
3196
-fsevents@^1.1.3, fsevents@^1.2.2:
3196
+fsevents@^1.2.2:
3197 3197
   version "1.2.4"
3198 3198
   resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-1.2.4.tgz#f41dcb1af2582af3692da36fc55cbd8e1041c426"
3199 3199
   dependencies:
@@ -6504,51 +6504,6 @@ react-mde@^5.8.0:
6504 6504
     classnames "^2.2.5"
6505 6505
     npm "^6.1.0"
6506 6506
 
6507
-react-scripts@1.1.5:
6508
-  version "1.1.5"
6509
-  resolved "https://registry.yarnpkg.com/react-scripts/-/react-scripts-1.1.5.tgz#3041610ab0826736b52197711a4c4e3756e97768"
6510
-  dependencies:
6511
-    autoprefixer "7.1.6"
6512
-    babel-core "6.26.0"
6513
-    babel-eslint "7.2.3"
6514
-    babel-jest "20.0.3"
6515
-    babel-loader "7.1.2"
6516
-    babel-preset-react-app "^3.1.2"
6517
-    babel-runtime "6.26.0"
6518
-    case-sensitive-paths-webpack-plugin "2.1.1"
6519
-    chalk "1.1.3"
6520
-    css-loader "0.28.7"
6521
-    dotenv "4.0.0"
6522
-    dotenv-expand "4.2.0"
6523
-    eslint "4.10.0"
6524
-    eslint-config-react-app "^2.1.0"
6525
-    eslint-loader "1.9.0"
6526
-    eslint-plugin-flowtype "2.39.1"
6527
-    eslint-plugin-import "2.8.0"
6528
-    eslint-plugin-jsx-a11y "5.1.1"
6529
-    eslint-plugin-react "7.4.0"
6530
-    extract-text-webpack-plugin "3.0.2"
6531
-    file-loader "1.1.5"
6532
-    fs-extra "3.0.1"
6533
-    html-webpack-plugin "2.29.0"
6534
-    jest "20.0.4"
6535
-    object-assign "4.1.1"
6536
-    postcss-flexbugs-fixes "3.2.0"
6537
-    postcss-loader "2.0.8"
6538
-    promise "8.0.1"
6539
-    raf "3.4.0"
6540
-    react-dev-utils "^5.0.2"
6541
-    resolve "1.6.0"
6542
-    style-loader "0.19.0"
6543
-    sw-precache-webpack-plugin "0.11.4"
6544
-    url-loader "0.6.2"
6545
-    webpack "3.8.1"
6546
-    webpack-dev-server "2.11.3"
6547
-    webpack-manifest-plugin "1.3.2"
6548
-    whatwg-fetch "2.0.3"
6549
-  optionalDependencies:
6550
-    fsevents "^1.1.3"
6551
-
6552 6507
 react@^16.5.0:
6553 6508
   version "16.5.0"
6554 6509
   resolved "https://registry.yarnpkg.com/react/-/react-16.5.0.tgz#f2c1e754bf9751a549d9c6d9aca41905beb56575"