Commit b6c8d2a4 authored by Tim Neutkens's avatar Tim Neutkens

Merge branch 'canary'

# Conflicts:
#	package.json
parents ae7e5323 8e9b84bf
......@@ -5,8 +5,11 @@
"@babel/preset-flow"
],
"plugins": [
"@babel/plugin-syntax-dynamic-import",
"@babel/plugin-proposal-object-rest-spread",
"@babel/plugin-proposal-class-properties",
"@babel/plugin-transform-runtime"
["@babel/plugin-transform-runtime", {
"corejs": 2
}]
]
}
version: 2
jobs:
build:
docker:
- image: circleci/node:8-browsers
working_directory: ~/repo
steps:
- checkout
- run: yarn install
- run: yarn test
......@@ -5,6 +5,7 @@ dist
# dependencies
node_modules
package-lock.json
yarn.lock
test/node_modules
# logs & pids
......
......@@ -8,23 +8,25 @@
}
},
language: "node_js",
node_js: ["6"],
node_js: ["8"],
cache: {
directories: ["node_modules"]
},
before_install: [
"rm yarn.lock",
"export DISPLAY=:99.0",
"sh -e /etc/init.d/xvfb start",
"sleep 3"
],
before_cache: [
"rm -rf node_modules/.cache"
],
after_script: ["npm run coveralls"],
deploy: {
provider: "npm",
email: "leo@zeit.co",
tag: "canary",
api_key: {
secure: "alCjiA+nrKvD+ZQwb/UNaxX4FH5He3/qrzYIQ+sLBlr9N5nfm2JvP0tUsKG9R1DcyYH8yUF3+2ih+3XZqq2EZxPNdYnNQ4diKjHQQw5LPGbMirT+k21PO8/lLxJpx1ZaMY0p19zMZsvVTdFT2eCfTBxvjiN+lwXSWSFF0FjevXelnZRPgqtp6v7AfU04uxk+IRPrktwGomyYuQqbaCn0IkaRruvaafkicUUcACNjoGI1TnxmrkOPJUulFCHj6+tSqv5UFaHqPa0LxU+8wubkbMZfngJTAftfqt3Z13lDtQSj0TLz5VbulhLRIa3sSD/WY6RWpGE66O1fn1PRiUx3SUKLKuJ1ePo6mAtnlgQYq9J1OpNAdwAHXnoP5nw4l6oX1bk0TmFOv1iPR+KdrcaGzM1skBQwkpdXIwvQIK0EJW7hx6Ioopy1eAhHixX719kqvnv08iUbWzWvQHqhs2ZdSL1x6QuPrF3brVTzakEKehK7MUSKVIpzoix87HSw98DH7HSXlhzsLHGROg7K5WqODAal7421xk20L5xWFJG4orSZ0JzVY5rtidtFfWpYRbNcD0a6nHvtHlnQblumRfZciJ2KvC7bmp+PStb7LNjQmEH9v/pD8QT1h8XwGcRbpZInpjgrgi1UYc9U29ORNjnPHcgwPeNW3rQ2u9pglgu69ag="
secure: "MJfpcAJC1IvPL01NiGRLYAAgb7TZz5K0ukM1n+E+QcoF9+L1gn4WcP056ECchuohEFSwvO/ZcTZM5yhpp10cd72RZykeat/YYgRXFyUDkD3up2FHr4hYdcv/tBHCkeUMJZwt1ZNH4xM69Y02KAmpRBWZGKe6qETlZqxUg79Gi1g6W5PdhbsKedTp2tJJzG58nevKsSRP01S97K7kDC5oJNwuO+cbLwtzX5cB6Rd8hGx6lMetWLzSmSS689N0flfm/R9pxY/WjgBBQ0iYZkosb1VO2NhJMnrHtdr/Wfrkvnz8KSO/KD2n7RrOnSzUQBJSNxx35kr7HU4pKreMxEiOnEbOog4HZmWsM0UyRlbYeREfXLBvIjlnYoWCblZdVbdIl4R7NflVBSeK2eDkZQt2iCqP0fHvJ7kyLQx9J2janlr+96dKSudalercfmV9aXtbCeweqim5l4AZywSggpZAvopE6uN6KtFafO0JM760flbQfDVEQWHrHGvZvu05NrzJvZa6CN47rDHbaO6IibMXakogVz+AIuTZ3t/2bynetkericV8MGdOrwb807DLWTdqNKCj2wTmHgDiX8n3FF7VisLS54mKFfuuzzALdWtlBPbwS+bZ0235/35rs2EUidC5eunryWp4Y150xWfCK2swxM9xR0iCE0KSXrsdGDGyrvE="
},
skip_cleanup: true,
on: {
......
This diff is collapsed.
environment:
matrix:
- nodejs_version: "6"
- nodejs_version: "8"
# Install scripts. (runs after repo cloning)
install:
......
......@@ -75,7 +75,7 @@ const startProcess = () => {
process.exit(137)
}
console.log(`got signal ${signal}, exiting`)
process.exit(1)
process.exit(signal === 'SIGINT' ? 0 : 1)
}
process.exit(0)
})
......
#!/usr/bin/env node
import { resolve, join } from 'path'
import parseArgs from 'minimist'
import { existsSync, readFileSync } from 'fs'
import { existsSync } from 'fs'
import Server from '../server'
import { printAndExit } from '../lib/utils'
......@@ -65,9 +65,14 @@ srv.start(argv.port, argv.hostname)
const pkgAppPath = require('find-up').sync('package.json', {
cwd: dir
})
const appPackage = JSON.parse(readFileSync(pkgAppPath, 'utf8'))
const nextScript = Object.entries(appPackage.scripts).find(scriptLine => scriptLine[1] === 'next')
if (nextScript) errorMessage += `\nUse \`npm run ${nextScript[0]} -- -p <some other port>\`.`
const appPackage = require(pkgAppPath)
if (appPackage.scripts) {
const nextScript = Object.entries(appPackage.scripts).find(scriptLine => scriptLine[1] === 'next')
if (nextScript) {
errorMessage += `\nUse \`npm run ${nextScript[0]} -- -p <some other port>\`.`
}
}
console.error(errorMessage)
} else {
console.error(err)
......
......@@ -2,7 +2,7 @@
import { resolve, join } from 'path'
import { existsSync } from 'fs'
import parseArgs from 'minimist'
import exportApp from '../server/export'
import exportApp from '../export'
import { printAndExit } from '../lib/utils'
const argv = parseArgs(process.argv.slice(2), {
......@@ -57,6 +57,10 @@ const options = {
outdir: argv.outdir ? resolve(argv.outdir) : resolve(dir, 'out')
}
exportApp(dir, options).catch((err) => {
printAndExit(err)
})
exportApp(dir, options)
.then(() => {
printAndExit('Export successful', 0)
})
.catch((err) => {
printAndExit(err)
})
// Based on https://github.com/airbnb/babel-plugin-dynamic-import-webpack
// We've added support for SSR with this version
import template from '@babel/template'
import syntax from '@babel/plugin-syntax-dynamic-import'
import { dirname, resolve, sep } from 'path'
import Crypto from 'crypto'
const TYPE_IMPORT = 'Import'
/*
Added "typeof require.resolveWeak !== 'function'" check instead of
"typeof window === 'undefined'" to support dynamic impports in non-webpack environments.
"require.resolveWeak" and "require.ensure" are webpack specific methods.
They would fail in Node/CommonJS environments.
*/
const buildImport = (args) => (template(`
(
typeof require.resolveWeak !== 'function' ?
new (require('next/dynamic').SameLoopPromise)((resolve, reject) => {
eval('require.ensure = function (deps, callback) { callback(require) }')
require.ensure([], (require) => {
let m = require(SOURCE)
m.__webpackChunkName = '${args.name}.js'
resolve(m);
}, 'chunks/${args.name}.js');
})
:
new (require('next/dynamic').SameLoopPromise)((resolve, reject) => {
const weakId = require.resolveWeak(SOURCE)
try {
const weakModule = __webpack_require__(weakId)
return resolve(weakModule)
} catch (err) {}
require.ensure([], (require) => {
try {
let m = require(SOURCE)
m.__webpackChunkName = '${args.name}'
resolve(m)
} catch(error) {
reject(error)
}
}, 'chunks/${args.name}');
})
)
`))
export function getModulePath (sourceFilename, moduleName) {
// resolve only if it's a local module
const modulePath = (moduleName[0] === '.')
? resolve(dirname(sourceFilename), moduleName) : moduleName
const cleanedModulePath = modulePath
.replace(/(index){0,1}\.js$/, '') // remove .js, index.js
.replace(/[/\\]$/, '') // remove end slash
return cleanedModulePath
}
export default () => ({
inherits: syntax,
visitor: {
CallExpression (path, state) {
if (path.node.callee.type === TYPE_IMPORT) {
const moduleName = path.node.arguments[0].value
const sourceFilename = state.file.opts.filename
const modulePath = getModulePath(sourceFilename, moduleName)
const modulePathHash = Crypto.createHash('md5').update(modulePath).digest('hex')
const relativeModulePath = modulePath.replace(`${process.cwd()}${sep}`, '')
const name = `${relativeModulePath.replace(/[^\w]/g, '_')}_${modulePathHash}`
const newImport = buildImport({
name
})({
SOURCE: path.node.arguments
})
path.replaceWith(newImport)
}
}
}
})
/**
COPYRIGHT (c) 2017-present James Kyle <me@thejameskyle.com>
MIT License
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWAR
*/
// This file is https://github.com/jamiebuilds/react-loadable/blob/master/src/babel.js
// Modified to also look for `next/dynamic`
// Modified to put `webpack` and `modules` under `loadableGenerated` to be backwards compatible with next/dynamic which has a `modules` key
// Modified to support `dynamic(import('something'))` and `dynamic(import('something'), options)
export default function ({ types: t, template }) {
return {
visitor: {
ImportDeclaration (path) {
let source = path.node.source.value
if (source !== 'next/dynamic') return
let defaultSpecifier = path.get('specifiers').find(specifier => {
return specifier.isImportDefaultSpecifier()
})
if (!defaultSpecifier) return
let bindingName = defaultSpecifier.node.local.name
let binding = path.scope.getBinding(bindingName)
binding.referencePaths.forEach(refPath => {
let callExpression = refPath.parentPath
if (
callExpression.isMemberExpression() &&
callExpression.node.computed === false &&
callExpression.get('property').isIdentifier({ name: 'Map' })
) {
callExpression = callExpression.parentPath
}
if (!callExpression.isCallExpression()) return
let args = callExpression.get('arguments')
if (args.length > 2) throw callExpression.error
let loader
let options
if (!args[0]) {
return
}
if (args[0].isCallExpression()) {
if (!args[1]) {
callExpression.pushContainer('arguments', t.objectExpression([]))
}
args = callExpression.get('arguments')
loader = args[0]
options = args[1]
} else {
options = args[0]
}
if (!options.isObjectExpression()) return
let properties = options.get('properties')
let propertiesMap = {}
properties.forEach(property => {
let key = property.get('key')
propertiesMap[key.node.name] = property
})
if (propertiesMap.loadableGenerated) {
return
}
if (propertiesMap.loader) {
loader = propertiesMap.loader.get('value')
}
if (propertiesMap.modules) {
loader = propertiesMap.modules.get('value')
}
let loaderMethod = loader
let dynamicImports = []
loaderMethod.traverse({
Import (path) {
dynamicImports.push(path.parentPath)
}
})
if (!dynamicImports.length) return
options.pushContainer(
'properties',
t.objectProperty(
t.identifier('loadableGenerated'),
t.objectExpression([
t.objectProperty(
t.identifier('webpack'),
t.arrowFunctionExpression(
[],
t.arrayExpression(
dynamicImports.map(dynamicImport => {
return t.callExpression(
t.memberExpression(
t.identifier('require'),
t.identifier('resolveWeak')
),
[dynamicImport.get('arguments')[0].node]
)
})
)
)
),
t.objectProperty(
t.identifier('modules'),
t.arrayExpression(
dynamicImports.map(dynamicImport => {
return dynamicImport.get('arguments')[0].node
})
)
)
])
)
)
})
}
}
}
}
const env = process.env.NODE_ENV
const isProduction = env === 'production'
const isDevelopment = env === 'development'
const isTest = env === 'test'
// Resolve styled-jsx plugins
function styledJsxOptions (opts) {
if (!opts) {
......@@ -25,21 +30,29 @@ function styledJsxOptions (opts) {
module.exports = (context, opts = {}) => ({
presets: [
[require('@babel/preset-env'), {
modules: false,
[require('@babel/preset-env').default, {
// In the test environment `modules` is often needed to be set to true, babel figures that out by itself using the `'auto'` option
// In production/development this option is set to `false` so that webpack can handle import/export with tree-shaking
modules: isDevelopment || isProduction ? false : 'auto',
...opts['preset-env']
}],
require('@babel/preset-react')
[require('@babel/preset-react'), {
// This adds @babel/plugin-transform-react-jsx-source and
// @babel/plugin-transform-react-jsx-self automatically in development
development: isDevelopment || isTest,
...opts['preset-react']
}]
],
plugins: [
require('babel-plugin-react-require'),
require('./plugins/handle-import'),
require('@babel/plugin-syntax-dynamic-import'),
require('./plugins/react-loadable-plugin'),
[require('@babel/plugin-proposal-class-properties'), opts['class-properties'] || {}],
require('@babel/plugin-proposal-object-rest-spread'),
[require('@babel/plugin-transform-runtime'), opts['transform-runtime'] || {
[require('@babel/plugin-transform-runtime'), {
helpers: false,
polyfill: false,
regenerator: true
regenerator: true,
...opts['transform-runtime']
}],
[require('styled-jsx/babel'), styledJsxOptions(opts['styled-jsx'])],
process.env.NODE_ENV === 'production' && require('babel-plugin-transform-react-remove-prop-types')
......
......@@ -51,7 +51,7 @@ function runCompiler (compiler) {
return reject(error)
}
resolve(jsonStats)
resolve()
})
})
}
......
This diff is collapsed.
......@@ -18,7 +18,7 @@ module.exports = function (content, sourceMap) {
}
const name = query.name || '[hash].[ext]'
const context = query.context || this.options.context
const context = query.context || this.rootContext || this.options.context
const regExp = query.regExp
const opts = { context, content, regExp }
const interpolateName = query.interpolateName || ((name) => name)
......
......@@ -2,7 +2,6 @@ import babelLoader from 'babel-loader'
module.exports = babelLoader.custom(babel => {
const presetItem = babel.createConfigItem(require('../../babel/preset'), {type: 'preset'})
const reactJsxSourceItem = babel.createConfigItem(require('@babel/plugin-transform-react-jsx-source'), {type: 'plugin'})
const configs = new Set()
......@@ -36,11 +35,6 @@ module.exports = babelLoader.custom(babel => {
options.presets = [...options.presets, presetItem]
}
options.plugins = [
...options.plugins,
dev && reactJsxSourceItem
].filter(Boolean)
return options
}
}
......
// @flow
import { RawSource } from 'webpack-sources'
import {BUILD_MANIFEST} from '../../../lib/constants'
import {BUILD_MANIFEST, ROUTE_NAME_REGEX, IS_BUNDLED_PAGE_REGEX, CLIENT_STATIC_FILES_RUNTIME_MAIN} from '../../../lib/constants'
// This plugin creates a build-manifest.json for all assets that are being output
// It has a mapping of "entry" filename to real filename. Because the real filename can be hashed in production
export default class BuildManifestPlugin {
apply (compiler: any) {
compiler.plugin('emit', (compilation, callback) => {
compiler.hooks.emit.tapAsync('NextJsBuildManifest', (compilation, callback) => {
const {chunks} = compilation
const assetMap = {pages: {}, css: []}
const assetMap = {devFiles: [], pages: {}}
for (const chunk of chunks) {
if (!chunk.name || !chunk.files) {
const mainJsChunk = chunks.find((c) => c.name === CLIENT_STATIC_FILES_RUNTIME_MAIN)
const mainJsFiles = mainJsChunk && mainJsChunk.files.length > 0 ? mainJsChunk.files.filter((file) => /\.js$/.test(file)) : []
for (const filePath of Object.keys(compilation.assets)) {
const path = filePath.replace(/\\/g, '/')
if (/^static\/development\/dll\//.test(path)) {
assetMap.devFiles.push(path)
}
}
// compilation.entrypoints is a Map object, so iterating over it 0 is the key and 1 is the value
for (const [, entrypoint] of compilation.entrypoints.entries()) {
const result = ROUTE_NAME_REGEX.exec(entrypoint.name)
if (!result) {
continue
}
const files = []
const pagePath = result[1]
for (const file of chunk.files) {
if (/\.map$/.test(file)) {
continue
}
if (!pagePath) {
continue
}
if (/\.hot-update\.js$/.test(file)) {
const filesForEntry = []
for (const chunk of entrypoint.chunks) {
// If there's no name or no files
if (!chunk.name || !chunk.files) {
continue
}
if (/\.css$/.exec(file)) {
assetMap.css.push(file)
continue
}
for (const file of chunk.files) {
if (/\.map$/.test(file) || /\.hot-update\.js$/.test(file)) {
continue
}
files.push(file)
}
// Only `.js` and `.css` files are added for now. In the future we can also handle other file types.
if (!/\.js$/.test(file) && !/\.css$/.test(file)) {
continue
}
// The page bundles are manually added to _document.js as they need extra properties
if (IS_BUNDLED_PAGE_REGEX.exec(file)) {
continue
}
if (files.length > 0) {
assetMap[chunk.name] = files
filesForEntry.push(file.replace(/\\/g, '/'))
}
}
assetMap.pages[`/${pagePath.replace(/\\/g, '/')}`] = [...filesForEntry, ...mainJsFiles]
}
if (typeof assetMap.pages['/index'] !== 'undefined') {
assetMap.pages['/'] = assetMap.pages['/index']
}
compilation.assets[BUILD_MANIFEST] = new RawSource(JSON.stringify(assetMap))
compilation.assets[BUILD_MANIFEST] = new RawSource(JSON.stringify(assetMap, null, 2))
callback()
})
}
......
// This plugin mirrors webpack 3 `filename` and `chunkfilename` behavior
// This fixes https://github.com/webpack/webpack/issues/6598
// This plugin is based on https://github.com/researchgate/webpack/commit/2f28947fa0c63ccbb18f39c0098bd791a2c37090
export default class ChunkNamesPlugin {
apply (compiler) {
compiler.hooks.compilation.tap('NextJsChunkNamesPlugin', (compilation) => {
compilation.chunkTemplate.hooks.renderManifest.intercept({
register (tapInfo) {
if (tapInfo.name === 'JavascriptModulesPlugin') {
const originalMethod = tapInfo.fn
tapInfo.fn = (result, options) => {
let filenameTemplate
const chunk = options.chunk
const outputOptions = options.outputOptions
if (chunk.filenameTemplate) {
filenameTemplate = chunk.filenameTemplate
} else if (chunk.hasEntryModule()) {
filenameTemplate = outputOptions.filename
} else {
filenameTemplate = outputOptions.chunkFilename
}
options.chunk.filenameTemplate = filenameTemplate
return originalMethod(result, options)
}
}
return tapInfo
}
})
})
}
}
import { ConcatSource } from 'webpack-sources'
const isImportChunk = /^chunks[/\\]/
const matchChunkName = /^chunks[/\\](.*)$/
class DynamicChunkTemplatePlugin {
apply (chunkTemplate) {
chunkTemplate.plugin('render', function (modules, chunk) {
if (!isImportChunk.test(chunk.name)) {
return modules
}
const chunkName = matchChunkName.exec(chunk.name)[1]
const source = new ConcatSource()
source.add(`
__NEXT_REGISTER_CHUNK('${chunkName}', function() {
`)
source.add(modules)
source.add(`
})
`)
return source
})
}
}
export default class DynamicChunksPlugin {
apply (compiler) {
compiler.plugin('compilation', (compilation) => {
compilation.chunkTemplate.apply(new DynamicChunkTemplatePlugin())
compilation.plugin('additional-chunk-assets', (chunks) => {
chunks = chunks.filter(chunk =>
isImportChunk.test(chunk.name) && compilation.assets[chunk.name]
)
chunks.forEach((chunk) => {
// This is to support, webpack dynamic import support with HMR
const copyFilename = `chunks/${chunk.name}`
compilation.additionalChunkAssets.push(copyFilename)
compilation.assets[copyFilename] = compilation.assets[chunk.name]
})
})
})
}
}
// @flow
function deleteCache (path: string) {
delete require.cache[path]
}
// This plugin flushes require.cache after emitting the files. Providing 'hot reloading' of server files.
export default class ChunkNamesPlugin {
prevAssets: null | {[string]: {existsAt: string}}
constructor () {
this.prevAssets = null
}
apply (compiler: any) {
compiler.hooks.afterEmit.tapAsync('NextJsRequireCacheHotReloader', (compilation, callback) => {
const { assets } = compilation
if (this.prevAssets) {
for (const f of Object.keys(assets)) {
deleteCache(assets[f].existsAt)
}
for (const f of Object.keys(this.prevAssets)) {
if (!assets[f]) {
deleteCache(this.prevAssets[f].existsAt)
}
}
}
this.prevAssets = assets
callback()
})
}
}
......@@ -4,8 +4,8 @@ import { join, resolve, relative, dirname } from 'path'
// to work with Next.js SSR
export default class NextJsSsrImportPlugin {
apply (compiler) {
compiler.plugin('compilation', (compilation) => {
compilation.mainTemplate.plugin('require-ensure', (code, chunk) => {
compiler.hooks.compilation.tap('NextJsSSRImport', (compilation) => {
compilation.mainTemplate.hooks.requireEnsure.tap('NextJsSSRImport', (code, chunk) => {
// Update to load chunks from our custom chunks directory
const outputPath = resolve('/')
const pagePath = join('/', dirname(chunk.name))
......@@ -13,16 +13,7 @@ export default class NextJsSsrImportPlugin {
// Make sure even in windows, the path looks like in unix
// Node.js require system will convert it accordingly
const relativePathToBaseDirNormalized = relativePathToBaseDir.replace(/\\/g, '/')
let updatedCode = code.replace('require("./"', `require("${relativePathToBaseDirNormalized}/"`)
// Replace a promise equivalent which runs in the same loop
// If we didn't do this webpack's module loading process block us from
// doing SSR for chunks
updatedCode = updatedCode.replace(
'return Promise.resolve();',
`return require('next/dynamic').SameLoopPromise.resolve();`
)
return updatedCode
return code.replace('require("./"', `require("${relativePathToBaseDirNormalized}/"`).replace('readFile(join(__dirname', `readFile(join(__dirname, "${relativePathToBaseDirNormalized}"`)
})
})
}
......
import webpack from 'webpack'
import { RawSource } from 'webpack-sources'
import { join, relative, dirname } from 'path'
import {IS_BUNDLED_PAGE_REGEX} from '../../../lib/constants'
const SSR_MODULE_CACHE_FILENAME = 'ssr-module-cache.js'
// By default webpack keeps initialized modules per-module.
// This means that if you have 2 entrypoints loaded into the same app
// they will *not* share the same instance
// This creates many issues when developers / libraries rely on the singleton pattern
// As this pattern assumes every module will have 1 instance
// This plugin overrides webpack's code generation step to replace `installedModules`
// The replacement is a require for a file that's also generated here that only exports an empty object
// Because of Node.js's single instance modules this makes webpack share all initialized instances
// Do note that this module is only geared towards the `node` compilation target.
// For the client side compilation we use `runtimeChunk: 'single'`
export default class NextJsSsrImportPlugin {
constructor (options) {
this.options = options
}
apply (compiler) {
const {outputPath} = this.options
compiler.hooks.emit.tapAsync('NextJsSSRModuleCache', (compilation, callback) => {
compilation.assets[SSR_MODULE_CACHE_FILENAME] = new RawSource(`
/* This cache is used by webpack for instantiated modules */
module.exports = {}
`)
callback()
})
compiler.hooks.compilation.tap('NextJsSSRModuleCache', (compilation) => {
compilation.mainTemplate.hooks.localVars.intercept({
register (tapInfo) {
if (tapInfo.name === 'MainTemplate') {
const originalFn = tapInfo.fn
tapInfo.fn = (source, chunk) => {
// If the chunk is not part of the pages directory we have to keep the original behavior,
// otherwise webpack will error out when the file is used before the compilation finishes
// this is the case with mini-css-extract-plugin
if (!IS_BUNDLED_PAGE_REGEX.exec(chunk.name)) {
return originalFn(source, chunk)
}
const pagePath = join(outputPath, dirname(chunk.name))
const relativePathToBaseDir = relative(pagePath, join(outputPath, SSR_MODULE_CACHE_FILENAME))
// Make sure even in windows, the path looks like in unix
// Node.js require system will convert it accordingly
const relativePathToBaseDirNormalized = relativePathToBaseDir.replace(/\\/g, '/')
return webpack.Template.asString([
source,
'// The module cache',
`var installedModules = require('${relativePathToBaseDirNormalized}');`
])
}
}
return tapInfo
}
})
})
}
}
......@@ -3,11 +3,11 @@ import { RawSource } from 'webpack-sources'
import {PAGES_MANIFEST, ROUTE_NAME_REGEX} from '../../../lib/constants'
// This plugin creates a pages-manifest.json from page entrypoints.
// This is used for mapping paths like `/` to `.next/dist/bundles/pages/index.js` when doing SSR
// This is used for mapping paths like `/` to `.next/server/static/<buildid>/pages/index.js` when doing SSR
// It's also used by next export to provide defaultPathMap
export default class PagesManifestPlugin {
apply (compiler: any) {
compiler.plugin('emit', (compilation, callback) => {
compiler.hooks.emit.tap('NextJsPagesManifest', (compilation) => {
const {entries} = compilation
const pages = {}
......@@ -32,7 +32,6 @@ export default class PagesManifestPlugin {
}
compilation.assets[PAGES_MANIFEST] = new RawSource(JSON.stringify(pages))
callback()
})
}
}
......@@ -5,47 +5,50 @@ import {
ROUTE_NAME_REGEX
} from '../../../lib/constants'
class PageChunkTemplatePlugin {
apply (chunkTemplate) {
chunkTemplate.plugin('render', function (modules, chunk) {
if (!IS_BUNDLED_PAGE_REGEX.test(chunk.name)) {
return modules
}
let routeName = ROUTE_NAME_REGEX.exec(chunk.name)[1]
// We need to convert \ into / when we are in windows
// to get the proper route name
// Here we need to do windows check because it's possible
// to have "\" in the filename in unix.
// Anyway if someone did that, he'll be having issues here.
// But that's something we cannot avoid.
if (/^win/.test(process.platform)) {
routeName = routeName.replace(/\\/g, '/')
}
routeName = `/${routeName.replace(/(^|\/)index$/, '')}`
const source = new ConcatSource()
source.add(`__NEXT_REGISTER_PAGE('${routeName}', function() {
var comp =
`)
source.add(modules)
source.add(`
return { page: comp.default }
})
`)
return source
})
}
}
export default class PagesPlugin {
apply (compiler: any) {
compiler.plugin('compilation', (compilation) => {
compilation.chunkTemplate.apply(new PageChunkTemplatePlugin())
compiler.hooks.compilation.tap('PagesPlugin', (compilation) => {
// This hook is triggered right before a module gets wrapped into it's initializing function,
// For example when you look at the source of a bundle you'll see an object holding `'pages/_app.js': function(module, etc, etc)`
// This hook triggers right before that code is added and wraps the module into `__NEXT_REGISTER_PAGE` when the module is a page
// The reason we're doing this is that we don't want to execute the page code which has potential side effects before switching to a route
compilation.moduleTemplates.javascript.hooks.render.tap('PagesPluginRenderPageRegister', (moduleSourcePostModule, module, options) => {
const {chunk} = options
// check if the current module is the entry module, we only want to wrap the topmost module
if (chunk.entryModule !== module) {
return moduleSourcePostModule
}
// Check if the chunk is a page
if (!IS_BUNDLED_PAGE_REGEX.test(chunk.name)) {
return moduleSourcePostModule
}
// Match the route the chunk belongs to
let routeName = ROUTE_NAME_REGEX.exec(chunk.name)[1]
// We need to convert \ into / when we are in windows
// to get the proper route name
// Here we need to do windows check because it's possible
// to have "\" in the filename in unix.
// Anyway if someone did that, he'll be having issues here.
// But that's something we cannot avoid.
if (/^win/.test(process.platform)) {
routeName = routeName.replace(/\\/g, '/')
}
routeName = `/${routeName.replace(/(^|\/)index$/, '')}`
const source = new ConcatSource(
`__NEXT_REGISTER_PAGE('${routeName}', function() {\n`,
moduleSourcePostModule,
'\nreturn { page: module.exports.default }',
'});'
)
return source
})
})
}
}
/**
COPYRIGHT (c) 2017-present James Kyle <me@thejameskyle.com>
MIT License
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWAR
*/
// Implementation of this PR: https://github.com/jamiebuilds/react-loadable/pull/132
// Modified to strip out unneeded results for Next's specific use case
import url from 'url'
function buildManifest (compiler, compilation) {
let context = compiler.options.context
let manifest = {}
compilation.chunks.forEach(chunk => {
chunk.files.forEach(file => {
for (const module of chunk.modulesIterable) {
let id = module.id
let name = typeof module.libIdent === 'function' ? module.libIdent({ context }) : null
// If it doesn't end in `.js` Next.js can't handle it right now.
if (!file.match(/\.js$/) || !file.match(/^static\/chunks\//)) {
return
}
let publicPath = url.resolve(compilation.outputOptions.publicPath || '', file)
let currentModule = module
if (module.constructor.name === 'ConcatenatedModule') {
currentModule = module.rootModule
}
if (!manifest[currentModule.rawRequest]) {
manifest[currentModule.rawRequest] = []
}
manifest[currentModule.rawRequest].push({ id, name, file, publicPath })
}
})
})
return manifest
}
export class ReactLoadablePlugin {
constructor (opts = {}) {
this.filename = opts.filename
}
apply (compiler) {
compiler.hooks.emit.tapAsync('ReactLoadableManifest', (compilation, callback) => {
const manifest = buildManifest(compiler, compilation)
var json = JSON.stringify(manifest, null, 2)
compilation.assets[this.filename] = {
source () {
return json
},
size () {
return json.length
}
}
callback()
})
}
}
......@@ -6,6 +6,7 @@ import { IS_BUNDLED_PAGE_REGEX } from '../../../lib/constants'
const unlink = promisify(fs.unlink)
// Makes sure removed pages are removed from `.next` in development
export default class UnlinkFilePlugin {
prevAssets: any
constructor () {
......@@ -13,7 +14,7 @@ export default class UnlinkFilePlugin {
}
apply (compiler: any) {
compiler.plugin('after-emit', (compilation, callback) => {
compiler.hooks.afterEmit.tapAsync('NextJsUnlinkRemovedPages', (compilation, callback) => {
const removed = Object.keys(this.prevAssets)
.filter((a) => IS_BUNDLED_PAGE_REGEX.test(a) && !compilation.assets[a])
......
import path from 'path'
import promisify from '../../lib/promisify'
import globModule from 'glob'
import {CLIENT_STATIC_FILES_PATH} from '../../lib/constants'
const glob = promisify(globModule)
export async function getPages (dir, {nextPagesDir, dev, isServer, pageExtensions}) {
export async function getPages (dir, {nextPagesDir, dev, buildId, isServer, pageExtensions}) {
const pageFiles = await getPagePaths(dir, {dev, isServer, pageExtensions})
return getPageEntries(pageFiles, {nextPagesDir, isServer, pageExtensions})
return getPageEntries(pageFiles, {nextPagesDir, buildId, isServer, pageExtensions})
}
export async function getPagePaths (dir, {dev, isServer, pageExtensions}) {
......@@ -15,8 +16,7 @@ export async function getPagePaths (dir, {dev, isServer, pageExtensions}) {
if (dev) {
// In development we only compile _document.js, _error.js and _app.js when starting, since they're always needed. All other pages are compiled with on demand entries
// _document also has to be in the client compiler in development because we want to detect HMR changes and reload the client
pages = await glob(`pages/+(_document|_app|_error).+(${pageExtensions})`, { cwd: dir })
pages = await glob(isServer ? `pages/+(_document|_app|_error).+(${pageExtensions})` : `pages/+(_app|_error).+(${pageExtensions})`, { cwd: dir })
} else {
// In production get all pages from the pages directory
pages = await glob(isServer ? `pages/**/*.+(${pageExtensions})` : `pages/**/!(_document)*.+(${pageExtensions})`, { cwd: dir })
......@@ -26,7 +26,7 @@ export async function getPagePaths (dir, {dev, isServer, pageExtensions}) {
}
// Convert page path into single entry
export function createEntry (filePath, {name, pageExtensions} = {}) {
export function createEntry (filePath, {buildId = '', name, pageExtensions} = {}) {
const parsedPath = path.parse(filePath)
let entryName = name || filePath
......@@ -42,35 +42,35 @@ export function createEntry (filePath, {name, pageExtensions} = {}) {
}
return {
name: path.join('bundles', entryName),
name: path.join(CLIENT_STATIC_FILES_PATH, buildId, entryName),
files: [parsedPath.root ? filePath : `./${filePath}`] // The entry always has to be an array.
}
}
// Convert page paths into entries
export function getPageEntries (pagePaths, {nextPagesDir, isServer = false, pageExtensions} = {}) {
export function getPageEntries (pagePaths, {nextPagesDir, buildId, isServer = false, pageExtensions} = {}) {
const entries = {}
for (const filePath of pagePaths) {
const entry = createEntry(filePath, {pageExtensions})
const entry = createEntry(filePath, {pageExtensions, buildId})
entries[entry.name] = entry.files
}
const appPagePath = path.join(nextPagesDir, '_app.js')
const appPageEntry = createEntry(appPagePath, {name: 'pages/_app.js'}) // default app.js
const appPageEntry = createEntry(appPagePath, {buildId, name: 'pages/_app.js'}) // default app.js
if (!entries[appPageEntry.name]) {
entries[appPageEntry.name] = appPageEntry.files
}
const errorPagePath = path.join(nextPagesDir, '_error.js')
const errorPageEntry = createEntry(errorPagePath, {name: 'pages/_error.js'}) // default error.js
const errorPageEntry = createEntry(errorPagePath, {buildId, name: 'pages/_error.js'}) // default error.js
if (!entries[errorPageEntry.name]) {
entries[errorPageEntry.name] = errorPageEntry.files
}
if (isServer) {
const documentPagePath = path.join(nextPagesDir, '_document.js')
const documentPageEntry = createEntry(documentPagePath, {name: 'pages/_document.js'}) // default _document.js
const documentPageEntry = createEntry(documentPagePath, {buildId, name: 'pages/_document.js'}) // default _document.js
if (!entries[documentPageEntry.name]) {
entries[documentPageEntry.name] = documentPageEntry.files
}
......
// @flow
import React from 'react'
import {applySourcemaps} from './source-map-support'
import ErrorDebug, {styles} from '../lib/error-debug'
import type {RuntimeError, ErrorReporterProps} from './error-boundary'
type State = {|
mappedError: null | RuntimeError
|}
// This component is only used in development, sourcemaps are applied on the fly because componentDidCatch is not async
class DevErrorOverlay extends React.Component<ErrorReporterProps, State> {
state = {
mappedError: null
}
componentDidMount () {
const {error} = this.props
// Since componentDidMount doesn't handle errors we use then/catch here
applySourcemaps(error).then(() => {
this.setState({mappedError: error})
}).catch((caughtError) => {
this.setState({mappedError: caughtError})
})
}
render () {
const {mappedError} = this.state
const {info} = this.props
if (mappedError === null) {
return <div style={styles.errorDebug}>
<h1 style={styles.heading}>Loading stacktrace...</h1>
</div>
}
return <ErrorDebug error={mappedError} info={info} />
}
}
export default DevErrorOverlay
function EventSourceWrapper (options) {
var source
var lastActivity = new Date()
var listeners = []
if (!options.timeout) {
options.timeout = 20 * 1000
}
init()
var timer = setInterval(function () {
if ((new Date() - lastActivity) > options.timeout) {
handleDisconnect()
}
}, options.timeout / 2)
function init () {
source = new window.EventSource(options.path)
source.onopen = handleOnline
source.onerror = handleDisconnect
source.onmessage = handleMessage
}
function handleOnline () {
if (options.log) console.log('[HMR] connected')
lastActivity = new Date()
}
function handleMessage (event) {
lastActivity = new Date()
for (var i = 0; i < listeners.length; i++) {
listeners[i](event)
}
}
function handleDisconnect () {
clearInterval(timer)
source.close()
setTimeout(init, options.timeout)
}
return {
addMessageListener: function (fn) {
listeners.push(fn)
}
}
}
export function getEventSourceWrapper (options) {
if (!window.__whmEventSourceWrapper) {
window.__whmEventSourceWrapper = {}
}
if (!window.__whmEventSourceWrapper[options.path]) {
// cache the wrapper for other entries loaded on
// the same page with the same options.path
window.__whmEventSourceWrapper[options.path] = EventSourceWrapper(options)
}
return window.__whmEventSourceWrapper[options.path]
}
/**
MIT License
Copyright (c) 2013-present, Facebook, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
// This file is based on https://github.com/facebook/create-react-app/blob/v1.1.4/packages/react-dev-utils/formatWebpackMessages.js
// It's been edited to remove chalk
'use strict'
// Some custom utilities to prettify Webpack output.
// This is quite hacky and hopefully won't be needed when Webpack fixes this.
// https://github.com/webpack/webpack/issues/2878
var friendlySyntaxErrorLabel = 'Syntax error:'
function isLikelyASyntaxError (message) {
return message.indexOf(friendlySyntaxErrorLabel) !== -1
}
// Cleans up webpack error messages.
// eslint-disable-next-line no-unused-vars
function formatMessage (message, isError) {
var lines = message.split('\n')
if (lines.length > 2 && lines[1] === '') {
// Remove extra newline.
lines.splice(1, 1)
}
// Remove webpack-specific loader notation from filename.
// Before:
// ./~/css-loader!./~/postcss-loader!./src/App.css
// After:
// ./src/App.css
if (lines[0].lastIndexOf('!') !== -1) {
lines[0] = lines[0].substr(lines[0].lastIndexOf('!') + 1)
}
// Remove unnecessary stack added by `thread-loader`
var threadLoaderIndex = -1
lines.forEach(function (line, index) {
if (threadLoaderIndex !== -1) {
return
}
if (/thread.loader/i.test(line)) {
threadLoaderIndex = index
}
})
if (threadLoaderIndex !== -1) {
lines = lines.slice(0, threadLoaderIndex)
}
lines = lines.filter(function (line) {
// Webpack adds a list of entry points to warning messages:
// @ ./src/index.js
// @ multi react-scripts/~/react-dev-utils/webpackHotDevClient.js ...
// It is misleading (and unrelated to the warnings) so we clean it up.
// It is only useful for syntax errors but we have beautiful frames for them.
return line.indexOf(' @ ') !== 0
})
// line #0 is filename
// line #1 is the main error message
if (!lines[0] || !lines[1]) {
return lines.join('\n')
}
// Cleans up verbose "module not found" messages for files and packages.
if (lines[1].indexOf('Module not found: ') === 0) {
lines = [
lines[0],
// Clean up message because "Module not found: " is descriptive enough.
lines[1]
.replace("Cannot resolve 'file' or 'directory' ", '')
.replace('Cannot resolve module ', '')
.replace('Error: ', '')
.replace('[CaseSensitivePathsPlugin] ', '')
]
}
// Cleans up syntax error messages.
if (lines[1].indexOf('Module build failed: ') === 0) {
lines[1] = lines[1].replace(
'Module build failed: SyntaxError:',
friendlySyntaxErrorLabel
)
}
// Clean up export errors.
// TODO: we should really send a PR to Webpack for this.
var exportError = /\s*(.+?)\s*(")?export '(.+?)' was not found in '(.+?)'/
if (lines[1].match(exportError)) {
lines[1] = lines[1].replace(
exportError,
"$1 '$4' does not contain an export named '$3'."
)
}
// Reassemble the message.
message = lines.join('\n')
// Internal stacks are generally useless so we strip them... with the
// exception of stacks containing `webpack:` because they're normally
// from user code generated by WebPack. For more information see
// https://github.com/facebook/create-react-app/pull/1050
message = message.replace(
/^\s*at\s((?!webpack:).)*:\d+:\d+[\s)]*(\n|$)/gm,
''
) // at ... ...:x:y
return message.trim()
}
function formatWebpackMessages (json) {
var formattedErrors = json.errors.map(function (message) {
return formatMessage(message, true)
})
var formattedWarnings = json.warnings.map(function (message) {
return formatMessage(message, false)
})
var result = {
errors: formattedErrors,
warnings: formattedWarnings
}
if (result.errors.some(isLikelyASyntaxError)) {
// If there are any syntax errors, show just them.
// This prevents a confusing ESLint parsing error
// preceding a much more useful Babel syntax error.
result.errors = result.errors.filter(isLikelyASyntaxError)
}
return result
}
module.exports = formatWebpackMessages
/* eslint-disable camelcase */
/**
MIT License
Copyright (c) 2013-present, Facebook, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
// This file is based on https://github.com/facebook/create-react-app/blob/v1.1.4/packages/react-dev-utils/webpackHotDevClient.js
// It's been edited to rely on webpack-hot-middleware and to be more compatible with SSR / Next.js
'use strict'
import {getEventSourceWrapper} from './eventsource'
import formatWebpackMessages from './format-webpack-messages'
import * as ErrorOverlay from 'react-error-overlay'
import stripAnsi from 'strip-ansi'
import {rewriteStacktrace} from '../source-map-support'
import fetch from 'unfetch'
// This alternative WebpackDevServer combines the functionality of:
// https://github.com/webpack/webpack-dev-server/blob/webpack-1/client/index.js
// https://github.com/webpack/webpack/blob/webpack-1/hot/dev-server.js
// It only supports their simplest configuration (hot updates on same server).
// It makes some opinionated choices on top, like adding a syntax error overlay
// that looks similar to our console output. The error overlay is inspired by:
// https://github.com/glenjamin/webpack-hot-middleware
// This is a modified version of create-react-app's webpackHotDevClient.js
// It implements webpack-hot-middleware's EventSource events instead of webpack-dev-server's websocket.
// https://github.com/facebook/create-react-app/blob/25184c4e91ebabd16fe1cde3d8630830e4a36a01/packages/react-dev-utils/webpackHotDevClient.js
let hadRuntimeError = false
let customHmrEventHandler
export default function connect (options) {
// Open stack traces in an editor.
ErrorOverlay.setEditorHandler(function editorHandler ({ fileName, lineNumber, colNumber }) {
// Resolve invalid paths coming from react-error-overlay
const resolvedFilename = fileName.replace(/^webpack:\/\//, '')
fetch(
'/_next/development/open-stack-frame-in-editor' +
`?fileName=${window.encodeURIComponent(resolvedFilename)}` +
`&lineNumber=${lineNumber || 1}` +
`&colNumber=${colNumber || 1}`
)
})
// We need to keep track of if there has been a runtime error.
// Essentially, we cannot guarantee application state was not corrupted by the
// runtime error. To prevent confusing behavior, we forcibly reload the entire
// application. This is handled below when we are notified of a compile (code
// change).
// See https://github.com/facebook/create-react-app/issues/3096
ErrorOverlay.startReportingRuntimeErrors({
onError: function () {
hadRuntimeError = true
}
})
if (module.hot && typeof module.hot.dispose === 'function') {
module.hot.dispose(function () {
// TODO: why do we need this?
ErrorOverlay.stopReportingRuntimeErrors()
})
}
getEventSourceWrapper(options).addMessageListener((event) => {
// This is the heartbeat event
if (event.data === '\uD83D\uDC93') {
return
}
try {
processMessage(event)
} catch (ex) {
console.warn('Invalid HMR message: ' + event.data + '\n' + ex)
}
})
return {
subscribeToHmrEvent (handler) {
customHmrEventHandler = handler
},
prepareError (err) {
// Temporary workaround for https://github.com/facebook/create-react-app/issues/4760
// Should be removed once the fix lands
hadRuntimeError = true
// react-error-overlay expects a type of `Error`
const error = new Error(err.message)
error.name = err.name
error.stack = err.stack
// __NEXT_DIST_DIR is provided by webpack
rewriteStacktrace(error, process.env.__NEXT_DIST_DIR)
return error
}
}
}
// Remember some state related to hot module replacement.
var isFirstCompilation = true
var mostRecentCompilationHash = null
var hasCompileErrors = false
function clearOutdatedErrors () {
// Clean up outdated compile errors, if any.
if (typeof console !== 'undefined' && typeof console.clear === 'function') {
if (hasCompileErrors) {
console.clear()
}
}
}
// Successful compilation.
function handleSuccess () {
const isHotUpdate = !isFirstCompilation
isFirstCompilation = false
hasCompileErrors = false
// Attempt to apply hot updates or reload.
if (isHotUpdate) {
tryApplyUpdates(function onHotUpdateSuccess () {
// Only dismiss it when we're sure it's a hot update.
// Otherwise it would flicker right before the reload.
ErrorOverlay.dismissBuildError()
})
}
}
// Compilation with warnings (e.g. ESLint).
function handleWarnings (warnings) {
clearOutdatedErrors()
// Print warnings to the console.
const formatted = formatWebpackMessages({
warnings: warnings,
errors: []
})
if (typeof console !== 'undefined' && typeof console.warn === 'function') {
for (let i = 0; i < formatted.warnings.length; i++) {
if (i === 5) {
console.warn(
'There were more warnings in other files.\n' +
'You can find a complete log in the terminal.'
)
break
}
console.warn(stripAnsi(formatted.warnings[i]))
}
}
}
// Compilation with errors (e.g. syntax error or missing modules).
function handleErrors (errors) {
clearOutdatedErrors()
isFirstCompilation = false
hasCompileErrors = true
// "Massage" webpack messages.
var formatted = formatWebpackMessages({
errors: errors,
warnings: []
})
// Only show the first error.
ErrorOverlay.reportBuildError(formatted.errors[0])
// Also log them to the console.
if (typeof console !== 'undefined' && typeof console.error === 'function') {
for (var i = 0; i < formatted.errors.length; i++) {
console.error(stripAnsi(formatted.errors[i]))
}
}
}
// There is a newer version of the code available.
function handleAvailableHash (hash) {
// Update last known compilation hash.
mostRecentCompilationHash = hash
}
// Handle messages from the server.
function processMessage (e) {
const obj = JSON.parse(e.data)
switch (obj.action) {
case 'building': {
console.log(
'[HMR] bundle ' + (obj.name ? "'" + obj.name + "' " : '') +
'rebuilding'
)
break
}
case 'built':
case 'sync': {
clearOutdatedErrors()
if (obj.hash) {
handleAvailableHash(obj.hash)
}
if (obj.warnings.length > 0) {
handleWarnings(obj.warnings)
break
}
if (obj.errors.length > 0) {
// When there is a compilation error coming from SSR we have to reload the page on next successful compile
if (obj.action === 'sync') {
hadRuntimeError = true
}
handleErrors(obj.errors)
break
}
handleSuccess()
break
}
default: {
if (customHmrEventHandler) {
customHmrEventHandler(obj)
break
}
break
}
}
}
// Is there a newer version of this code available?
function isUpdateAvailable () {
/* globals __webpack_hash__ */
// __webpack_hash__ is the hash of the current compilation.
// It's a global variable injected by Webpack.
return mostRecentCompilationHash !== __webpack_hash__
}
// Webpack disallows updates in other states.
function canApplyUpdates () {
return module.hot.status() === 'idle'
}
// Attempt to update code on the fly, fall back to a hard reload.
async function tryApplyUpdates (onHotUpdateSuccess) {
if (!module.hot) {
// HotModuleReplacementPlugin is not in Webpack configuration.
console.error('HotModuleReplacementPlugin is not in Webpack configuration.')
// window.location.reload();
return
}
if (!isUpdateAvailable() || !canApplyUpdates()) {
return
}
function handleApplyUpdates (err, updatedModules) {
if (err || hadRuntimeError) {
if (err) {
console.warn('Error while applying updates, reloading page', err)
}
if (hadRuntimeError) {
console.warn('Had runtime error previously, reloading page')
}
window.location.reload()
return
}
if (typeof onHotUpdateSuccess === 'function') {
// Maybe we want to do something.
onHotUpdateSuccess()
}
if (isUpdateAvailable()) {
// While we were updating, there was a new update! Do it again.
tryApplyUpdates()
}
}
// https://webpack.github.io/docs/hot-module-replacement.html#check
try {
const updatedModules = await module.hot.check(/* autoApply */ {
ignoreUnaccepted: true
})
if (updatedModules) {
handleApplyUpdates(null, updatedModules)
}
} catch (err) {
handleApplyUpdates(err, null)
}
}
// @flow
import * as React from 'react'
import {polyfill} from 'react-lifecycles-compat'
type ComponentDidCatchInfo = {
componentStack: string
}
export type Info = null | ComponentDidCatchInfo
export type RuntimeError = Error & {|
module: ?{|
rawRequest: string
|}
|}
export type ErrorReporterProps = {|error: RuntimeError, info: Info|}
type ErrorReporterComponent = React.ComponentType<ErrorReporterProps>
type Props = {|
ErrorReporter: null | ErrorReporterComponent,
onError: (error: RuntimeError, info: ComponentDidCatchInfo) => void,
onError: (error: Error, info: ComponentDidCatchInfo) => void,
children: React.ComponentType<*>
|}
type State = {|
error: null | RuntimeError,
info: Info
|}
class ErrorBoundary extends React.Component<Props, State> {
state = {
error: null,
info: null
}
static getDerivedStateFromProps () {
return {
error: null,
info: null
}
}
componentDidCatch (error: RuntimeError, info: ComponentDidCatchInfo) {
class ErrorBoundary extends React.Component<Props> {
componentDidCatch (error: Error, info: ComponentDidCatchInfo) {
const {onError} = this.props
// onError is provided in production
if (onError) {
onError(error, info)
} else {
this.setState({ error, info })
}
// onError is required
onError(error, info)
}
render () {
const {ErrorReporter, children} = this.props
const {error, info} = this.state
if (ErrorReporter && error) {
return <ErrorReporter error={error} info={info} />
}
const {children} = this.props
return React.Children.only(children)
}
}
// Makes sure we can use React 16.3 lifecycles and still support older versions of React.
polyfill(ErrorBoundary)
export default ErrorBoundary
......@@ -8,12 +8,13 @@ import PageLoader from '../lib/page-loader'
import * as asset from '../lib/asset'
import * as envConfig from '../lib/runtime-config'
import ErrorBoundary from './error-boundary'
import Loadable from '../lib/loadable'
// Polyfill Promise globally
// This is needed because Webpack2's dynamic loading(common chunks) code
// This is needed because Webpack's dynamic loading(common chunks) code
// depends on Promise.
// So, we need to polyfill it.
// See: https://github.com/webpack/webpack/issues/4254
// See: https://webpack.js.org/guides/code-splitting/#dynamic-imports
if (!window.Promise) {
window.Promise = Promise
}
......@@ -26,18 +27,19 @@ const {
pathname,
query,
buildId,
chunks,
assetPrefix,
runtimeConfig
},
location
} = window
const prefix = assetPrefix || ''
// With dynamic assetPrefix it's no longer possible to set assetPrefix at the build time
// So, this is how we do it in the client side at runtime
__webpack_public_path__ = `${assetPrefix}/_next/webpack/` //eslint-disable-line
__webpack_public_path__ = `${prefix}/_next/` //eslint-disable-line
// Initialize next/asset with the assetPrefix
asset.setAssetPrefix(assetPrefix)
asset.setAssetPrefix(prefix)
// Initialize next/config with the environment configuration
envConfig.setConfig({
serverRuntimeConfig: {},
......@@ -46,48 +48,32 @@ envConfig.setConfig({
const asPath = getURL()
const pageLoader = new PageLoader(buildId, assetPrefix)
window.__NEXT_LOADED_PAGES__.forEach(({ route, fn }) => {
pageLoader.registerPage(route, fn)
const pageLoader = new PageLoader(buildId, prefix)
window.__NEXT_LOADED_PAGES__.forEach(([r, f]) => {
pageLoader.registerPage(r, f)
})
delete window.__NEXT_LOADED_PAGES__
window.__NEXT_LOADED_CHUNKS__.forEach(({ chunkName, fn }) => {
pageLoader.registerChunk(chunkName, fn)
})
delete window.__NEXT_LOADED_CHUNKS__
window.__NEXT_REGISTER_PAGE = pageLoader.registerPage.bind(pageLoader)
window.__NEXT_REGISTER_CHUNK = pageLoader.registerChunk.bind(pageLoader)
const headManager = new HeadManager()
const appContainer = document.getElementById('__next')
const errorContainer = document.getElementById('__next-error')
let lastAppProps
let webpackHMR
export let router
export let ErrorComponent
let DevErrorOverlay
let Component
let App
let stripAnsi = (s) => s
let applySourcemaps = (e) => e
export const emitter = new EventEmitter()
export default async ({
DevErrorOverlay: passedDevErrorOverlay,
stripAnsi: passedStripAnsi,
applySourcemaps: passedApplySourcemaps
webpackHMR: passedWebpackHMR
} = {}) => {
// Wait for all the dynamic chunks to get loaded
for (const chunkName of chunks) {
await pageLoader.waitForChunk(chunkName)
// This makes sure this specific line is removed in production
if (process.env.NODE_ENV === 'development') {
webpackHMR = passedWebpackHMR
}
stripAnsi = passedStripAnsi || stripAnsi
applySourcemaps = passedApplySourcemaps || applySourcemaps
DevErrorOverlay = passedDevErrorOverlay
ErrorComponent = await pageLoader.loadPage('/_error')
App = await pageLoader.loadPage('/_app')
......@@ -104,6 +90,8 @@ export default async ({
initialErr = error
}
await Loadable.preloadReady()
router = createRouter(pathname, query, asPath, {
initialProps: props,
pageLoader,
......@@ -132,7 +120,6 @@ export async function render (props) {
try {
await doRender(props)
} catch (err) {
if (err.abort) return
await renderError({...props, err})
}
}
......@@ -141,29 +128,34 @@ export async function render (props) {
// 404 and 500 errors are special kind of errors
// and they are still handle via the main render method.
export async function renderError (props) {
const {err, errorInfo} = props
const {App, err} = props
// In development we apply sourcemaps to the error
if (process.env.NODE_ENV !== 'production') {
await applySourcemaps(err)
throw webpackHMR.prepareError(err)
}
const str = stripAnsi(`${err.message}\n${err.stack}${errorInfo ? `\n\n${errorInfo.componentStack}` : ''}`)
console.error(str)
if (process.env.NODE_ENV !== 'production') {
// We need to unmount the current app component because it's
// in the inconsistant state.
// Otherwise, we need to face issues when the issue is fixed and
// it's get notified via HMR
ReactDOM.unmountComponentAtNode(appContainer)
renderReactElement(<DevErrorOverlay error={err} />, errorContainer)
return
}
// Make sure we log the error to the console, otherwise users can't track down issues.
console.error(err)
// In production we do a normal render with the `ErrorComponent` as component.
// `App` will handle the calling of `getInitialProps`, which will include the `err` on the context
await doRender({...props, err, Component: ErrorComponent})
// If we've gotten here upon initial render, we can use the props from the server.
// Otherwise, we need to call `getInitialProps` on `App` before mounting.
const initProps = props.props
? props.props
: await loadGetInitialProps(App, {Component: ErrorComponent, router, ctx: {err, pathname, query, asPath}})
await doRender({...props, err, Component: ErrorComponent, props: initProps})
}
let isInitialRender = true
function renderReactElement (reactEl, domEl) {
// The check for `.hydrate` is there to support React alternatives like preact
if (isInitialRender && typeof ReactDOM.hydrate === 'function') {
ReactDOM.hydrate(reactEl, domEl)
isInitialRender = false
} else {
ReactDOM.render(reactEl, domEl)
}
}
async function doRender ({ App, Component, props, hash, err, emitter: emitterProp = emitter }) {
......@@ -185,38 +177,26 @@ async function doRender ({ App, Component, props, hash, err, emitter: emitterPro
emitterProp.emit('before-reactdom-render', { Component, ErrorComponent, appProps })
// We need to clear any existing runtime error messages
ReactDOM.unmountComponentAtNode(errorContainer)
let onError = null
if (process.env.NODE_ENV !== 'development') {
onError = async (error, errorInfo) => {
// In development runtime errors are caught by react-error-overlay.
if (process.env.NODE_ENV === 'development') {
renderReactElement((
<App {...appProps} />
), appContainer)
} else {
// In production we catch runtime errors using componentDidCatch which will trigger renderError.
const onError = async (error) => {
try {
await renderError({App, err: error, errorInfo})
await renderError({App, err: error})
} catch (err) {
console.error('Error while rendering error page: ', err)
}
}
renderReactElement((
<ErrorBoundary onError={onError}>
<App {...appProps} />
</ErrorBoundary>
), appContainer)
}
// In development we render a wrapper component that catches runtime errors.
renderReactElement((
<ErrorBoundary ErrorReporter={DevErrorOverlay} onError={onError}>
<App {...appProps} />
</ErrorBoundary>
), appContainer)
emitterProp.emit('after-reactdom-render', { Component, ErrorComponent, appProps })
}
let isInitialRender = true
function renderReactElement (reactEl, domEl) {
// The check for `.hydrate` is there to support React alternatives like preact
if (isInitialRender && typeof ReactDOM.hydrate === 'function') {
ReactDOM.hydrate(reactEl, domEl)
isInitialRender = false
} else {
ReactDOM.render(reactEl, domEl)
}
}
import stripAnsi from 'strip-ansi'
import initNext, * as next from './'
import DevErrorOverlay from './dev-error-overlay'
import initOnDemandEntries from './on-demand-entries-client'
import initWebpackHMR from './webpack-hot-middleware-client'
import {applySourcemaps} from './source-map-support'
window.next = next
// Temporary workaround for the issue described here:
// https://github.com/zeit/next.js/issues/3775#issuecomment-407438123
// The runtimeChunk doesn't have dynamic import handling code when there hasn't been a dynamic import
// The runtimeChunk can't hot reload itself currently to correct it when adding pages using on-demand-entries
import('./noop')
const {
__NEXT_DATA__: {
assetPrefix
}
} = window
const prefix = assetPrefix || ''
const webpackHMR = initWebpackHMR({assetPrefix: prefix})
initNext({ DevErrorOverlay, applySourcemaps, stripAnsi })
window.next = next
initNext({ webpackHMR })
.then((emitter) => {
initOnDemandEntries()
initWebpackHMR()
initOnDemandEntries({assetPrefix: prefix})
let lastScroll
......@@ -33,7 +43,6 @@ initNext({ DevErrorOverlay, applySourcemaps, stripAnsi })
lastScroll = null
}
})
})
.catch((err) => {
console.error(stripAnsi(`${err.message}\n${err.stack}`))
}).catch((err) => {
console.error('Error was not caught', err)
})
......@@ -3,29 +3,23 @@
import Router from '../lib/router'
import fetch from 'unfetch'
const {
__NEXT_DATA__: {
assetPrefix
}
} = window
export default () => {
export default ({assetPrefix}) => {
Router.ready(() => {
Router.router.events.on('routeChangeComplete', ping)
Router.events.on('routeChangeComplete', ping)
})
async function ping () {
try {
const url = `${assetPrefix}/_next/on-demand-entries-ping?page=${Router.pathname}`
const url = `${assetPrefix || ''}/_next/on-demand-entries-ping?page=${Router.pathname}`
const res = await fetch(url, {
credentials: 'omit'
credentials: 'same-origin'
})
const payload = await res.json()
if (payload.invalid) {
// Payload can be invalid even if the page is not exists.
// So, we need to make sure it's exists before reloading.
const pageRes = await fetch(location.href, {
credentials: 'omit'
credentials: 'same-origin'
})
if (pageRes.status === 200) {
location.reload()
......
// @flow
import fetch from 'unfetch'
const filenameRE = /\(([^)]+\.js):(\d+):(\d+)\)$/
export async function applySourcemaps (e: any): Promise<void> {
if (!e || typeof e.stack !== 'string' || e.sourceMapsApplied) {
export function rewriteStacktrace (e: any, distDir: string): void {
if (!e || typeof e.stack !== 'string') {
return
}
const lines = e.stack.split('\n')
const result = await Promise.all(lines.map((line) => {
return rewriteTraceLine(line)
}))
const result = lines.map((line) => {
return rewriteTraceLine(line, distDir)
})
e.stack = result.join('\n')
// This is to make sure we don't apply the sourcemaps twice on the same object
e.sourceMapsApplied = true
}
async function rewriteTraceLine (trace: string): Promise<string> {
function rewriteTraceLine (trace: string, distDir: string): string {
const m = trace.match(filenameRE)
if (m == null) {
return trace
}
const filePath = m[1]
if (filePath.match(/node_modules/)) {
return trace
}
const mapPath = `${filePath}.map`
const res = await fetch(mapPath)
if (res.status !== 200) {
return trace
}
const mapContents = await res.json()
const {SourceMapConsumer} = require('source-map')
const map = new SourceMapConsumer(mapContents)
const originalPosition = map.originalPositionFor({
line: Number(m[2]),
column: Number(m[3])
})
if (originalPosition.source != null) {
const { source, line, column } = originalPosition
const mappedPosition = `(${source.replace(/^webpack:\/\/\//, '')}:${String(line)}:${String(column)})`
return trace.replace(filenameRE, mappedPosition)
}
const filename = m[1]
const filenameLink = filename.replace(distDir, '/_next/development').replace(/\\/g, '/')
trace = trace.replace(filename, filenameLink)
return trace
}
import 'event-source-polyfill'
import webpackHotMiddlewareClient from 'webpack-hot-middleware/client?autoConnect=false&overlay=false&reload=true'
import connect from './dev-error-overlay/hot-dev-client'
import Router from '../lib/router'
const {
__NEXT_DATA__: {
assetPrefix
}
} = window
export default () => {
webpackHotMiddlewareClient.setOptionsAndConnect({
path: `${assetPrefix}/_next/webpack-hmr`
})
const handlers = {
reload (route) {
// If the App component changes we have to reload the current route, this is handled by hot-self-accept-loader
// So we just return
if (route === '/_app') {
return
}
const handlers = {
reload (route) {
if (route === '/_error') {
for (const r of Object.keys(Router.components)) {
const { err } = Router.components[r]
if (err) {
// reload all error routes
// which are expected to be errors of '/_error' routes
Router.reload(r)
}
if (route === '/_error') {
for (const r of Object.keys(Router.components)) {
const { err } = Router.components[r]
if (err) {
// reload all error routes
// which are expected to be errors of '/_error' routes
Router.reload(r)
}
return
}
// If the App component changes we have to reload the current route
if (route === '/_app') {
Router.reload(Router.route)
return
}
// Since _document is server only we need to reload the full page when it changes.
if (route === '/_document') {
window.location.reload()
return
}
return
}
Router.reload(route)
},
// Since _document is server only we need to reload the full page when it changes.
if (route === '/_document') {
window.location.reload()
return
}
change (route) {
// If the App component changes we have to reload the current route
if (route === '/_app') {
Router.reload(Router.route)
return
}
Router.reload(route)
},
// Since _document is server only we need to reload the full page when it changes.
if (route === '/_document') {
window.location.reload()
return
}
change (route) {
// If the App component changes we have to reload the current route, this is handled by hot-self-accept-loader
// So we just return
if (route === '/_app') {
return
}
const { err, Component } = Router.components[route] || {}
const { err, Component } = Router.components[route] || {}
if (err) {
// reload to recover from runtime errors
Router.reload(route)
}
if (err) {
// reload to recover from runtime errors
Router.reload(route)
}
if (Router.route !== route) {
// If this is a not a change for a currently viewing page.
// We don't need to worry about it.
return
}
if (Router.route !== route) {
// If this is a not a change for a currently viewing page.
// We don't need to worry about it.
return
}
if (!Component) {
// This only happens when we create a new page without a default export.
// If you removed a default export from a exising viewing page, this has no effect.
console.log(`Hard reloading due to no default component in page: ${route}`)
window.location.reload()
}
if (!Component) {
// This only happens when we create a new page without a default export.
// If you removed a default export from a exising viewing page, this has no effect.
console.warn(`Hard reloading due to no default component in page: ${route}`)
window.location.reload()
}
}
}
export default ({assetPrefix}) => {
const options = {
path: `${assetPrefix}/_next/webpack-hmr`
}
const devClient = connect(options)
webpackHotMiddlewareClient.subscribe((obj) => {
devClient.subscribeToHmrEvent((obj) => {
const fn = handlers[obj.action]
if (fn) {
const data = obj.data || []
......@@ -86,4 +76,6 @@ export default () => {
throw new Error('Unexpected action ' + obj.action)
}
})
return devClient
}
# getInitialProps was defined as an instance method
#### Why This Error Occurred
`getInitialProps` must be a static method in order to be called by next.js.
#### Possible Ways to Fix It
Use the static keyword.
```js
export default class YourEntryComponent extends React.Component {
static getInitialProps () {
return {}
}
render () {
return 'foo'
}
}
```
or
```js
const YourEntryComponent = function () {
return 'foo'
}
YourEntryComponent.getInitialProps = () => {
return {}
}
export default YourEntryComponent
```
### Useful Links
- [Fetching data and component lifecycle](https://github.com/zeit/next.js#fetching-data-and-component-lifecycle)
# `popstate` called with empty state
#### Why This Error Occurred
When using the browser back button the popstate event is triggered. Next.js sets
`popstate` event triggered but `event.state` did not have `url` or `as`, causing a route change failure
#### Possible Ways to Fix It
The only known cause of this issue is manually manipulating `window.history` instead of using `next/router`
### Useful Links
- [The issue this was reported in: #4994](https://github.com/zeit/next.js/issues/4994)
......@@ -6,7 +6,7 @@ In versions prior to 6.x the `url` property got magically injected into every `P
The reason this is going away is that we want to make things very predictable and explicit. Having a magical url property coming out of nowhere doesn't aid that goal.
*Note:* In some cases using React Dev Tools may trigger this warning even if you do not reference `url` anywhere in your code. Try temporarily disabling the extension and see if the warning persists.
> ⚠️ In some cases using React Dev Tools may trigger this warning even if you do not reference `url` anywhere in your code. Try temporarily disabling the extension and see if the warning persists.
#### Possible Ways to Fix It
......
......@@ -16,7 +16,7 @@ yarn create next-app --example active-class-name active-class-name-app
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/active-class-name
......
......@@ -16,7 +16,7 @@ yarn create next-app --example basic-css basic-css-app
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/basic-css
......
......@@ -16,7 +16,7 @@ yarn create next-app --example basic-export basic-export-app
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/basic-export
......
......@@ -16,7 +16,7 @@ yarn create next-app --example custom-charset custom-charset-app
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/custom-charset
......
......@@ -19,7 +19,7 @@ yarn create next-app --example custom-server-actionhero custom-server-actionhero
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/custom-server-actionhero
......
......@@ -16,7 +16,7 @@ yarn create next-app --example custom-server-express custom-server-express-app
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/custom-server-express
......
......@@ -16,7 +16,7 @@ yarn create next-app --example custom-server-fastify custom-server-fastify-app
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/custom-server-fastify
......
......@@ -7,7 +7,7 @@
"start": "NODE_ENV=production node server.js"
},
"dependencies": {
"fastify": "^0.29.2",
"fastify": "1.8.0",
"next": "latest",
"react": "^16.0.0",
"react-dom": "^16.0.0"
......
const fastify = require('fastify')
const fastify = require('fastify')({ logger: { level: 'error' } })
const Next = require('next')
const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = Next({ dev })
const handle = app.getRequestHandler()
app.prepare()
.then(() => {
const server = fastify()
fastify.register((fastify, opts, next) => {
const app = Next({ dev })
app.prepare()
.then(() => {
if (dev) {
fastify.get('/_next/*', (req, reply) => {
return app.handleRequest(req.req, reply.res)
.then(() => {
reply.sent = true
})
})
}
server.get('/a', (req, res) => {
return app.render(req.req, res.res, '/a', req.query)
})
fastify.get('/a', (req, reply) => {
return app.render(req.req, reply.res, '/b', req.query)
.then(() => {
reply.sent = true
})
})
server.get('/b', (req, res) => {
return app.render(req.req, res.res, '/b', req.query)
})
fastify.get('/b', (req, reply) => {
return app.render(req.req, reply.res, '/a', req.query)
.then(() => {
reply.sent = true
})
})
server.get('/*', (req, res) => {
return handle(req.req, res.res)
})
fastify.get('/*', (req, reply) => {
return app.handleRequest(req.req, reply.res)
.then(() => {
reply.sent = true
})
})
server.listen(port, (err) => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
fastify.setNotFoundHandler((request, reply) => {
return app.render404(request.req, reply.res)
.then(() => {
reply.sent = true
})
})
next()
})
})
.catch((err) => next(err))
})
fastify.listen(port, (err) => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
})
......@@ -16,7 +16,7 @@ yarn create next-app --example custom-server-hapi custom-server-hapi-app
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/custom-server-hapi
......
......@@ -16,7 +16,7 @@ yarn create next-app --example custom-server-koa custom-server-koa-app
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/custom-server-koa
......
......@@ -16,7 +16,7 @@ yarn create next-app --example custom-server-micro custom-server-micro-app
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/custom-server-micro
......
......@@ -16,7 +16,7 @@ yarn create next-app --example custom-server-nodemon custom-server-nodemon-app
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/custom-server-nodemon
......
......@@ -16,7 +16,7 @@ yarn create next-app --example custom-server-polka custom-server-polka-app
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/custom-server-polka
......
......@@ -16,7 +16,7 @@ yarn create next-app --example custom-server-typescript custom-server-typescript
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/custom-server-typescript
......
{
"watch": ["server/**/*.ts"],
"execMap": {
"ts": "ts-node --compilerOptions '{\"module\":\"commonjs\"}'"
"ts": "ts-node --typeCheck --compilerOptions '{\"module\":\"commonjs\"}'"
}
}
......@@ -5,8 +5,8 @@
"start": "NODE_ENV=production node .next/production-server/index.js"
},
"dependencies": {
"@babel/core": "^7.0.0-beta.48",
"@zeit/next-typescript": "1.0.1",
"@babel/core": "^7.0.0-rc.1",
"@zeit/next-typescript": "1.1.0",
"babel-loader": "^7.1.4",
"next": "latest",
"react": "^16.4.0",
......
......@@ -16,7 +16,7 @@ yarn create next-app --example custom-server custom-server-app
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/custom-server
......
......@@ -16,7 +16,7 @@ yarn create next-app --example data-fetch data-fetch-app
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/data-fetch
......
......@@ -16,7 +16,7 @@ yarn create next-app --example form-handler form-handler-app
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/form-handler
......
......@@ -14,7 +14,7 @@ yarn create next-app --example gh-pages gh-pages-app
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/gh-pages
......
......@@ -16,7 +16,7 @@ yarn create next-app --example head-elements head-elements-app
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/head-elements
......
......@@ -16,7 +16,7 @@ yarn create next-app --example hello-world hello-world-app
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/hello-world
......@@ -41,4 +41,4 @@ now
## The idea behind the example
This example shows the most basic idea behind Next. We have 2 pages: `pages/index.js` and `pages/about.js`. The former responds to `/` requests and the latter to `/about`. Using `next/link` you can add hyperlinks between them with universal routing capabilities.
This example shows the most basic idea behind Next. We have 2 pages: `pages/index.js` and `pages/about.js`. The former responds to `/` requests and the latter to `/about`. Using `next/link` you can add hyperlinks between them with universal routing capabilities. The `day` directory shows that you can have subdirectories.
......@@ -16,7 +16,7 @@ yarn create next-app --example layout-component layout-component-app
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/layout-component
......
......@@ -16,7 +16,7 @@ yarn create next-app --example nested-components nested-components-app
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/nested-components
......
......@@ -16,7 +16,7 @@ yarn create next-app --example only-client-render-external-dependencies only-cli
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/only-client-render-external-dependencies
......
import dynamic from 'next/dynamic'
export default dynamic({
modules: () => ({
BarChart: import('recharts').then(({ BarChart }) => BarChart),
Bar: import('recharts').then(({ Bar }) => Bar)
}),
render: (props, { BarChart, Bar }) =>
<BarChart width={props.width} height={props.height} data={props.data}>
<Bar dataKey='uv' fill='#8884d8' />
</BarChart>
})
import dynamic from 'next/dynamic'
export default dynamic({
modules: () => ({
LineChart: import('recharts').then(({ LineChart }) => LineChart),
Line: import('recharts').then(({ Line }) => Line)
}),
render: (props, { LineChart, Line }) =>
<LineChart width={props.width} height={props.height} data={props.data}>
<Line type='monotone' dataKey='uv' stroke='#8884d8' />
</LineChart>
})
......@@ -10,7 +10,7 @@
"next": "latest",
"react": "^16.0.0",
"react-dom": "^16.0.0",
"recharts": "^1.0.0-beta.0"
"recharts": "^1.1.0"
},
"license": "ISC"
}
import React from 'react'
let LineChart
let Line
class Chart extends React.Component {
constructor () {
super()
this.state = {
chart: false,
data: [
{name: 'Page A', uv: 4000, pv: 2400, amt: 2400},
{name: 'Page B', uv: 3000, pv: 1398, amt: 2210},
{name: 'Page C', uv: 2000, pv: 9800, amt: 2290},
{name: 'Page D', uv: 2780, pv: 3908, amt: 2000},
{name: 'Page E', uv: 1890, pv: 4800, amt: 2181},
{name: 'Page F', uv: 2390, pv: 3800, amt: 2500},
{name: 'Page G', uv: 3490, pv: 4300, amt: 2100}
]
}
}
import BarChart from '../components/BarChart'
componentDidMount () {
LineChart = require('recharts').LineChart
Line = require('recharts').Line
const data = [
{name: 'Page A', uv: 4000, pv: 2400, amt: 2400},
{name: 'Page B', uv: 3000, pv: 1398, amt: 2210},
{name: 'Page C', uv: 2000, pv: 9800, amt: 2290},
{name: 'Page D', uv: 2780, pv: 3908, amt: 2000},
{name: 'Page E', uv: 1890, pv: 4800, amt: 2181},
{name: 'Page F', uv: 2390, pv: 3800, amt: 2500},
{name: 'Page G', uv: 3490, pv: 4300, amt: 2100}
]
this.setState({
chart: true
})
}
render () {
return (
<div>
<h1>Another chart</h1>
{this.state.chart &&
<LineChart width={400} height={400} data={this.state.data}>
<Line type='monotone' dataKey='uv' stroke='#8884d8' />
</LineChart>
}
</div>
)
}
}
const Chart = () => (
<div>
<h1>Another chart</h1>
<BarChart width={400} height={400} data={data} />
</div>
)
export default Chart
import React from 'react'
import Link from 'next/link'
let LineChart
let Line
import LineChart from '../components/LineChart'
class Index extends React.Component {
constructor () {
super()
this.state = {
chart: false,
data: [
{name: 'Page A', uv: 1000, pv: 2400, amt: 2400},
{name: 'Page B', uv: 3000, pv: 1398, amt: 2210},
{name: 'Page C', uv: 2000, pv: 9800, amt: 2290},
{name: 'Page D', uv: 2780, pv: 3908, amt: 2000},
{name: 'Page E', uv: 1890, pv: 4800, amt: 2181},
{name: 'Page F', uv: 2390, pv: 3800, amt: 2500},
{name: 'Page G', uv: 3490, pv: 4300, amt: 2100}
]
}
}
const data = [
{name: 'Page A', uv: 1000, pv: 2400, amt: 2400},
{name: 'Page B', uv: 3000, pv: 1398, amt: 2210},
{name: 'Page C', uv: 2000, pv: 9800, amt: 2290},
{name: 'Page D', uv: 2780, pv: 3908, amt: 2000},
{name: 'Page E', uv: 1890, pv: 4800, amt: 2181},
{name: 'Page F', uv: 2390, pv: 3800, amt: 2500},
{name: 'Page G', uv: 3490, pv: 4300, amt: 2100}
]
componentDidMount () {
LineChart = require('recharts').LineChart
Line = require('recharts').Line
this.setState({
chart: true
})
}
render () {
return (
<div>
<h1>Chart</h1>
<Link href='/chart'><a>Go to another chart</a></Link>
{this.state.chart &&
<LineChart width={400} height={400} data={this.state.data}>
<Line type='monotone' dataKey='uv' stroke='#8884d8' />
</LineChart>
}
</div>
)
}
}
const Index = () => (
<div>
<h1>Chart</h1>
<Link href='/chart'>
<a>Go to another chart</a>
</Link>
<LineChart width={400} height={400} data={data} />
</div>
)
export default Index
......@@ -16,7 +16,7 @@ yarn create next-app --example parameterized-routing parameterized-routing-app
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/parameterized-routing
......
......@@ -16,7 +16,7 @@ yarn create next-app --example pass-server-data pass-server-data-app
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/pass-server-data
......
......@@ -15,7 +15,7 @@ yarn create next-app --example progressive-render progressive-render-app
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/progressive-render
......
......@@ -16,7 +16,7 @@ yarn create next-app --example root-static-files root-static-files-app
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/custom-server
......
......@@ -15,7 +15,7 @@ yarn create next-app --example shared-modules shared-modules-app
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/shared-modules
......
......@@ -16,7 +16,7 @@ yarn create next-app --example ssr-caching ssr-caching-app
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/ssr-caching
......
......@@ -16,7 +16,7 @@ yarn create next-app --example svg-components svg-components-app
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/svg-components
......
......@@ -16,7 +16,7 @@ yarn create next-app --example using-inferno using-inferno-app
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/using-inferno
......
......@@ -16,7 +16,7 @@ yarn create next-app --example using-nerv using-nerv-app
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/using-nerv
......
......@@ -16,7 +16,7 @@ yarn create next-app --example using-preact using-preact-app
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/using-preact
......
......@@ -15,7 +15,7 @@ yarn create next-app --example using-router using-router-app
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/using-router
......
......@@ -15,7 +15,7 @@ yarn create next-app --example using-with-router using-with-router-app
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/using-with-router
......
......@@ -14,7 +14,7 @@ yarn create next-app --example with-absolute-imports with-absolute-imports-app
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-absolute-imports
......
......@@ -16,7 +16,7 @@ yarn create next-app --example with-algolia-react-instantsearch with-algolia-rea
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-algolia-react-instantsearch
......
......@@ -16,7 +16,7 @@ yarn create next-app --example with-amp with-amp-app
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js.git):
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-amp
......
......@@ -6,7 +6,7 @@
"import",
{
"libraryName": "antd",
"style": "less"
"style": true
}
]
]
......
......@@ -16,7 +16,7 @@ yarn create next-app --example with-ant-design-less with-ant-design-app
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-ant-design-less
......
/* eslint-disable */
const withLess = require('@zeit/next-less')
// fix: prevents error when .less files are required by node
if (typeof require !== 'undefined') {
require.extensions['.less'] = (file) => {}
}
module.exports = withLess({
lessLoaderOptions: {
javascriptEnabled: true,
......
......@@ -16,7 +16,7 @@ yarn create next-app --example with-ant-design with-ant-design-app
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-ant-design
......
import Head from 'next/head'
export default ({ children }) =>
<div>
<Head>
<meta name='viewport' content='width=device-width, initial-scale=1' />
<meta charSet='utf-8' />
<link rel='stylesheet' href='/_next/static/style.css' />
</Head>
<style jsx global>{`
body {
}
`}</style>
{children}
</div>
/*
In production the stylesheet is compiled to .next/static/style.css and served from /_next/static/style.css
You have to include it into the page using either next/head or a custom _document.js, as is being done in this file.
*/
import Document, { Head, Main, NextScript } from 'next/document'
export default class MyDocument extends Document {
......@@ -11,6 +5,8 @@ export default class MyDocument extends Document {
return (
<html>
<Head>
<meta name='viewport' content='width=device-width, initial-scale=1' />
<meta charSet='utf-8' />
<link rel='stylesheet' href='/_next/static/style.css' />
</Head>
<body>
......
import Layout from '../index.js'
import { Form, Select, InputNumber, DatePicker, Switch, Slider, Button } from 'antd'
const FormItem = Form.Item
const Option = Select.Option
export default () => (
<Layout>
<div style={{ marginTop: 100 }}>
<Form layout='horizontal'>
<FormItem
label='Input Number'
labelCol={{ span: 8 }}
wrapperCol={{ span: 8 }}
>
<InputNumber size='large' min={1} max={10} style={{ width: 100 }} defaultValue={3} name='inputNumber' />
<a href='#'>Link</a>
</FormItem>
<div style={{ marginTop: 100 }}>
<Form layout='horizontal'>
<FormItem
label='Input Number'
labelCol={{ span: 8 }}
wrapperCol={{ span: 8 }}
>
<InputNumber size='large' min={1} max={10} style={{ width: 100 }} defaultValue={3} name='inputNumber' />
<a href='#'>Link</a>
</FormItem>
<FormItem
label='Switch'
labelCol={{ span: 8 }}
wrapperCol={{ span: 8 }}
>
<Switch defaultChecked name='switch' />
</FormItem>
<FormItem
label='Switch'
labelCol={{ span: 8 }}
wrapperCol={{ span: 8 }}
>
<Switch defaultChecked name='switch' />
</FormItem>
<FormItem
label='Slider'
labelCol={{ span: 8 }}
wrapperCol={{ span: 8 }}
>
<Slider defaultValue={70} />
</FormItem>
<FormItem
label='Slider'
labelCol={{ span: 8 }}
wrapperCol={{ span: 8 }}
>
<Slider defaultValue={70} />
</FormItem>
<FormItem
label='Select'
labelCol={{ span: 8 }}
wrapperCol={{ span: 8 }}
>
<Select size='large' defaultValue='lucy' style={{ width: 192 }} name='select'>
<Option value='jack'>jack</Option>
<Option value='lucy'>lucy</Option>
<Option value='disabled' disabled>disabled</Option>
<Option value='yiminghe'>yiminghe</Option>
</Select>
</FormItem>
<FormItem
label='Select'
labelCol={{ span: 8 }}
wrapperCol={{ span: 8 }}
>
<Select size='large' defaultValue='lucy' style={{ width: 192 }} name='select'>
<Option value='jack'>jack</Option>
<Option value='lucy'>lucy</Option>
<Option value='disabled' disabled>disabled</Option>
<Option value='yiminghe'>yiminghe</Option>
</Select>
</FormItem>
<FormItem
label='DatePicker'
labelCol={{ span: 8 }}
wrapperCol={{ span: 8 }}
>
<DatePicker name='startDate' />
</FormItem>
<FormItem
style={{ marginTop: 48 }}
wrapperCol={{ span: 8, offset: 8 }}
>
<Button size='large' type='primary' htmlType='submit'>
OK
</Button>
<Button size='large' style={{ marginLeft: 8 }}>
Cancel
</Button>
</FormItem>
</Form>
</div>
</Layout>
<FormItem
label='DatePicker'
labelCol={{ span: 8 }}
wrapperCol={{ span: 8 }}
>
<DatePicker name='startDate' />
</FormItem>
<FormItem
style={{ marginTop: 48 }}
wrapperCol={{ span: 8, offset: 8 }}
>
<Button size='large' type='primary' htmlType='submit'>
OK
</Button>
<Button size='large' style={{ marginLeft: 8 }}>
Cancel
</Button>
</FormItem>
</Form>
</div>
)
......@@ -15,7 +15,7 @@ yarn create next-app --example with-antd-mobile with-antd-mobile-app
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-antd-mobile
......
......@@ -16,7 +16,7 @@ yarn create next-app --example with-aphrodite with-aphrodite-app
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-aphrodite
......
......@@ -15,7 +15,7 @@ yarn create next-app --example with-apollo-and-redux-saga with-apollo-and-redux-
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-apollo-and-redux-saga
......
......@@ -3,7 +3,7 @@ export const actionTypes = {
TICK_CLOCK: 'TICK_CLOCK'
}
export function startClock(isServer=true) {
export function startClock (isServer = true) {
return {
type: actionTypes.START_CLOCK,
light: isServer,
......@@ -11,7 +11,7 @@ export function startClock(isServer=true) {
}
}
export function tickClock(isServer) {
export function tickClock (isServer) {
return {
type: actionTypes.TICK_CLOCK,
light: !isServer,
......
......@@ -5,7 +5,7 @@ export const initialState = {
light: false
}
function reducer(state = initialState, action) {
function reducer (state = initialState, action) {
switch (action.type) {
case actionTypes.TICK_CLOCK:
return {
......
......@@ -7,7 +7,7 @@ import { actionTypes, tickClock } from './actions'
es6promise.polyfill()
function* runClockSaga() {
function * runClockSaga () {
yield take(actionTypes.START_CLOCK)
while (true) {
yield put(tickClock(false))
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment