Rewrite frontend using create-react-app

This commit is contained in:
MICHAEL JACKSON 2017-03-25 23:53:54 -07:00
parent 69a578fcda
commit 0f5c584104
60 changed files with 20489 additions and 18930 deletions

View File

@ -1,26 +0,0 @@
{
"parser": "babel-eslint",
"plugins": [
"import",
"react"
],
"env": {
"es6": true,
"node": true
},
"extends": [
"eslint:recommended",
"plugin:import/errors",
"plugin:react/recommended"
],
"settings": {
"import/resolver": "webpack"
},
"rules": {
"array-bracket-spacing": [ 2, "always" ],
"eqeqeq": [ 2, "smart" ],
"prefer-arrow-callback": 2,
"react/no-danger": 0,
"semi": [ 2, "never" ]
}
}

21
.gitignore vendored
View File

@ -1,3 +1,18 @@
stats.json
public/__assets__
lib
# See https://help.github.com/ignore-files/ for more about ignoring files.
# dependencies
/node_modules
# testing
/coverage
# production
/build
# misc
.DS_Store
.env
npm-debug.log*
yarn-debug.log*
yarn-error.log*

View File

@ -1 +1 @@
web: node lib/server
web: node server.js

View File

@ -1 +1 @@
web: NODE_ENV=development node -r ./modules/register.js modules/server
web: NODE_ENV=development node server.js

View File

@ -1,3 +1,11 @@
The website for [unpkg](https://unpkg.com), built using [web-starter](https://github.com/mjackson/web-starter).
# unpkg
If you're interested in learning how the server works or you'd like to open an issue, you probably want [unpkg/npm-http-server](https://github.com/unpkg/npm-http-server)
[unpkg](https://unpkg.com) is a fast, global CDN for everything on [npm](https://www.npmjs.com/).
The project is maintained by [React Training](https://reacttraining.com) with sponsorship from [Cloudflare](https://cloudflare.com) and [Heroku](https://heroku.com).
## Development
The website was built using [create-react-app](https://github.com/facebookincubator/create-react-app). This is the app you see when you run `yarn start`. However, none of the package links will work.
To start the backend, use `yarn run serve`. This will start the backend so the website (which is really just a static HTML file) can serve as a proxy for package requests.

View File

@ -2,7 +2,7 @@ unpkg is an [open source](https://github.com/mjackson/unpkg) project built by me
<div class="about-logos">
<div class="about-logo">
<a href="https://reacttraining.com"><img src="../ReactTrainingLogo.png"></a>
<a href="https://reacttraining.com"><img src="./ReactTrainingLogo.png"></a>
</div>
</div>
@ -14,10 +14,10 @@ The fast, global infrastructure that powers unpkg is generously donated by [Clou
<div class="about-logos">
<div class="about-logo">
<a href="https://www.cloudflare.com"><img src="../CloudflareLogo.png"></a>
<a href="https://www.cloudflare.com"><img src="./CloudflareLogo.png"></a>
</div>
<div class="about-logo">
<a href="https://www.heroku.com"><img src="../HerokuLogo.png"></a>
<a href="https://www.heroku.com"><img src="./HerokuLogo.png"></a>
</div>
</div>

20
client/App.js Normal file
View File

@ -0,0 +1,20 @@
import React from 'react'
import { HashRouter as Router, Switch, Route } from 'react-router-dom'
import Layout from './Layout'
import About from './About'
import Stats from './Stats'
import Home from './Home'
const App = () => (
<Router>
<Layout>
<Switch>
<Route path="/stats" component={Stats}/>
<Route path="/about" component={About}/>
<Route path="/" component={Home}/>
</Switch>
</Layout>
</Router>
)
export default App

8
client/App.test.js Normal file
View File

@ -0,0 +1,8 @@
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<App />, div);
});

View File

Before

Width:  |  Height:  |  Size: 9.1 KiB

After

Width:  |  Height:  |  Size: 9.1 KiB

View File

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 13 KiB

View File

@ -1,7 +1,8 @@
import React, { PropTypes } from 'react'
import { Motion, spring } from 'react-motion'
import { findDOMNode } from 'react-dom'
import Window from './Window'
import { Motion, spring } from 'react-motion'
import { withRouter, Link } from 'react-router-dom'
import WindowSize from './WindowSize'
class Layout extends React.Component {
static propTypes = {
@ -39,15 +40,16 @@ class Layout extends React.Component {
})
}
componentDidMount = () =>
componentDidMount() {
this.adjustUnderline()
}
componentDidUpdate = (prevProps) => {
componentDidUpdate(prevProps) {
if (prevProps.location.pathname !== this.props.location.pathname)
this.adjustUnderline(true)
}
render = () => {
render() {
const { underlineLeft, underlineWidth, useSpring } = this.state
const style = {
@ -57,14 +59,14 @@ class Layout extends React.Component {
return (
<div>
<Window onResize={this.adjustUnderline}/>
<WindowSize onChange={this.adjustUnderline}/>
<header>
<h1>unpkg</h1>
<nav>
<ol className="underlist">
<li><a href="#/">Home</a></li>
<li><a href="#/stats">Stats</a></li>
<li><a href="#/about">About</a></li>
<li><Link to="/">Home</Link></li>
<li><Link to="/stats">Stats</Link></li>
<li><Link to="/about">About</Link></li>
</ol>
<Motion defaultStyle={{ left: underlineLeft, width: underlineWidth }} style={style}>
{s => (
@ -86,4 +88,4 @@ class Layout extends React.Component {
}
}
export default Layout
export default withRouter(Layout)

View File

@ -1,5 +1,5 @@
import React, { PropTypes } from 'react'
import { parseNumber, formatNumber } from '../NumberUtils'
import { parseNumber, formatNumber } from './NumberUtils'
class NumberTextInput extends React.Component {
static propTypes = {

View File

Before

Width:  |  Height:  |  Size: 27 KiB

After

Width:  |  Height:  |  Size: 27 KiB

View File

@ -1,9 +1,9 @@
import React, { PropTypes } from 'react'
import formatBytes from 'byte-size'
import formatBytes from 'pretty-bytes'
import formatDate from 'date-fns/format'
import parseDate from 'date-fns/parse'
import { formatNumber, formatPercent } from '../NumberUtils'
import { ContinentsIndex, CountriesIndex, getCountriesByContinent } from '../CountryUtils'
import { formatNumber, formatPercent } from './NumberUtils'
import { ContinentsIndex, CountriesIndex, getCountriesByContinent } from './CountryUtils'
import NumberTextInput from './NumberTextInput'
const getSum = (data, countries) =>
@ -21,23 +21,24 @@ const addValues = (a, b) => {
class Stats extends React.Component {
static propTypes = {
stats: PropTypes.object
serverData: PropTypes.object
}
static defaultProps = {
stats: window.cloudFlareStats
serverData: window.serverData
}
state = {
minRequests: 5000000
}
updateMinRequests = (value) =>
updateMinRequests = (value) => {
this.setState({ minRequests: value })
}
render = () => {
render() {
const { minRequests } = this.state
const { stats } = this.props
const stats = this.props.serverData.cloudflareStats
const { timeseries, totals } = stats
// Summary data

32
client/WindowSize.js Normal file
View File

@ -0,0 +1,32 @@
import React, { PropTypes } from 'react'
import { addEvent, removeEvent } from './DOMUtils'
const ResizeEvent = 'resize'
class WindowSize extends React.Component {
static propTypes = {
onChange: PropTypes.func
}
handleWindowResize = () => {
if (this.props.onChange)
this.props.onChange({
width: window.innerWidth,
height: window.innerHeight
})
}
componentDidMount() {
addEvent(window, ResizeEvent, this.handleWindowResize)
}
componentWillUnmount() {
removeEvent(window, ResizeEvent, this.handleWindowResize)
}
render() {
return null
}
}
export default WindowSize

9
client/index.js Normal file
View File

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

38
config/env.js Normal file
View File

@ -0,0 +1,38 @@
'use strict';
// Grab NODE_ENV and REACT_APP_* environment variables and prepare them to be
// injected into the application via DefinePlugin in Webpack configuration.
var REACT_APP = /^REACT_APP_/i;
function getClientEnvironment(publicUrl) {
var raw = Object
.keys(process.env)
.filter(key => REACT_APP.test(key))
.reduce((env, key) => {
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 resolving the correct path to static assets in `public`.
// For example, <img src={process.env.PUBLIC_URL + '/img/logo.png'} />.
// 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
var stringified = {
'process.env': Object
.keys(raw)
.reduce((env, key) => {
env[key] = JSON.stringify(raw[key]);
return env;
}, {})
};
return { raw, stringified };
}
module.exports = getClientEnvironment;

View File

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

View File

@ -0,0 +1,12 @@
'use strict';
const path = require('path');
// This is a custom Jest transformer turning file imports into filenames.
// http://facebook.github.io/jest/docs/tutorial-webpack.html
module.exports = {
process(src, filename) {
return 'module.exports = ' + JSON.stringify(path.basename(filename)) + ';';
},
};

80
config/paths.js Normal file
View File

@ -0,0 +1,80 @@
'use strict';
var path = require('path');
var fs = require('fs');
var url = require('url');
// Make sure any symlinks in the project folder are resolved:
// https://github.com/facebookincubator/create-react-app/issues/637
var appDirectory = fs.realpathSync(process.cwd());
function resolveApp(relativePath) {
return path.resolve(appDirectory, relativePath);
}
// We support resolving modules according to `NODE_PATH`.
// This lets you use absolute paths in imports inside large monorepos:
// https://github.com/facebookincubator/create-react-app/issues/253.
// It works similar to `NODE_PATH` in Node itself:
// https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders
// We will export `nodePaths` as an array of absolute paths.
// It will then be used by Webpack configs.
// Jest doesnt need this because it already handles `NODE_PATH` out of the box.
// Note that unlike in Node, only *relative* paths from `NODE_PATH` are honored.
// 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
var nodePaths = (process.env.NODE_PATH || '')
.split(process.platform === 'win32' ? ';' : ':')
.filter(Boolean)
.filter(folder => !path.isAbsolute(folder))
.map(resolveApp);
var envPublicUrl = process.env.PUBLIC_URL;
function ensureSlash(path, needsSlash) {
var hasSlash = path.endsWith('/');
if (hasSlash && !needsSlash) {
return path.substr(path, path.length - 1);
} else if (!hasSlash && needsSlash) {
return path + '/';
} else {
return path;
}
}
function getPublicUrl(appPackageJson) {
return envPublicUrl || require(appPackageJson).homepage;
}
// We use `PUBLIC_URL` environment variable or "homepage" field to infer
// "public path" at which the app is served.
// Webpack needs to know it to put the right <script> hrefs into HTML even in
// single-page apps that may serve index.html for nested URLs like /todos/42.
// 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.
function getServedPath(appPackageJson) {
var publicUrl = getPublicUrl(appPackageJson);
var servedUrl = envPublicUrl || (
publicUrl ? url.parse(publicUrl).pathname : '/'
);
return ensureSlash(servedUrl, true);
}
// config after eject: we're in ./config/
module.exports = {
appBuild: resolveApp('build'),
appPublic: resolveApp('public'),
appHtml: resolveApp('public/index.html'),
appIndexJs: resolveApp('client/index.js'),
appPackageJson: resolveApp('package.json'),
appSrc: resolveApp('client'),
yarnLockFile: resolveApp('yarn.lock'),
testsSetup: resolveApp('client/setupTests.js'),
appNodeModules: resolveApp('node_modules'),
nodePaths: nodePaths,
publicUrl: getPublicUrl(resolveApp('package.json')),
servedPath: getServedPath(resolveApp('package.json'))
};

16
config/polyfills.js Normal file
View File

@ -0,0 +1,16 @@
'use strict';
if (typeof Promise === 'undefined') {
// Rejection tracking prevents a common issue where React gets into an
// 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.
require('promise/lib/rejection-tracking').enable();
window.Promise = require('promise/lib/es6-extensions.js');
}
// fetch() polyfill for making API calls.
require('whatwg-fetch');
// Object.assign() is commonly used with React.
// It will use the native implementation if it's present and isn't buggy.
Object.assign = require('object-assign');

View File

@ -0,0 +1,217 @@
'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');
// Webpack uses `publicPath` to determine where the app is being served from.
// In development, we always serve from the root. This makes config easier.
var publicPath = '/';
// `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.
// Omit trailing slash as %PUBLIC_PATH%/xyz looks better than %PUBLIC_PATH%xyz.
var publicUrl = '';
// Get environment variables to inject into our app.
var env = getClientEnvironment(publicUrl);
// This is the development configuration.
// It is focused on developer experience and fast rebuilds.
// The production configuration is different and lives in a separate file.
module.exports = {
// 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.
devtool: 'cheap-module-source-map',
// These are the "entry points" to our application.
// 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.
entry: [
// Include an alternative client for WebpackDevServer. A client's job is to
// connect to WebpackDevServer by a socket and get notified about changes.
// When you save a file, the client will either apply hot updates (in case
// of CSS changes), or refresh the page (in case of JS changes). When you
// make a syntax error, this client will display a syntax error overlay.
// Note: instead of the default WebpackDevServer client, we use a custom one
// to bring better experience for Create React App users. You can replace
// the line below with these two lines if you prefer the stock client:
// require.resolve('webpack-dev-server/client') + '?/',
// require.resolve('webpack/hot/dev-server'),
require.resolve('react-dev-utils/webpackHotDevClient'),
// We ship a few polyfills by default:
require.resolve('./polyfills'),
// Finally, this is your app's code:
paths.appIndexJs
// We include the app code last so that if there is a runtime error during
// initialization, it doesn't blow up the WebpackDevServer client, and
// changing JS code would still trigger a refresh.
],
output: {
// Next line is not used in dev but WebpackDevServer crashes without it:
path: paths.appBuild,
// Add /* filename */ comments to generated require()s in the output.
pathinfo: true,
// 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
// containing code from all our entry points, and the Webpack runtime.
filename: 'static/js/bundle.js',
// This is the URL that app is served from. We use "/" in development.
publicPath: publicPath
},
resolve: {
// This allows you to set a fallback for where Webpack should look for modules.
// We read `NODE_PATH` environment variable in `paths.js` and pass paths here.
// We use `fallback` instead of `root` because we want `node_modules` to "win"
// if there any conflicts. This matches Node resolution mechanism.
// https://github.com/facebookincubator/create-react-app/issues/253
fallback: paths.nodePaths,
// These are the reasonable defaults supported by the Node ecosystem.
// We also include JSX as a common component filename extension to support
// some tools, although we do not recommend using it, see:
// https://github.com/facebookincubator/create-react-app/issues/290
extensions: ['.js', '.json', '.jsx', ''],
alias: {
// Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
'react-native': 'react-native-web'
}
},
module: {
// First, run the linter.
// It's important to do this before Babel processes the JS.
preLoaders: [
{
test: /\.(js|jsx)$/,
loader: 'eslint',
include: paths.appSrc,
}
],
loaders: [
// ** ADDING/UPDATING LOADERS **
// The "url" loader handles all assets unless explicitly excluded.
// The `exclude` list *must* be updated with every change to loader extensions.
// When adding a new loader, you must add its `test`
// as a new entry in the `exclude` list for "url" loader.
// "url" loader embeds assets smaller than specified size as data URLs to avoid requests.
// Otherwise, it acts like the "file" loader.
{
exclude: [
/\.html$/,
// We have to write /\.(js|jsx)(\?.*)?$/ rather than just /\.(js|jsx)$/
// because you might change the hot reloading server from the custom one
// to Webpack's built-in webpack-dev-server/client?/, which would not
// get properly excluded by /\.(js|jsx)$/ because of the query string.
// Webpack 2 fixes this, but for now we include this hack.
// https://github.com/facebookincubator/create-react-app/issues/1713
/\.(js|jsx)(\?.*)?$/,
/\.css$/,
/\.json$/,
/\.svg$/,
/\.md$/
],
loader: 'url',
query: {
limit: 10000,
name: 'static/media/[name].[hash:8].[ext]'
}
},
// Process JS with Babel.
{
test: /\.(js|jsx)$/,
include: paths.appSrc,
loader: 'babel',
query: {
// This is a feature of `babel-loader` for webpack (not Babel itself).
// It enables caching results in ./node_modules/.cache/babel-loader/
// directory for faster rebuilds.
cacheDirectory: true
}
},
// "postcss" loader applies autoprefixer to our CSS.
// "css" loader resolves paths in CSS and adds assets as dependencies.
// "style" loader turns CSS into JS modules that inject <style> tags.
// In production, we use a plugin to extract that CSS to a file, but
// in development "style" loader enables hot editing of CSS.
{
test: /\.css$/,
loader: 'style!css?importLoaders=1!postcss'
},
// JSON is not enabled by default in Webpack but both Node and Browserify
// allow it implicitly so we also enable it.
{
test: /\.json$/,
loader: 'json'
},
// "file" loader for svg
{
test: /\.svg$/,
loader: 'file',
query: {
name: 'static/media/[name].[hash:8].[ext]'
}
},
// HTML loader for Markdown files.
{
test: /\.md$/,
loader: 'html!markdown'
}
// ** STOP ** Are you adding a new loader?
// Remember to add the new extension(s) to the "url" loader exclusion list.
]
},
// We use PostCSS for autoprefixing only.
postcss: function() {
return [
autoprefixer({
browsers: [
'>1%',
'last 4 versions',
'Firefox ESR',
'not ie < 9', // React doesn't support IE8 anyway
]
}),
];
},
plugins: [
// Makes some environment variables available in index.html.
// The public URL is available as %PUBLIC_URL% in index.html, e.g.:
// <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
// In development, this will be an empty string.
new InterpolateHtmlPlugin(env.raw),
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin({
inject: true,
template: paths.appHtml,
}),
// Makes some environment variables available to the JS code, for example:
// if (process.env.NODE_ENV === 'development') { ... }. See `./env.js`.
new webpack.DefinePlugin(env.stringified),
// This is necessary to emit hot updates (currently CSS only):
new webpack.HotModuleReplacementPlugin(),
// Watcher doesn't work well if you mistype casing in a path so we use
// a plugin that prints an error when you attempt to do this.
// See https://github.com/facebookincubator/create-react-app/issues/240
new CaseSensitivePathsPlugin(),
// If you require a missing module and then `npm install` it, you still have
// to restart the development server for Webpack to discover it. This plugin
// makes the discovery automatic so you don't have to restart.
// See https://github.com/facebookincubator/create-react-app/issues/186
new WatchMissingNodeModulesPlugin(paths.appNodeModules)
],
// 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.
node: {
fs: 'empty',
net: 'empty',
tls: 'empty'
}
};

View File

@ -0,0 +1,251 @@
'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');
// 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.
var publicPath = paths.servedPath;
// Some apps do not use client-side routing with pushState.
// For these, "homepage" can be set to "." to enable relative asset paths.
var shouldUseRelativeAssetPaths = publicPath === './';
// `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.
// Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
var publicUrl = publicPath.slice(0, -1);
// Get environment variables to inject into our app.
var env = getClientEnvironment(publicUrl);
// Assert this just to be safe.
// Development builds of React are slow and not intended for production.
if (env.stringified['process.env'].NODE_ENV !== '"production"') {
throw new Error('Production builds must have NODE_ENV=production.');
}
// Note: defined here because it will be used more than once.
const cssFilename = 'static/css/[name].[contenthash:8].css';
// ExtractTextPlugin expects the build output to be flat.
// (See https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/27)
// 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.
const extractTextPluginOptions = shouldUseRelativeAssetPaths
// Making sure that the publicPath goes back to to build folder.
? { publicPath: Array(cssFilename.split('/').length).join('../') }
: undefined;
// This is the production configuration.
// It compiles slowly and is focused on producing a fast and minimal bundle.
// The development configuration is different and lives in a separate file.
module.exports = {
// Don't attempt to continue if there are any errors.
bail: true,
// We generate sourcemaps in production. This is slow but gives good results.
// You can exclude the *.map files from the build during deployment.
devtool: 'source-map',
// In production, we only want to load the polyfills and the app code.
entry: [
require.resolve('./polyfills'),
paths.appIndexJs
],
output: {
// The build folder.
path: paths.appBuild,
// Generated JS file names (with nested folders).
// There will be one main bundle, and one file per asynchronous chunk.
// We don't currently advertise code splitting but Webpack supports it.
filename: 'static/js/[name].[chunkhash:8].js',
chunkFilename: 'static/js/[name].[chunkhash:8].chunk.js',
// We inferred the "public path" (such as / or /my-project) from homepage.
publicPath: publicPath
},
resolve: {
// This allows you to set a fallback for where Webpack should look for modules.
// We read `NODE_PATH` environment variable in `paths.js` and pass paths here.
// We use `fallback` instead of `root` because we want `node_modules` to "win"
// if there any conflicts. This matches Node resolution mechanism.
// https://github.com/facebookincubator/create-react-app/issues/253
fallback: paths.nodePaths,
// These are the reasonable defaults supported by the Node ecosystem.
// We also include JSX as a common component filename extension to support
// some tools, although we do not recommend using it, see:
// https://github.com/facebookincubator/create-react-app/issues/290
extensions: ['.js', '.json', '.jsx', ''],
alias: {
// Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
'react-native': 'react-native-web'
}
},
module: {
// First, run the linter.
// It's important to do this before Babel processes the JS.
preLoaders: [
{
test: /\.(js|jsx)$/,
loader: 'eslint',
include: paths.appSrc
}
],
loaders: [
// ** ADDING/UPDATING LOADERS **
// The "url" loader handles all assets unless explicitly excluded.
// The `exclude` list *must* be updated with every change to loader extensions.
// When adding a new loader, you must add its `test`
// as a new entry in the `exclude` list in the "url" loader.
// "url" loader embeds assets smaller than specified size as data URLs to avoid requests.
// Otherwise, it acts like the "file" loader.
{
exclude: [
/\.html$/,
/\.(js|jsx)$/,
/\.css$/,
/\.json$/,
/\.svg$/,
/\.md$/
],
loader: 'url',
query: {
limit: 10000,
name: 'static/media/[name].[hash:8].[ext]'
}
},
// Process JS with Babel.
{
test: /\.(js|jsx)$/,
include: paths.appSrc,
loader: 'babel',
},
// The notation here is somewhat confusing.
// "postcss" loader applies autoprefixer to our CSS.
// "css" loader resolves paths in CSS and adds assets as dependencies.
// "style" loader normally turns CSS into JS modules injecting <style>,
// but unlike in development configuration, we do something different.
// `ExtractTextPlugin` first applies the "postcss" and "css" loaders
// (second argument), then grabs the result CSS and puts it into a
// separate file in our build process. This way we actually ship
// a single CSS file in production instead of JS code injecting <style>
// tags. If you use code splitting, however, any async bundles will still
// use the "style" loader inside the async code so CSS from them won't be
// in the main CSS file.
{
test: /\.css$/,
loader: ExtractTextPlugin.extract(
'style',
'css?importLoaders=1!postcss',
extractTextPluginOptions
)
// Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
},
// JSON is not enabled by default in Webpack but both Node and Browserify
// allow it implicitly so we also enable it.
{
test: /\.json$/,
loader: 'json'
},
// "file" loader for svg
{
test: /\.svg$/,
loader: 'file',
query: {
name: 'static/media/[name].[hash:8].[ext]'
}
},
// HTML loader for Markdown files.
{
test: /\.md$/,
loader: 'html!markdown'
}
// ** STOP ** Are you adding a new loader?
// Remember to add the new extension(s) to the "url" loader exclusion list.
]
},
// We use PostCSS for autoprefixing only.
postcss: function() {
return [
autoprefixer({
browsers: [
'>1%',
'last 4 versions',
'Firefox ESR',
'not ie < 9', // React doesn't support IE8 anyway
]
}),
];
},
plugins: [
// Makes some environment variables available in index.html.
// The public URL is available as %PUBLIC_URL% in index.html, e.g.:
// <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
// In production, it will be an empty string unless you specify "homepage"
// in `package.json`, in which case it will be the pathname of that URL.
new InterpolateHtmlPlugin(env.raw),
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin({
inject: true,
template: paths.appHtml,
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true
}
}),
// Makes some environment variables available to the JS code, for example:
// if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
// It is absolutely essential that NODE_ENV was set to production here.
// Otherwise React will be compiled in the very slow development mode.
new webpack.DefinePlugin(env.stringified),
// This helps ensure the builds are consistent if source hasn't changed:
new webpack.optimize.OccurrenceOrderPlugin(),
// Try to dedupe duplicated modules, if any:
new webpack.optimize.DedupePlugin(),
// Minify the code.
new webpack.optimize.UglifyJsPlugin({
compress: {
screw_ie8: true, // React doesn't support IE8
warnings: false
},
mangle: {
screw_ie8: true
},
output: {
comments: false,
screw_ie8: true
}
}),
// Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`.
new ExtractTextPlugin(cssFilename),
// Generate a manifest file which contains a mapping of all asset filenames
// to their corresponding output file so that tools can pick it up without
// having to parse `index.html`.
new ManifestPlugin({
fileName: 'asset-manifest.json'
})
],
// 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.
node: {
fs: 'empty',
net: 'empty',
tls: 'empty'
}
};

View File

@ -1,10 +0,0 @@
{
"presets": [
[ "es2015", { "loose": true } ],
"stage-1",
"react"
],
"plugins": [
"transform-object-assign"
]
}

View File

@ -1,4 +0,0 @@
module.exports = [
'goodjsproject',
'thisoneisevil'
]

View File

@ -1,5 +0,0 @@
{
"env": {
"browser": true
}
}

View File

@ -1,51 +0,0 @@
import React from 'react'
import history from '../history'
import Layout from './Layout'
import About from './About'
import Stats from './Stats'
import Home from './Home'
const findMatchingComponents = (location) => {
let components
switch (location.pathname) {
case '/about':
components = [ Layout, About ]
break
case '/stats':
components = [ Layout, Stats ]
break
case '/':
default:
components = [ Layout, Home ]
}
return components
}
const renderNestedComponents = (components, props) =>
components.reduceRight(
(children, component) => React.createElement(component, { ...props, children }),
undefined
)
class Router extends React.Component {
state = {
location: history.getCurrentLocation()
}
componentDidMount = () =>
this.unlisten = history.listen(location => {
this.setState({ location })
})
componentWillUnmount = () =>
this.unlisten()
render = () => {
const { location } = this.state
const components = findMatchingComponents(location)
return renderNestedComponents(components, { location })
}
}
export default Router

View File

@ -1,26 +0,0 @@
import React, { PropTypes } from 'react'
import { addEvent, removeEvent } from '../DOMUtils'
const ResizeEvent = 'resize'
class Window extends React.Component {
static propTypes = {
onResize: PropTypes.func
}
handleWindowResize = () => {
if (this.props.onResize)
this.props.onResize()
}
componentDidMount = () =>
addEvent(window, ResizeEvent, this.handleWindowResize)
componentWillUnmount = () =>
removeEvent(window, ResizeEvent, this.handleWindowResize)
render = () =>
null
}
export default Window

View File

@ -1,5 +0,0 @@
import createHistory from 'history/lib/createHashHistory'
const history = createHistory()
export default history

View File

@ -1,10 +0,0 @@
import React from 'react'
import { render } from 'react-dom'
import Router from './components/Router'
import './styles.css'
render(
<Router/>,
document.getElementById('app')
)

View File

@ -1,3 +0,0 @@
require('babel-register')({
only: __dirname
})

View File

@ -1,147 +0,0 @@
const fs = require('fs')
const invariant = require('invariant')
const webpack = require('webpack')
const createBundle = (webpackStats) => {
const { publicPath, assetsByChunkName } = webpackStats
const createURL = (asset) =>
publicPath + asset
const getAssets = (chunks = [ 'main' ]) =>
(Array.isArray(chunks) ? chunks : [ chunks ]).reduce((memo, chunk) => (
memo.concat(assetsByChunkName[chunk] || [])
), [])
const getScriptAssets = (...args) =>
getAssets(...args)
.filter(asset => (/\.js$/).test(asset))
.map(createURL)
const getStyleAssets = (...args) =>
getAssets(...args)
.filter(asset => (/\.css$/).test(asset))
.map(createURL)
return {
createURL,
getAssets,
getScriptAssets,
getStyleAssets
}
}
/**
* An express middleware that sets req.manifest from the build manifest
* in the given file. Should be used in production to get consistent hashes.
*/
const assetsManifest = (webpackManifestFile) => {
let manifest
try {
manifest = JSON.parse(fs.readFileSync(webpackManifestFile, 'utf8'))
} catch (error) {
invariant(
false,
'assetsManifest middleware cannot read the manifest file "%s"; ' +
'do `npm run build` before starting the server',
webpackManifestFile
)
}
return (req, res, next) => {
req.manifest = manifest
next()
}
}
/**
* An express middleware that sets req.bundle from the build
* info in the given stats file. Should be used in production.
*/
const staticAssets = (webpackStatsFile) => {
let stats
try {
stats = JSON.parse(fs.readFileSync(webpackStatsFile, 'utf8'))
} catch (error) {
invariant(
false,
'staticAssets middleware cannot read the build stats in %s; ' +
'do `npm run build` before starting the server',
webpackStatsFile
)
}
const bundle = createBundle(stats)
return (req, res, next) => {
req.bundle = bundle
next()
}
}
/**
* An express middleware that sets req.bundle from the
* latest result from a running webpack compiler (i.e. using
* webpack-dev-middleware). Should only be used in dev.
*/
const devAssets = (webpackCompiler) => {
let bundle
webpackCompiler.plugin('done', (stats) => {
bundle = createBundle(stats.toJson())
})
return (req, res, next) => {
invariant(
bundle != null,
'devAssets middleware needs a running compiler; ' +
'use webpack-dev-middleware in front of devAssets'
)
req.bundle = bundle
next()
}
}
/**
* Creates a webpack compiler that automatically inlines the
* webpack dev runtime in all entry points.
*/
const createDevCompiler = (webpackConfig, webpackRuntimeModuleID) =>
webpack({
...webpackConfig,
entry: prependModuleID(
webpackConfig.entry,
webpackRuntimeModuleID
)
})
/**
* Returns a modified copy of the given webpackEntry object with
* the moduleID in front of all other assets.
*/
const prependModuleID = (webpackEntry, moduleID) => {
if (typeof webpackEntry === 'string')
return [ moduleID, webpackEntry ]
if (Array.isArray(webpackEntry))
return [ moduleID, ...webpackEntry ]
if (webpackEntry && typeof webpackEntry === 'object') {
const entry = { ...webpackEntry }
for (const chunkName in entry)
if (entry.hasOwnProperty(chunkName))
entry[chunkName] = prependModuleID(entry[chunkName], moduleID)
return entry
}
throw new Error('Invalid webpack entry object')
}
module.exports = {
assetsManifest,
staticAssets,
devAssets,
createDevCompiler
}

File diff suppressed because it is too large Load Diff

View File

@ -1,47 +0,0 @@
const React = require('react')
const { renderToStaticMarkup } = require('react-dom/server')
const { getAnalyticsDashboards } = require('./Cloudflare')
const HomePage = require('./components/HomePage')
const OneMinute = 1000 * 60
const ThirtyDays = OneMinute * 60 * 24 * 30
const DOCTYPE = '<!DOCTYPE html>'
const fetchStats = (callback) => {
if (process.env.NODE_ENV === 'development') {
callback(null, require('./CloudflareStats.json'))
} else {
const since = new Date(Date.now() - ThirtyDays)
const until = new Date(Date.now() - OneMinute)
getAnalyticsDashboards([ 'npmcdn.com', 'unpkg.com' ], since, until)
.then(result => callback(null, result), callback)
}
}
const sendHomePage = (req, res, next) => {
const chunks = [ 'vendor', 'home' ]
const props = {
styles: req.bundle.getStyleAssets(chunks),
scripts: req.bundle.getScriptAssets(chunks)
}
if (req.manifest)
props.webpackManifest = req.manifest
fetchStats((error, stats) => {
if (error) {
next(error)
} else {
res.set('Cache-Control', 'public, max-age=60')
res.send(
DOCTYPE + renderToStaticMarkup(<HomePage {...props} stats={stats}/>)
)
}
})
}
module.exports = {
sendHomePage
}

View File

@ -1,18 +0,0 @@
const path = require('path')
exports.id = 1
exports.port = parseInt(process.env.PORT, 10) || 5000
exports.webpackConfig = require('../../webpack.config')
exports.statsFile = path.resolve(__dirname, '../../stats.json')
exports.publicDir = path.resolve(__dirname, '../../public')
exports.manifestFile = path.resolve(exports.publicDir, '__assets__/chunk-manifest.json')
exports.timeout = parseInt(process.env.TIMEOUT, 10) || 20000
exports.maxAge = process.env.MAX_AGE || '365d'
exports.registryURL = process.env.REGISTRY_URL || 'https://registry.npmjs.org'
exports.bowerBundle = process.env.BOWER_BUNDLE || '/bower.zip'
exports.redirectTTL = process.env.REDIRECT_TTL || 500
exports.autoIndex = !process.env.DISABLE_INDEX
exports.redisURL = process.env.REDIS_URL
exports.blacklist = require('../PackageBlacklist')

View File

@ -1,48 +0,0 @@
const React = require('react')
const PropTypes = React.PropTypes
class HomePage extends React.Component {
static propTypes = {
webpackManifest: PropTypes.object,
styles: PropTypes.arrayOf(PropTypes.string),
scripts: PropTypes.arrayOf(PropTypes.string),
stats: PropTypes.object
}
static defaultProps = {
webpackManifest: {},
styles: [],
scripts: [],
stats: {}
}
render() {
const { webpackManifest, styles, scripts, stats } = this.props
return (
<html>
<head>
<meta charSet="utf-8"/>
<meta httpEquiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
<meta name="description" content="A fast, global content delivery network for stuff that is published to npm"/>
<meta name="viewport" content="width=700,maximum-scale=1"/>
<meta name="timestamp" content={(new Date).toISOString()}/>
<link rel="icon" href="/favicon.ico?v3"/>
<title>unpkg</title>
<script dangerouslySetInnerHTML={{ __html: "window.Promise || document.write('\\x3Cscript src=\"/es6-promise.min.js\">\\x3C/script>\\x3Cscript>ES6Promise.polyfill()\\x3C/script>')" }}/>
<script dangerouslySetInnerHTML={{ __html: "window.fetch || document.write('\\x3Cscript src=\"/fetch.min.js\">\\x3C/script>')" }}/>
<script dangerouslySetInnerHTML={{ __html: "window.webpackManifest = " + JSON.stringify(webpackManifest) }}/>
<script dangerouslySetInnerHTML={{ __html: "window.cloudFlareStats = " + JSON.stringify(stats) }}/>
{styles.map(s => <link rel="stylesheet" key={s} href={s}/>)}
</head>
<body>
<div id="app"/>
{scripts.map(s => <script key={s} src={s}/>)}
</body>
</html>
)
}
}
module.exports = HomePage

View File

@ -1,136 +0,0 @@
/*eslint-disable no-console*/
const http = require('http')
const cors = require('cors')
const throng = require('throng')
const morgan = require('morgan')
const express = require('express')
const devErrorHandler = require('errorhandler')
const WebpackDevServer = require('webpack-dev-server')
const { createRequestHandler } = require('express-unpkg')
const DefaultServerConfig = require('./ServerConfig')
const { assetsManifest, staticAssets, devAssets, createDevCompiler } = require('./AssetsUtils')
const { sendHomePage } = require('./MainController')
const { logStats } = require('./StatsUtils')
const createRouter = (config = {}) => {
const router = express.Router()
router.get('/', sendHomePage)
if (config.redisURL)
router.use(logStats(config.redisURL))
router.use(createRequestHandler(config))
return router
}
const errorHandler = (err, req, res, next) => {
res.status(500).send('<p>Internal Server Error</p>')
console.error(err.stack)
next(err)
}
const createServer = (config) => {
const app = express()
app.disable('x-powered-by')
app.use(errorHandler)
app.use(cors())
app.use(express.static(config.publicDir, { maxAge: config.maxAge }))
app.use(assetsManifest(config.manifestFile))
app.use(staticAssets(config.statsFile))
app.use(createRouter(config))
const server = http.createServer(app)
// Heroku dynos automatically timeout after 30s. Set our
// own timeout here to force sockets to close before that.
// https://devcenter.heroku.com/articles/request-timeout
if (config.timeout) {
server.setTimeout(config.timeout, (socket) => {
const message = `Timeout of ${config.timeout}ms exceeded`
socket.end([
`HTTP/1.1 503 Service Unavailable`,
`Date: ${(new Date).toGMTString()}`,
`Content-Type: text/plain`,
`Content-Length: ${message.length}`,
`Connection: close`,
``,
message
].join(`\r\n`))
})
}
return server
}
const createDevServer = (config) => {
const webpackConfig = config.webpackConfig
const compiler = createDevCompiler(
webpackConfig,
`webpack-dev-server/client?http://localhost:${config.port}`
)
const server = new WebpackDevServer(compiler, {
// webpack-dev-middleware options.
publicPath: webpackConfig.output.publicPath,
quiet: false,
noInfo: false,
stats: {
// https://webpack.github.io/docs/node.js-api.html#stats-tojson
assets: true,
colors: true,
version: true,
hash: true,
timings: true,
chunks: false
},
// webpack-dev-server options.
contentBase: false,
setup(app) {
// This runs before webpack-dev-middleware.
app.disable('x-powered-by')
app.use(morgan('dev'))
}
})
// This runs after webpack-dev-middleware.
server.use(devErrorHandler())
server.use(express.static(config.publicDir))
server.use(devAssets(compiler))
server.use(createRouter(config))
return server
}
const startServer = (serverConfig) => {
const config = {
...DefaultServerConfig,
...serverConfig
}
const server = process.env.NODE_ENV === 'production'
? createServer(config)
: createDevServer(config)
server.listen(config.port, () => {
console.log('Server #%s listening on port %s, Ctrl+C to stop', config.id, config.port)
})
}
module.exports = {
createServer,
createDevServer,
startServer
}
if (require.main === module)
throng({
start: (id) => startServer({ id }),
workers: process.env.WEB_CONCURRENCY || 1,
lifetime: Infinity
})

View File

@ -1,63 +1,102 @@
{
"private": true,
"repository": "unpkg/unpkg.com",
"name": "unpkg.com",
"proxy": "http://localhost:3001",
"scripts": {
"start": "heroku local -f Procfile.local",
"build": "node ./tools/build.js",
"heroku-postbuild": "node ./tools/build.js",
"lint": "eslint modules",
"test": "npm run lint"
"start": "node scripts/start.js",
"build": "node scripts/build.js",
"heroku-postbuild": "node scripts/build.js",
"serve": "heroku local -f Procfile.local -p 3001",
"test": "node scripts/test.js --env=jsdom"
},
"dependencies": {
"autoprefixer": "^6.3.6",
"babel-cli": "^6.8.0",
"babel-core": "^6.9.1",
"babel-loader": "^6.2.4",
"babel-plugin-transform-object-assign": "^6.8.0",
"babel-preset-es2015": "^6.6.0",
"babel-preset-react": "^6.5.0",
"babel-preset-stage-1": "^6.5.0",
"byte-size": "^2.0.0",
"chunk-manifest-webpack-plugin": "^0.1.0",
"cors": "^2.7.1",
"countries-list": "^1.1.0",
"css-loader": "^0.23.1",
"date-fns": "^1.0.0",
"errorhandler": "^1.4.3",
"express": "^4.13.4",
"cors": "^2.8.1",
"countries-list": "^1.3.2",
"date-fns": "^1.28.1",
"express": "^4.15.2",
"express-unpkg": "^1.1.1",
"extract-text-webpack-plugin": "^1.0.1",
"file-loader": "^0.8.5",
"history": "^3.0.0-2",
"html-loader": "^0.4.3",
"http-client": "^4.0.1",
"invariant": "^2.2.1",
"isomorphic-fetch": "^2.2.1",
"json-loader": "^0.5.4",
"markdown-loader": "^0.1.7",
"morgan": "^1.7.0",
"http-client": "^4.3.1",
"morgan": "^1.8.1",
"on-finished": "^2.3.0",
"postcss-loader": "^0.9.1",
"react": "^15.1.0",
"react-dom": "^15.1.0",
"react-motion": "^0.4.3",
"redis": "^2.6.0-1",
"rimraf": "^2.5.2",
"style-loader": "^0.13.1",
"throng": "^4.0.0",
"webpack": "^1.13.0",
"webpack-dev-server": "^1.14.1",
"webpack-md5-hash": "0.0.5"
"pretty-bytes": "^3",
"react": "^15.4.2",
"react-dom": "^15.4.2",
"react-motion": "^0.4.7",
"react-router-dom": "^4.0.0",
"redis": "^2.7.1",
"throng": "^4.0.0"
},
"devDependencies": {
"babel-eslint": "^6.0.4",
"babel-register": "^6.8.0",
"eslint": "^3.0.1",
"eslint-import-resolver-webpack": "^0.4.0",
"eslint-plugin-import": "^1.8.1",
"eslint-plugin-react": "^5.1.1"
"autoprefixer": "6.7.2",
"babel-core": "6.22.1",
"babel-eslint": "7.1.1",
"babel-jest": "18.0.0",
"babel-loader": "6.2.10",
"babel-preset-react-app": "^2.2.0",
"babel-runtime": "^6.20.0",
"case-sensitive-paths-webpack-plugin": "1.1.4",
"chalk": "1.1.3",
"connect-history-api-fallback": "1.3.0",
"cross-spawn": "4.0.2",
"css-loader": "0.26.1",
"detect-port": "1.1.0",
"dotenv": "2.0.0",
"eslint": "3.16.1",
"eslint-config-react-app": "^0.6.2",
"eslint-loader": "1.6.0",
"eslint-plugin-flowtype": "2.21.0",
"eslint-plugin-import": "2.0.1",
"eslint-plugin-jsx-a11y": "4.0.0",
"eslint-plugin-react": "6.4.1",
"extract-text-webpack-plugin": "1.0.1",
"file-loader": "0.10.0",
"fs-extra": "0.30.0",
"html-loader": "^0.4.5",
"html-webpack-plugin": "2.24.0",
"http-proxy-middleware": "0.17.3",
"jest": "18.1.0",
"json-loader": "0.5.4",
"markdown-loader": "^2.0.0",
"object-assign": "4.1.1",
"postcss-loader": "1.2.2",
"promise": "7.1.1",
"react-dev-utils": "^0.5.2",
"style-loader": "0.13.1",
"url-loader": "0.5.7",
"webpack": "1.14.0",
"webpack-dev-server": "1.16.2",
"webpack-manifest-plugin": "1.1.0",
"whatwg-fetch": "2.0.2"
},
"engines": {
"node": "6.6.x"
"jest": {
"collectCoverageFrom": [
"src/**/*.{js,jsx}"
],
"setupFiles": [
"<rootDir>/config/polyfills.js"
],
"testPathIgnorePatterns": [
"<rootDir>[/\\\\](build|docs|node_modules|scripts)[/\\\\]"
],
"testEnvironment": "node",
"testURL": "http://localhost",
"transform": {
"^.+\\.(js|jsx)$": "<rootDir>/node_modules/babel-jest",
"^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
"^(?!.*\\.(js|jsx|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
},
"transformIgnorePatterns": [
"[/\\\\]node_modules[/\\\\].+\\.(js|jsx)$"
],
"moduleNameMapper": {
"^react-native$": "react-native-web"
}
},
"babel": {
"presets": [
"react-app"
]
},
"eslintConfig": {
"extends": "react-app"
}
}

File diff suppressed because one or more lines are too long

1
public/fetch.min.js vendored

File diff suppressed because one or more lines are too long

24
public/index.html Normal file
View File

@ -0,0 +1,24 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="description" content="A fast, global content delivery network for stuff that is published to npm">
<meta name="viewport" content="width=700,maximum-scale=1">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<script>window.serverData = %REACT_APP_SERVER_DATA%</script>
<!--
Notice the use of %PUBLIC_URL% in the tag above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>unpkg</title>
</head>
<body>
<div id="root"></div>
</body>
</html>

160
scripts/build.js Normal file
View File

@ -0,0 +1,160 @@
'use strict';
// Do this as the first thing so that any code reading it knows the right env.
process.env.NODE_ENV = 'production';
process.env.REACT_APP_SERVER_DATA = '__SERVER_DATA__';
// Load environment variables from .env file. Suppress warnings using silent
// if this file is missing. dotenv will never modify any environment variables
// that have already been set.
// https://github.com/motdotla/dotenv
require('dotenv').config({silent: true});
var chalk = require('chalk');
var fs = require('fs-extra');
var path = require('path');
var url = require('url');
var webpack = require('webpack');
var config = require('../config/webpack.config.prod');
var paths = require('../config/paths');
var checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
var FileSizeReporter = require('react-dev-utils/FileSizeReporter');
var measureFileSizesBeforeBuild = FileSizeReporter.measureFileSizesBeforeBuild;
var printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild;
var useYarn = fs.existsSync(paths.yarnLockFile);
// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
process.exit(1);
}
// First, read the current file sizes in build directory.
// This lets us display how much they changed later.
measureFileSizesBeforeBuild(paths.appBuild).then(previousFileSizes => {
// Remove all content but keep the directory so that
// if you're in it, you don't end up in Trash
fs.emptyDirSync(paths.appBuild);
// Start the webpack build
build(previousFileSizes);
// Merge with the public folder
copyPublicFolder();
});
// Print out errors
function printErrors(summary, errors) {
console.log(chalk.red(summary));
console.log();
errors.forEach(err => {
console.log(err.message || err);
console.log();
});
}
// Create the production build and print the deployment instructions.
function build(previousFileSizes) {
console.log('Creating an optimized production build...');
webpack(config).run((err, stats) => {
if (err) {
printErrors('Failed to compile.', [err]);
process.exit(1);
}
if (stats.compilation.errors.length) {
printErrors('Failed to compile.', stats.compilation.errors);
process.exit(1);
}
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);
process.exit(1);
}
console.log(chalk.green('Compiled successfully.'));
console.log();
console.log('File sizes after gzip:');
console.log();
printFileSizesAfterBuild(stats, previousFileSizes);
console.log();
var appPackage = require(paths.appPackageJson);
var publicUrl = paths.publicUrl;
var publicPath = config.output.publicPath;
var publicPathname = url.parse(publicPath).pathname;
if (publicUrl && publicUrl.indexOf('.github.io/') !== -1) {
// "homepage": "http://user.github.io/project"
console.log('The project was built assuming it is hosted at ' + chalk.green(publicPathname) + '.');
console.log('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 (typeof appPackage.scripts.deploy === 'undefined') {
console.log();
if (useYarn) {
console.log(' ' + chalk.cyan('yarn') + ' add --dev gh-pages');
} else {
console.log(' ' + chalk.cyan('npm') + ' install --save-dev gh-pages');
}
console.log();
console.log('Add the following script in your ' + chalk.cyan('package.json') + '.');
console.log();
console.log(' ' + chalk.dim('// ...'));
console.log(' ' + chalk.yellow('"scripts"') + ': {');
console.log(' ' + chalk.dim('// ...'));
console.log(' ' + chalk.yellow('"predeploy"') + ': ' + chalk.yellow('"npm run build",'));
console.log(' ' + chalk.yellow('"deploy"') + ': ' + chalk.yellow('"gh-pages -d build"'));
console.log(' }');
console.log();
console.log('Then run:');
}
console.log();
console.log(' ' + chalk.cyan(useYarn ? 'yarn' : 'npm') + ' run deploy');
console.log();
} else if (publicPath !== '/') {
// "homepage": "http://mywebsite.com/project"
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('The ' + chalk.cyan('build') + ' folder is ready to be deployed.');
console.log();
} else {
if (publicUrl) {
// "homepage": "http://mywebsite.com"
console.log('The project was built assuming it is hosted at ' + chalk.green(publicUrl) + '.');
console.log('You can control this with the ' + chalk.green('homepage') + ' field in your ' + chalk.cyan('package.json') + '.');
console.log();
} else {
// no homepage
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('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);
console.log('The ' + chalk.cyan(build) + ' folder is ready to be deployed.');
console.log('You may serve it with a static server:');
console.log();
if (useYarn) {
console.log(` ${chalk.cyan('yarn')} global add serve`);
} else {
console.log(` ${chalk.cyan('npm')} install -g serve`);
}
console.log(` ${chalk.cyan('serve')} -s build`);
console.log();
}
});
}
function copyPublicFolder() {
fs.copySync(paths.appPublic, paths.appBuild, {
dereference: true,
filter: file => file !== paths.appHtml
});
}

318
scripts/start.js Normal file
View File

@ -0,0 +1,318 @@
'use strict';
process.env.NODE_ENV = 'development';
process.env.REACT_APP_SERVER_DATA = JSON.stringify(require('../server/dev-data'))
// Load environment variables from .env file. Suppress warnings using silent
// if this file is missing. dotenv will never modify any environment variables
// that have already been set.
// https://github.com/motdotla/dotenv
require('dotenv').config({silent: true});
var chalk = require('chalk');
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var historyApiFallback = require('connect-history-api-fallback');
var httpProxyMiddleware = require('http-proxy-middleware');
var detect = require('detect-port');
var clearConsole = require('react-dev-utils/clearConsole');
var checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
var formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
var getProcessForPort = require('react-dev-utils/getProcessForPort');
var openBrowser = require('react-dev-utils/openBrowser');
var prompt = require('react-dev-utils/prompt');
var fs = require('fs');
var config = require('../config/webpack.config.dev');
var paths = require('../config/paths');
var useYarn = fs.existsSync(paths.yarnLockFile);
var cli = useYarn ? 'yarn' : 'npm';
var isInteractive = process.stdout.isTTY;
// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
process.exit(1);
}
// Tools like Cloud9 rely on this.
var DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000;
var compiler;
var handleCompile;
// You can safely remove this after ejecting.
// We only use this block for testing of Create React App itself:
var isSmokeTest = process.argv.some(arg => arg.indexOf('--smoke-test') > -1);
if (isSmokeTest) {
handleCompile = function (err, stats) {
if (err || stats.hasErrors() || stats.hasWarnings()) {
process.exit(1);
} else {
process.exit(0);
}
};
}
function setupCompiler(host, port, protocol) {
// "Compiler" is a low-level interface to Webpack.
// It lets us listen to some events and provide our own custom messages.
compiler = webpack(config, handleCompile);
// "invalid" event fires when you have changed a file, and Webpack is
// recompiling a bundle. WebpackDevServer takes care to pause serving the
// 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.
compiler.plugin('invalid', function() {
if (isInteractive) {
clearConsole();
}
console.log('Compiling...');
});
var isFirstCompile = true;
// "done" event fires when Webpack has finished recompiling the bundle.
// Whether or not you have warnings or errors, you will get this event.
compiler.plugin('done', function(stats) {
if (isInteractive) {
clearConsole();
}
// We have switched off the default Webpack output in WebpackDevServer
// options so we are going to "massage" the warnings and errors and present
// them in a readable focused way.
var messages = formatWebpackMessages(stats.toJson({}, true));
var isSuccessful = !messages.errors.length && !messages.warnings.length;
var showInstructions = isSuccessful && (isInteractive || isFirstCompile);
if (isSuccessful) {
console.log(chalk.green('Compiled successfully!'));
}
if (showInstructions) {
console.log();
console.log('The app is running at:');
console.log();
console.log(' ' + chalk.cyan(protocol + '://' + host + ':' + port + '/'));
console.log();
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();
isFirstCompile = false;
}
// If errors exist, only show errors.
if (messages.errors.length) {
console.log(chalk.red('Failed to compile.'));
console.log();
messages.errors.forEach(message => {
console.log(message);
console.log();
});
return;
}
// Show warnings if no errors were found.
if (messages.warnings.length) {
console.log(chalk.yellow('Compiled with warnings.'));
console.log();
messages.warnings.forEach(message => {
console.log(message);
console.log();
});
// Teach some ESLint tricks.
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('Use ' + chalk.yellow('/* eslint-disable */') + ' to ignore all warnings in a file.');
}
});
}
// We need to provide a custom onError function for httpProxyMiddleware.
// It allows us to log custom error messages on the console.
function onProxyError(proxy) {
return function(err, req, res){
var host = req.headers && req.headers.host;
console.log(
chalk.red('Proxy error:') + ' Could not proxy request ' + chalk.cyan(req.url) +
' from ' + chalk.cyan(host) + ' to ' + chalk.cyan(proxy) + '.'
);
console.log(
'See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (' +
chalk.cyan(err.code) + ').'
);
console.log();
// And immediately send the proper error response to the client.
// Otherwise, the request will eventually timeout with ERR_EMPTY_RESPONSE on the client side.
if (res.writeHead && !res.headersSent) {
res.writeHead(500);
}
res.end('Proxy error: Could not proxy request ' + req.url + ' from ' +
host + ' to ' + proxy + ' (' + err.code + ').'
);
}
}
function addMiddleware(devServer) {
// `proxy` lets you to specify a fallback server during development.
// Every unrecognized request will be forwarded to it.
var proxy = require(paths.appPackageJson).proxy;
devServer.use(historyApiFallback({
// Paths with dots should still use the history fallback.
// See https://github.com/facebookincubator/create-react-app/issues/387.
disableDotRule: true,
// For single page apps, we generally want to fallback to /index.html.
// However we also want to respect `proxy` for API calls.
// So if `proxy` is specified, we need to decide which fallback to use.
// We use a heuristic: if request `accept`s text/html, we pick /index.html.
// Modern browsers include text/html into `accept` header when navigating.
// However API calls like `fetch()` wont generally accept text/html.
// If this heuristic doesnt work well for you, dont use `proxy`.
htmlAcceptHeaders: proxy ?
['text/html'] :
['text/html', '*/*']
}));
if (proxy) {
if (typeof proxy !== '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('Either remove "proxy" from package.json, or make it a string.'));
process.exit(1);
}
// Otherwise, if proxy is specified, we will let it handle any request.
// There are a few exceptions which we won't send to the proxy:
// - /index.html (served as HTML5 history API fallback)
// - /*.hot-update.json (WebpackDevServer uses this too for hot reloading)
// - /sockjs-node/* (WebpackDevServer uses this for hot reloading)
// Tip: use https://jex.im/regulex/ to visualize the regex
var mayProxy = /^(?!\/(index\.html$|.*\.hot-update\.json$|sockjs-node\/)).*$/;
// Pass the scope regex both to Express and to the middleware for proxying
// of both HTTP and WebSockets to work without false positives.
var hpm = httpProxyMiddleware(pathname => mayProxy.test(pathname), {
target: proxy,
logLevel: 'silent',
onProxyReq: function(proxyReq) {
// Browers may send Origin headers even with same-origin
// requests. To prevent CORS issues, we have to change
// the Origin to match the target URL.
if (proxyReq.getHeader('origin')) {
proxyReq.setHeader('origin', proxy);
}
},
onError: onProxyError(proxy),
secure: false,
changeOrigin: true,
ws: true,
xfwd: true
});
devServer.use(mayProxy, hpm);
// Listen for the websocket 'upgrade' event and upgrade the connection.
// If this is not done, httpProxyMiddleware will not try to upgrade until
// an initial plain HTTP request is made.
devServer.listeningApp.on('upgrade', hpm.upgrade);
}
// Finally, by now we have certainly resolved the URL.
// It may be /index.html, so let the dev server try serving it again.
devServer.use(devServer.middleware);
}
function runDevServer(host, port, protocol) {
var devServer = new WebpackDevServer(compiler, {
// Enable gzip compression of generated files.
compress: true,
// Silence WebpackDevServer's own logs since they're generally not useful.
// It will still show compile warnings and errors with this setting.
clientLogLevel: 'none',
// By default WebpackDevServer serves physical files from current directory
// in addition to all the virtual build products that it serves from memory.
// This is confusing because those files wont automatically be available in
// production build folder unless we copy them. However, copying the whole
// project directory is dangerous because we may expose sensitive files.
// Instead, we establish a convention that only files in `public` directory
// get served. Our build script will copy `public` into the `build` folder.
// In `index.html`, you can get URL of `public` folder with %PUBLIC_URL%:
// <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
// In JavaScript code, you can access it with `process.env.PUBLIC_URL`.
// Note that we only recommend to use `public` folder as an escape hatch
// for files like `favicon.ico`, `manifest.json`, and libraries that are
// for some reason broken when imported through Webpack. If you just want to
// use an image, put it in `src` and `import` it from JavaScript instead.
contentBase: paths.appPublic,
// Enable hot reloading server. It will provide /sockjs-node/ endpoint
// for the WebpackDevServer client so it can learn when the files were
// updated. The WebpackDevServer client is included as an entry point
// in the Webpack development configuration. Note that only changes
// to CSS are currently hot reloaded. JS changes will refresh the browser.
hot: true,
// It is important to tell WebpackDevServer to use the same "root" path
// as we specified in the config. In development, we always serve from /.
publicPath: config.output.publicPath,
// WebpackDevServer is noisy by default so we emit custom message instead
// by listening to the compiler events with `compiler.plugin` calls above.
quiet: true,
// Reportedly, this avoids CPU overload on some systems.
// https://github.com/facebookincubator/create-react-app/issues/293
watchOptions: {
ignored: /node_modules/
},
// Enable HTTPS if the HTTPS environment variable is set to 'true'
https: protocol === "https",
host: host
});
// Our custom middleware proxies requests to /index.html or a remote API.
addMiddleware(devServer);
// Launch WebpackDevServer.
devServer.listen(port, err => {
if (err) {
return console.log(err);
}
if (isInteractive) {
clearConsole();
}
console.log(chalk.cyan('Starting the development server...'));
console.log();
openBrowser(protocol + '://' + host + ':' + port + '/');
});
}
function run(port) {
var protocol = process.env.HTTPS === 'true' ? "https" : "http";
var host = process.env.HOST || 'localhost';
setupCompiler(host, port, protocol);
runDevServer(host, port, protocol);
}
// 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.
detect(DEFAULT_PORT).then(port => {
if (port === DEFAULT_PORT) {
run(port);
return;
}
if (isInteractive) {
clearConsole();
var existingProcess = getProcessForPort(DEFAULT_PORT);
var question =
chalk.yellow('Something is already running on port ' + DEFAULT_PORT + '.' +
((existingProcess) ? ' Probably:\n ' + existingProcess : '')) +
'\n\nWould you like to run the app on another port instead?';
prompt(question, true).then(shouldChangePort => {
if (shouldChangePort) {
run(port);
}
});
} else {
console.log(chalk.red('Something is already running on port ' + DEFAULT_PORT + '.'));
}
});

21
scripts/test.js Normal file
View File

@ -0,0 +1,21 @@
'use strict';
process.env.NODE_ENV = 'test';
process.env.PUBLIC_URL = '';
// Load environment variables from .env file. Suppress warnings using silent
// if this file is missing. dotenv will never modify any environment variables
// that have already been set.
// https://github.com/motdotla/dotenv
require('dotenv').config({silent: true});
const jest = require('jest');
const argv = process.argv.slice(2);
// Watch unless on CI or in coverage mode
if (!process.env.CI && argv.indexOf('--coverage') < 0) {
argv.push('--watch');
}
jest.run(argv);

12
server.js Normal file
View File

@ -0,0 +1,12 @@
const path = require('path')
const throng = require('throng')
const { startServer } = require('./server/index')
const port = parseInt(process.env.PORT, 10) || 5000
const publicDir = path.resolve(__dirname, 'build')
throng({
workers: process.env.WEB_CONCURRENCY || 1,
start: (id) => startServer({ id, port, publicDir }),
lifetime: Infinity
})

View File

@ -74,8 +74,20 @@ const reduceResults = (target, results) => {
return target
}
const OneMinute = 1000 * 60
const ThirtyDays = OneMinute * 60 * 24 * 30
const fetchStats = (callback) => {
const since = new Date(Date.now() - ThirtyDays)
const until = new Date(Date.now() - OneMinute)
getAnalyticsDashboards([ 'npmcdn.com', 'unpkg.com' ], since, until)
.then(result => callback(null, result), callback)
}
module.exports = {
getZones,
getZoneAnalyticsDashboard,
getAnalyticsDashboards
getAnalyticsDashboards,
fetchStats
}

17445
server/dev-data.json Normal file

File diff suppressed because it is too large Load Diff

111
server/index.js Normal file
View File

@ -0,0 +1,111 @@
/*eslint-disable no-console*/
const http = require('http')
const express = require('express')
const cors = require('cors')
const morgan = require('morgan')
const unpkg = require('express-unpkg')
const { fetchStats } = require('./cloudflare')
const { logPackageRequests } = require('./logging')
const fs = require('fs')
const path = require('path')
const sendHomePage = (publicDir) => {
const html = fs.readFileSync(path.join(publicDir, 'index.html'), 'utf8')
return (req, res, next) => {
fetchStats((error, stats) => {
if (error) {
next(error)
} else {
res.set('Cache-Control', 'public, max-age=60')
res.send(
html.replace('__SERVER_DATA__', JSON.stringify({
cloudflareStats: stats
}))
)
}
})
}
}
const errorHandler = (err, req, res, next) => {
res.status(500).send('<p>Internal Server Error</p>')
console.error(err.stack)
next(err)
}
const createServer = (config) => {
const app = express()
app.disable('x-powered-by')
if (process.env.NODE_ENV === 'development')
app.use(morgan('dev'))
app.use(errorHandler)
app.use(cors())
app.get('/', sendHomePage(config.publicDir))
app.use(express.static(config.publicDir, {
maxAge: config.maxAge
}))
if (config.redisURL)
app.use(logPackageRequests(config.redisURL))
app.use(unpkg.createRequestHandler(config))
const server = http.createServer(app)
// Heroku dynos automatically timeout after 30s. Set our
// own timeout here to force sockets to close before that.
// https://devcenter.heroku.com/articles/request-timeout
if (config.timeout) {
server.setTimeout(config.timeout, (socket) => {
const message = `Timeout of ${config.timeout}ms exceeded`
socket.end([
`HTTP/1.1 503 Service Unavailable`,
`Date: ${(new Date).toGMTString()}`,
`Content-Type: text/plain`,
`Content-Length: ${message.length}`,
`Connection: close`,
``,
message
].join(`\r\n`))
})
}
return server
}
const defaultServerConfig = {
id: 1,
port: parseInt(process.env.PORT, 10) || 5000,
publicDir: 'public',
timeout: parseInt(process.env.TIMEOUT, 10) || 20000,
maxAge: process.env.MAX_AGE || '365d',
// for express-unpkg
registryURL: process.env.REGISTRY_URL || 'https://registry.npmjs.org',
redirectTTL: process.env.REDIRECT_TTL || 500,
autoIndex: !process.env.DISABLE_INDEX,
redisURL: process.env.REDIS_URL,
blacklist: require('./package-blacklist').blacklist
}
const startServer = (serverConfig = {}) => {
const config = Object.assign({}, defaultServerConfig, serverConfig)
const server = createServer(config)
server.listen(config.port, () => {
console.log('Server #%s listening on port %s, Ctrl+C to stop', config.id, config.port)
})
}
module.exports = {
createServer,
startServer
}

View File

@ -3,7 +3,7 @@ const onFinished = require('on-finished')
const URLFormat = /^\/((?:@[^\/@]+\/)?[^\/@]+)(?:@([^\/]+))?(\/.*)?$/
const logStats = (redisURL) => {
const logPackageRequests = (redisURL) => {
const redisClient = redis.createClient(redisURL)
return (req, res, next) => {
@ -27,5 +27,5 @@ const logStats = (redisURL) => {
}
module.exports = {
logStats
logPackageRequests
}

View File

@ -0,0 +1,6 @@
{
"blacklist": [
"goodjsproject",
"thisoneisevil"
]
}

View File

@ -1,16 +0,0 @@
const { execSync } = require('child_process')
console.log('Building CommonJS modules ...')
execSync('rimraf lib && babel ./modules -d lib --copy-files', {
stdio: 'inherit'
})
console.log('\nBuilding client bundles ...')
execSync('webpack -p --json > stats.json', {
stdio: 'inherit',
env: Object.assign({}, process.env, {
NODE_ENV: 'production'
})
})

View File

@ -1,48 +0,0 @@
const path = require('path')
const webpack = require('webpack')
const autoprefixer = require('autoprefixer')
const ChunkManifestPlugin = require('chunk-manifest-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const WebpackMD5Hash = require('webpack-md5-hash')
module.exports = {
entry: {
vendor: [ 'react', 'react-dom' ],
home: path.resolve(__dirname, 'modules/client/home.js')
},
output: {
filename: '[chunkhash:8]-[name].js',
path: path.resolve(__dirname, 'public/__assets__'),
publicPath: '/__assets__/'
},
module: {
loaders: [
{ test: /\.js$/, exclude: /node_modules/, loader: 'babel' },
{ test: /\.css$/, loader: ExtractTextPlugin.extract('style', 'css!postcss') },
{ test: /\.json$/, loader: 'json' },
{ test: /\.png$/, loader: 'file' },
{ test: /\.md$/, loader: 'html!markdown' }
]
},
plugins: [
new WebpackMD5Hash(),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks: Infinity
}),
new ChunkManifestPlugin({
filename: 'chunk-manifest.json',
manifestVariable: 'webpackManifest'
}),
new ExtractTextPlugin('[chunkhash:8]-styles.css'),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
}),
new webpack.optimize.OccurrenceOrderPlugin()
],
postcss: () => [ autoprefixer ]
}

2335
yarn.lock

File diff suppressed because it is too large Load Diff