Commit 7c80febc authored by Tim Neutkens's avatar Tim Neutkens Committed by JJ Kasper

Initial plugins implementation (#9139)

* Add initial bit for plugins

* Add checks for needed metadata values

* Add test

* Initial plugins changes

* Add handling for _app middleware

* Add loading of _document middleware and
handling of multiple default export syntaxes

* Fix insert order for middleware member expression

* Remove early return from middleware plugin from testing

* Add tests for current plugin middlewares

* Update test plugin package.json

* Update handling for class default export

* Update to use webpack loader instead of babel
plugin, remove redundant middleware naming, and add field for required env for plugins

* Add middleware to support material-ui use case
and example material-ui plugin

* Update tests and remove tests stuff from google analytics plugin

* Remove old plugin suite

* Add init-server middleware

* Exit hard without stack trace when error in collecting plugins

* Add on-error-client and on-error-server and update
to run init-server with next-start in serverless mode

* Update init-client for google analytics plugin

* Add example Sentry plugin and update with-sentry-simple

* Remove middleware field/folder and use src dir for plugins

* Add post-hydration middleware and update
material-ui plugin

* Put plugins code behind flag

* Update chromedriver

* Revert "Update chromedriver"

This reverts commit 1461e978e677f7da05e29e0415ec614a04bf65f9.

* Update lock file

* Remove un-needed _app for sentry example

* Add auto loading of scoped packages, add plugins
config for manually listing plugins, and update
to only collect plugins once

* Update example plugins

* Expose plugins' config

* Rename plugin lifecycles and add babel-preset-build

* Rename other methods with unstable

* Update log when plugin config overrides auto-detecting
parent 68390378
# Material-UI example # Next.js example
Source code is hosted on the [Material-UI](https://github.com/mui-org/material-ui/tree/master/examples/nextjs) repository. ## How to use
Download the example [or clone the repo](https://github.com/mui-org/material-ui):
```sh
curl https://codeload.github.com/mui-org/material-ui/tar.gz/master | tar -xz --strip=2 material-ui-master/examples/nextjs
cd nextjs
```
Install it and run:
```sh
npm install
npm run dev
```
## The idea behind the example
[Next.js](https://github.com/zeit/next.js) is a framework for server-rendered React apps.
{
"name": "nextjs",
"version": "4.0.0",
"private": true,
"dependencies": {
"@material-ui/core": "latest",
"@material-ui/styles": "latest",
"@next/plugin-material-ui": "latest",
"clsx": "latest",
"next": "latest",
"prop-types": "latest",
"react": "latest",
"react-dom": "latest"
},
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
}
}
import React from 'react'
import App from 'next/app'
import Head from 'next/head'
import { ThemeProvider } from '@material-ui/styles'
import CssBaseline from '@material-ui/core/CssBaseline'
import theme from '../src/theme'
export default class MyApp extends App {
render () {
const { Component, pageProps } = this.props
return (
<React.Fragment>
<Head>
<title>My page</title>
</Head>
<ThemeProvider theme={theme}>
{/* CssBaseline kickstart an elegant, consistent, and simple baseline to build upon. */}
<CssBaseline />
<Component {...pageProps} />
</ThemeProvider>
</React.Fragment>
)
}
}
import React from 'react'
import Container from '@material-ui/core/Container'
import Typography from '@material-ui/core/Typography'
import Box from '@material-ui/core/Box'
import MuiLink from '@material-ui/core/Link'
import Button from '@material-ui/core/Button'
import ProTip from '../src/ProTip'
import Link from '../src/Link'
function Copyright () {
return (
<Typography variant='body2' color='textSecondary' align='center'>
{'Copyright © '}
<MuiLink color='inherit' href='https://material-ui.com/'>
Your Website
</MuiLink>{' '}
{new Date().getFullYear()}
{'.'}
</Typography>
)
}
export default function About () {
return (
<Container maxWidth='sm'>
<Box my={4}>
<Typography variant='h4' component='h1' gutterBottom>
Next.js example
</Typography>
<Button
variant='contained'
color='primary'
component={Link}
naked
href='/'
>
Go to the main page
</Button>
<ProTip />
<Copyright />
</Box>
</Container>
)
}
import React from 'react'
import Container from '@material-ui/core/Container'
import Typography from '@material-ui/core/Typography'
import Box from '@material-ui/core/Box'
import MuiLink from '@material-ui/core/Link'
import ProTip from '../src/ProTip'
import Link from '../src/Link'
function Copyright () {
return (
<Typography variant='body2' color='textSecondary' align='center'>
{'Copyright © '}
<MuiLink color='inherit' href='https://material-ui.com/'>
Your Website
</MuiLink>{' '}
{new Date().getFullYear()}
{'.'}
</Typography>
)
}
export default function Index () {
return (
<Container maxWidth='sm'>
<Box my={4}>
<Typography variant='h4' component='h1' gutterBottom>
Next.js example
</Typography>
<Link href='/about' color='secondary'>
Go to the about page
</Link>
<ProTip />
<Copyright />
</Box>
</Container>
)
}
/* eslint-disable jsx-a11y/anchor-has-content */
import React from 'react'
import PropTypes from 'prop-types'
import clsx from 'clsx'
import { useRouter } from 'next/router'
import NextLink from 'next/link'
import MuiLink from '@material-ui/core/Link'
const NextComposed = React.forwardRef(function NextComposed (props, ref) {
const { as, href, prefetch, ...other } = props
return (
<NextLink href={href} prefetch={prefetch} as={as}>
<a ref={ref} {...other} />
</NextLink>
)
})
NextComposed.propTypes = {
as: PropTypes.string,
href: PropTypes.string,
prefetch: PropTypes.bool
}
// A styled version of the Next.js Link component:
// https://nextjs.org/docs/#with-link
function Link (props) {
const {
activeClassName = 'active',
className: classNameProps,
innerRef,
naked,
...other
} = props
const router = useRouter()
const className = clsx(classNameProps, {
[activeClassName]: router.pathname === props.href && activeClassName
})
if (naked) {
return <NextComposed className={className} ref={innerRef} {...other} />
}
return (
<MuiLink
component={NextComposed}
className={className}
ref={innerRef}
{...other}
/>
)
}
Link.propTypes = {
activeClassName: PropTypes.string,
as: PropTypes.string,
className: PropTypes.string,
href: PropTypes.string,
innerRef: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
naked: PropTypes.bool,
onClick: PropTypes.func,
prefetch: PropTypes.bool
}
export default React.forwardRef((props, ref) => (
<Link {...props} innerRef={ref} />
))
import React from 'react'
import { makeStyles } from '@material-ui/core/styles'
import Link from '@material-ui/core/Link'
import SvgIcon from '@material-ui/core/SvgIcon'
import Typography from '@material-ui/core/Typography'
function LightBulbIcon (props) {
return (
<SvgIcon {...props}>
<path d='M9 21c0 .55.45 1 1 1h4c.55 0 1-.45 1-1v-1H9v1zm3-19C8.14 2 5 5.14 5 9c0 2.38 1.19 4.47 3 5.74V17c0 .55.45 1 1 1h6c.55 0 1-.45 1-1v-2.26c1.81-1.27 3-3.36 3-5.74 0-3.86-3.14-7-7-7zm2.85 11.1l-.85.6V16h-4v-2.3l-.85-.6C7.8 12.16 7 10.63 7 9c0-2.76 2.24-5 5-5s5 2.24 5 5c0 1.63-.8 3.16-2.15 4.1z' />
</SvgIcon>
)
}
const useStyles = makeStyles(theme => ({
root: {
margin: theme.spacing(6, 0, 3)
},
lightBulb: {
verticalAlign: 'middle',
marginRight: theme.spacing(1)
}
}))
export default function ProTip () {
const classes = useStyles()
return (
<Typography className={classes.root} color='textSecondary'>
<LightBulbIcon className={classes.lightBulb} />
Pro tip: See more{' '}
<Link href='https://material-ui.com/getting-started/templates/'>
templates
</Link>{' '}
on the Material-UI documentation.
</Typography>
)
}
import { createMuiTheme } from '@material-ui/core/styles'
import { red } from '@material-ui/core/colors'
// Create a theme instance.
const theme = createMuiTheme({
palette: {
primary: {
main: '#556cd6'
},
secondary: {
main: '#19857b'
},
error: {
main: red.A400
},
background: {
default: '#fff'
}
}
})
export default theme
const withSourceMaps = require('@zeit/next-source-maps')() const withSourceMaps = require('@zeit/next-source-maps')()
module.exports = withSourceMaps({ module.exports = withSourceMaps({
webpack: (config, options) => { env: {
// In `pages/_app.js`, Sentry is imported from @sentry/node. While SENTRY_DSN: 'hello-world',
// @sentry/browser will run in a Node.js environment, @sentry/node will use // would want to synchronously grab git commit id here for
// Node.js-only APIs to catch even more unhandled exceptions. // best debugging experience
// SENTRY_RELEASE: '0.0.1'
// This works well when Next.js is SSRing your page on a server with
// Node.js, but it is not what we want when your client-side bundle is being
// executed by a browser.
//
// Luckily, Next.js will call this webpack function twice, once for the
// server and once for the client. Read more:
// https://nextjs.org/docs#customizing-webpack-config
//
// So ask Webpack to replace @sentry/node imports with @sentry/browser when
// building the browser's bundle
if (!options.isServer) {
config.resolve.alias['@sentry/node'] = '@sentry/browser'
}
return config
} }
}) })
...@@ -8,8 +8,7 @@ ...@@ -8,8 +8,7 @@
"start": "next start" "start": "next start"
}, },
"dependencies": { "dependencies": {
"@sentry/browser": "^5.1.0", "@next/plugin-sentry": "latest",
"@sentry/node": "^5.6.2",
"next": "latest", "next": "latest",
"react": "^16.8.6", "react": "^16.8.6",
"react-dom": "^16.8.6" "react-dom": "^16.8.6"
......
import React from 'react'
import App from 'next/app'
import * as Sentry from '@sentry/node'
Sentry.init({
// Replace with your project's Sentry DSN
dsn: 'https://00000000000000000000000000000000@sentry.io/1111111'
})
class MyApp extends App {
render () {
const { Component, pageProps } = this.props
// Workaround for https://github.com/zeit/next.js/issues/8592
const { err } = this.props
const modifiedPageProps = { ...pageProps, err }
return <Component {...modifiedPageProps} />
}
}
export default MyApp
import React from 'react'
import Error from 'next/error'
import * as Sentry from '@sentry/node'
const MyError = ({ statusCode, hasGetInitialPropsRun, err }) => {
if (!hasGetInitialPropsRun && err) {
// getInitialProps is not called in case of
// https://github.com/zeit/next.js/issues/8592. As a workaround, we pass
// err via _app.js so it can be captured
Sentry.captureException(err)
}
return <Error statusCode={statusCode} />
}
MyError.getInitialProps = async ({ res, err, asPath }) => {
const errorInitialProps = await Error.getInitialProps({ res, err })
// Workaround for https://github.com/zeit/next.js/issues/8592, mark when
// getInitialProps has run
errorInitialProps.hasGetInitialPropsRun = true
if (res) {
// Running on the server, the response object is available.
//
// Next.js will pass an err on the server if a page's `getInitialProps`
// threw or returned a Promise that rejected
if (res.statusCode === 404) {
// Opinionated: do not record an exception in Sentry for 404
return { statusCode: 404 }
}
if (err) {
Sentry.captureException(err)
return errorInitialProps
}
} else {
// Running on the client (browser).
//
// Next.js will provide an err if:
//
// - a page's `getInitialProps` threw or returned a Promise that rejected
// - an exception was thrown somewhere in the React lifecycle (render,
// componentDidMount, etc) that was caught by Next.js's React Error
// Boundary. Read more about what types of exceptions are caught by Error
// Boundaries: https://reactjs.org/docs/error-boundaries.html
if (err) {
Sentry.captureException(err)
return errorInitialProps
}
}
// If this point is reached, getInitialProps was called without any
// information about what the error might be. This is unexpected and may
// indicate a bug introduced in Next.js, so record it in Sentry
Sentry.captureException(
new Error(`_error.js getInitialProps missing data at path: ${asPath}`)
)
return errorInitialProps
}
export default MyError
...@@ -13,8 +13,8 @@ addParameters({ ...@@ -13,8 +13,8 @@ addParameters({
return a[1].kind === b[1].kind return a[1].kind === b[1].kind
? 0 ? 0
: a[1].id.localeCompare(b[1].id, { numeric: true }) : a[1].id.localeCompare(b[1].id, { numeric: true })
}, }
}, }
}) })
// automatically import all files ending in *.stories.js // automatically import all files ending in *.stories.js
......
{
"name": "@next/plugin-google-analytics",
"version": "9.1.2-canary.1",
"nextjs": {
"name": "Google Analytics",
"required-env": [
"GA_TRACKING_ID"
]
},
"peerDependencies": {
"next": "*"
}
}
export default async function headTags () {
return (
<>
<script
async
src={`https://www.googletagmanager.com/gtag/js?id=${
process.env.GA_TRACKING_ID
}`}
/>
<script
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${process.env.GA_TRACKING_ID}');
`
}}
/>
</>
)
}
export default async function initClient ({ router }) {
router.events.on('routeChangeComplete', url => {
setTimeout(() => {
window.gtag('config', process.env.GA_TRACKING_ID, {
page_location: url,
page_title: document.title
})
}, 0)
})
}
{
"name": "@next/plugin-material-ui",
"version": "9.1.2-canary.1",
"nextjs": {
"name": "Material UI",
"required-env": []
},
"peerDependencies": {
"@material-ui/styles": "*",
"next": "*"
}
}
export default async function headTags () {
return (
<>
<meta charSet='utf-8' />
<meta
name='viewport'
content='minimum-scale=1, initial-scale=1, width=device-width, shrink-to-fit=no'
/>
<link
rel='stylesheet'
href='https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap'
/>
</>
)
}
import { ServerStyleSheets } from '@material-ui/styles'
export default async function enhanceApp (ctx) {
ctx.sheets = new ServerStyleSheets()
return App => props => ctx.sheets.collect(<App {...props} />)
}
export default async function getStyles (ctx) {
return ctx.sheets.getStyleElement()
}
export default async function unstablePostHydration () {
// Remove the server-side injected CSS.
const jssStyles = document.querySelector('#jss-server-side')
if (jssStyles) {
jssStyles.parentNode.removeChild(jssStyles)
}
}
{
"name": "@next/plugin-sentry",
"version": "9.1.2-canary.1",
"nextjs": {
"name": "Sentry",
"required-env": [
"SENTRY_DSN",
"SENTRY_RELEASE"
]
},
"peerDependencies": {
"next": "*"
},
"dependencies": {
"@sentry/browser": "5.7.1",
"@sentry/node": "5.7.1"
}
}
import * as Sentry from '@sentry/browser'
export default async function onErrorClient ({ err }) {
Sentry.captureException(err)
}
import * as Sentry from '@sentry/node'
export default async function onErrorServer ({ err }) {
Sentry.captureException(err)
}
import * as Sentry from '@sentry/browser'
export default async function initClient () {
// by default `@sentry/browser` is configured with defaultIntegrations
// which capture uncaughtExceptions and unhandledRejections
Sentry.init({
dsn: process.env.SENTRY_DSN,
release: process.env.SENTRY_RELEASE
})
}
import * as Sentry from '@sentry/node'
export default async function initServer () {
// by default `@sentry/node` is configured with defaultIntegrations
// which capture uncaughtExceptions and unhandledRejections
// see here for more https://github.com/getsentry/sentry-javascript/blob/46a02209bafcbc1603c769476ba0a1eaa450759d/packages/node/src/sdk.ts#L22
Sentry.init({
dsn: process.env.SENTRY_DSN,
release: process.env.SENTRY_RELEASE
})
}
...@@ -309,7 +309,6 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -309,7 +309,6 @@ export default async function build(dir: string, conf = null): Promise<void> {
) )
) )
} }
const postBuildSpinner = createSpinner({ const postBuildSpinner = createSpinner({
prefixText: 'Automatically optimizing pages', prefixText: 'Automatically optimizing pages',
}) })
......
import findUp from 'find-up'
import fs from 'fs'
import path from 'path'
import { promisify } from 'util'
import resolve from 'next/dist/compiled/resolve/index.js'
import { execOnce } from '../../next-server/lib/utils'
const readdir = promisify(fs.readdir)
export type PluginMetaData = {
requiredEnv: string[]
middleware: string[]
pluginName: string
directory: string
pkgName: string
version: string
config?: { [name: string]: any }
}
// currently supported middleware
export const VALID_MIDDLEWARE = [
'document-head-tags-server',
'document-body-tags-server',
'document-html-props-server',
'on-init-client',
'on-init-server',
'on-error-server',
'on-error-client',
'on-error-client',
'on-error-server',
'babel-preset-build',
'unstable-post-hydration',
'unstable-get-styles-server',
'unstable-enhance-app-server',
]
type ENV_OPTIONS = { [name: string]: string }
const exitWithError = (error: string) => {
console.error(error)
process.exit(1)
}
async function collectPluginMeta(
env: ENV_OPTIONS,
pluginPackagePath: string
): Promise<PluginMetaData> {
const pkgDir = path.dirname(pluginPackagePath)
const pluginPackageJson = require(pluginPackagePath)
const pluginMetaData: {
name: string
'required-env': string[]
} = pluginPackageJson.nextjs
if (!pluginMetaData) {
exitWithError('Next.js plugins need to have a "nextjs" key in package.json')
}
if (!pluginMetaData.name) {
exitWithError(
'Next.js plugins need to have a "nextjs.name" key in package.json'
)
}
// TODO: add err.sh explaining requirements
let middleware: string[] = []
try {
middleware = await readdir(path.join(pkgDir, 'src'))
} catch (err) {
if (err.code !== 'ENOENT') {
console.error(err)
}
exitWithError(
`Failed to read src/ directory for Next.js plugin: ${pluginMetaData.name}`
)
}
// remove the extension from the middleware
middleware = middleware.map(item => {
const parts = item.split('.')
parts.pop()
return parts.join('.')
})
const invalidMiddleware: string[] = []
for (const item of middleware) {
if (!VALID_MIDDLEWARE.includes(item)) {
invalidMiddleware.push(item)
}
}
if (invalidMiddleware.length > 0) {
console.error(
`Next.js Plugin: ${
pluginMetaData.name
} listed invalid middleware ${invalidMiddleware.join(', ')}`
)
}
// TODO: investigate requiring plugins' env be prefixed
// somehow to prevent collision
if (!Array.isArray(pluginMetaData['required-env'])) {
exitWithError(
'Next.js plugins need to have a "nextjs.required-env" key in package.json'
)
}
const missingEnvFields: string[] = []
for (const field of pluginMetaData['required-env']) {
if (typeof env[field] === 'undefined') {
missingEnvFields.push(field)
}
}
if (missingEnvFields.length > 0) {
exitWithError(
`Next.js Plugin: ${
pluginMetaData.name
} required env ${missingEnvFields.join(
', '
)} but was missing in your \`next.config.js\``
)
}
return {
middleware,
directory: pkgDir,
requiredEnv: pluginMetaData['required-env'],
version: pluginPackageJson.version,
pluginName: pluginMetaData.name,
pkgName: pluginPackageJson.name,
}
}
type SeparatedPlugins = {
appMiddlewarePlugins: PluginMetaData[]
documentMiddlewarePlugins: PluginMetaData[]
}
// clean package name so it can be used as variable
export const getPluginId = (pkg: string): string => {
pkg = pkg.replace(/\W/g, '')
if (pkg.match(/^[0-9]/)) {
pkg = `_${pkg}`
}
return pkg
}
type PluginConfig =
| string
| {
name: string
config: { [name: string]: any }
}
async function _collectPlugins(
dir: string,
env: ENV_OPTIONS,
pluginsConfig: PluginConfig[] | undefined
): Promise<PluginMetaData[]> {
let nextPluginNames: string[] = []
const skippedPluginNames: string[] = []
const hasPluginConfig = Array.isArray(pluginsConfig)
const nextPluginConfigNames = hasPluginConfig
? pluginsConfig!.map(config =>
typeof config === 'string' ? config : config.name
)
: null
const rootPackageJsonPath = await findUp('package.json', { cwd: dir })
if (!rootPackageJsonPath && !nextPluginConfigNames) {
console.log('Failed to load plugins, no package.json')
return []
}
if (rootPackageJsonPath) {
const rootPackageJson = require(rootPackageJsonPath)
let dependencies: string[] = []
if (rootPackageJson.dependencies) {
dependencies = dependencies.concat(
Object.keys(rootPackageJson.dependencies)
)
}
if (rootPackageJson.devDependencies) {
dependencies = dependencies.concat(
Object.keys(rootPackageJson.devDependencies)
)
}
// find packages with the naming convention
// @scope/next-plugin-[name]
// @next/plugin-[name]
// next-plugin-[name]
const filteredDeps = dependencies.filter(name => {
return name.match(/(^@next\/plugin|next-plugin-)/)
})
if (nextPluginConfigNames) {
for (const dep of filteredDeps) {
if (!nextPluginConfigNames.includes(dep)) {
skippedPluginNames.push(dep)
}
}
nextPluginNames = nextPluginConfigNames
} else {
nextPluginNames = filteredDeps
}
}
const nextPluginMetaData = await Promise.all(
nextPluginNames.map(name =>
collectPluginMeta(
env,
resolve.sync(path.join(name, 'package.json'), {
basedir: dir,
preserveSymlinks: true,
})
)
)
)
for (const plugin of nextPluginMetaData) {
// Add plugin config from `next.config.js`
if (hasPluginConfig) {
const curPlugin = pluginsConfig!.find(
config =>
config && typeof config === 'object' && config.name === plugin.pkgName
)
if (curPlugin && typeof curPlugin === 'object') {
plugin.config = curPlugin.config
}
}
console.log(
`Loaded plugin: ${plugin.pkgName}${
plugin.version ? `@${plugin.version}` : ''
}`
)
}
if (skippedPluginNames.length) {
console.log(
`Plugins config used skipped loading: ${skippedPluginNames.join(', ')}`
)
}
console.log()
return nextPluginMetaData
}
// only execute it once between server/client configs
// since the plugins need to match
export const collectPlugins = execOnce(
_collectPlugins
) as typeof _collectPlugins
...@@ -35,10 +35,16 @@ import NextJsSsrImportPlugin from './webpack/plugins/nextjs-ssr-import' ...@@ -35,10 +35,16 @@ import NextJsSsrImportPlugin from './webpack/plugins/nextjs-ssr-import'
import NextJsSSRModuleCachePlugin from './webpack/plugins/nextjs-ssr-module-cache' import NextJsSSRModuleCachePlugin from './webpack/plugins/nextjs-ssr-module-cache'
import PagesManifestPlugin from './webpack/plugins/pages-manifest-plugin' import PagesManifestPlugin from './webpack/plugins/pages-manifest-plugin'
// @ts-ignore: JS file // @ts-ignore: JS file
import { pluginLoaderOptions } from './webpack/loaders/next-plugin-loader'
import { ProfilingPlugin } from './webpack/plugins/profiling-plugin' import { ProfilingPlugin } from './webpack/plugins/profiling-plugin'
import { ReactLoadablePlugin } from './webpack/plugins/react-loadable-plugin' import { ReactLoadablePlugin } from './webpack/plugins/react-loadable-plugin'
import { ServerlessPlugin } from './webpack/plugins/serverless-plugin' import { ServerlessPlugin } from './webpack/plugins/serverless-plugin'
import { TerserPlugin } from './webpack/plugins/terser-webpack-plugin/src/index' import { TerserPlugin } from './webpack/plugins/terser-webpack-plugin/src/index'
import {
collectPlugins,
VALID_MIDDLEWARE,
PluginMetaData,
} from './plugins/collect-plugins'
type ExcludesFalse = <T>(x: T | false) => x is T type ExcludesFalse = <T>(x: T | false) => x is T
...@@ -70,17 +76,34 @@ export default async function getBaseWebpackConfig( ...@@ -70,17 +76,34 @@ export default async function getBaseWebpackConfig(
entrypoints: WebpackEntrypoints entrypoints: WebpackEntrypoints
} }
): Promise<webpack.Configuration> { ): Promise<webpack.Configuration> {
let plugins: PluginMetaData[] = []
let babelPresetPlugins: { dir: string; config: any }[] = []
if (config.experimental.plugins) {
plugins = await collectPlugins(dir, config.env, config.plugins)
pluginLoaderOptions.plugins = plugins
for (const plugin of plugins) {
if (plugin.middleware.includes('babel-preset-build')) {
babelPresetPlugins.push({
dir: plugin.directory,
config: plugin.config,
})
}
}
}
const distDir = path.join(dir, config.distDir) const distDir = path.join(dir, config.distDir)
const defaultLoaders = { const defaultLoaders = {
babel: { babel: {
loader: 'next-babel-loader', loader: 'next-babel-loader',
options: { options: {
isServer, isServer,
hasModern: !!config.experimental.modern,
distDir, distDir,
pagesDir, pagesDir,
cwd: dir, cwd: dir,
cache: true, cache: true,
babelPresetPlugins,
hasModern: !!config.experimental.modern,
}, },
}, },
// Backwards compat // Backwards compat
...@@ -89,6 +112,16 @@ export default async function getBaseWebpackConfig( ...@@ -89,6 +112,16 @@ export default async function getBaseWebpackConfig(
}, },
} }
const babelIncludeRegexes: RegExp[] = [
/next[\\/]dist[\\/]next-server[\\/]lib/,
/next[\\/]dist[\\/]client/,
/next[\\/]dist[\\/]pages/,
/[\\/](strip-ansi|ansi-regex)[\\/]/,
...(config.experimental.plugins
? VALID_MIDDLEWARE.map(name => new RegExp(`src/${name}`))
: []),
]
// Support for NODE_PATH // Support for NODE_PATH
const nodePathList = (process.env.NODE_PATH || '') const nodePathList = (process.env.NODE_PATH || '')
.split(process.platform === 'win32' ? ';' : ':') .split(process.platform === 'win32' ? ';' : ':')
...@@ -334,6 +367,12 @@ export default async function getBaseWebpackConfig( ...@@ -334,6 +367,12 @@ export default async function getBaseWebpackConfig(
return callback() return callback()
} }
// make sure we don't externalize anything that is
// supposed to be transpiled
if (babelIncludeRegexes.some(r => r.test(request))) {
return callback()
}
// Relative requires don't need custom resolution, because they // Relative requires don't need custom resolution, because they
// are relative to requests we've already resolved here. // are relative to requests we've already resolved here.
// Absolute requires (require('/foo')) are extremely uncommon, but // Absolute requires (require('/foo')) are extremely uncommon, but
...@@ -476,6 +515,13 @@ export default async function getBaseWebpackConfig( ...@@ -476,6 +515,13 @@ export default async function getBaseWebpackConfig(
return { return {
...(clientEntries ? clientEntries : {}), ...(clientEntries ? clientEntries : {}),
...entrypoints, ...entrypoints,
...(isServer
? {
'init-server.js': 'next-plugin-loader?middleware=on-init-server!',
'on-error-server.js':
'next-plugin-loader?middleware=on-error-server!',
}
: {}),
} }
}, },
output: { output: {
...@@ -515,6 +561,7 @@ export default async function getBaseWebpackConfig( ...@@ -515,6 +561,7 @@ export default async function getBaseWebpackConfig(
'next-data-loader', 'next-data-loader',
'next-serverless-loader', 'next-serverless-loader',
'noop-loader', 'noop-loader',
'next-plugin-loader',
].reduce( ].reduce(
(alias, loader) => { (alias, loader) => {
// using multiple aliases to replace `resolveLoader.modules` // using multiple aliases to replace `resolveLoader.modules`
...@@ -542,23 +589,11 @@ export default async function getBaseWebpackConfig( ...@@ -542,23 +589,11 @@ export default async function getBaseWebpackConfig(
}, },
{ {
test: /\.(tsx|ts|js|mjs|jsx)$/, test: /\.(tsx|ts|js|mjs|jsx)$/,
include: [ include: [dir, ...babelIncludeRegexes],
dir,
/next[\\/]dist[\\/]next-server[\\/]lib/,
/next[\\/]dist[\\/]client/,
/next[\\/]dist[\\/]pages/,
/[\\/](strip-ansi|ansi-regex)[\\/]/,
],
exclude: (path: string) => { exclude: (path: string) => {
if ( if (babelIncludeRegexes.some(r => r.test(path))) {
/next[\\/]dist[\\/]next-server[\\/]lib/.test(path) ||
/next[\\/]dist[\\/]client/.test(path) ||
/next[\\/]dist[\\/]pages/.test(path) ||
/[\\/](strip-ansi|ansi-regex)[\\/]/.test(path)
) {
return false return false
} }
return /node_modules/.test(path) return /node_modules/.test(path)
}, },
use: defaultLoaders.babel, use: defaultLoaders.babel,
...@@ -750,6 +785,9 @@ export default async function getBaseWebpackConfig( ...@@ -750,6 +785,9 @@ export default async function getBaseWebpackConfig(
'process.env.__NEXT_PRERENDER_INDICATOR': JSON.stringify( 'process.env.__NEXT_PRERENDER_INDICATOR': JSON.stringify(
config.devIndicators.autoPrerender config.devIndicators.autoPrerender
), ),
'process.env.__NEXT_PLUGINS': JSON.stringify(
config.experimental.plugins
),
'process.env.__NEXT_STRICT_MODE': JSON.stringify( 'process.env.__NEXT_STRICT_MODE': JSON.stringify(
config.reactStrictMode config.reactStrictMode
), ),
......
...@@ -55,7 +55,8 @@ module.exports = babelLoader.custom(babel => { ...@@ -55,7 +55,8 @@ module.exports = babelLoader.custom(babel => {
isServer: opts.isServer, isServer: opts.isServer,
isModern: opts.isModern, isModern: opts.isModern,
pagesDir: opts.pagesDir, pagesDir: opts.pagesDir,
hasModern: opts.hasModern hasModern: opts.hasModern,
babelPresetPlugins: opts.babelPresetPlugins
} }
const filename = join(opts.cwd, 'noop.js') const filename = join(opts.cwd, 'noop.js')
const loader = Object.assign( const loader = Object.assign(
...@@ -88,13 +89,20 @@ module.exports = babelLoader.custom(babel => { ...@@ -88,13 +89,20 @@ module.exports = babelLoader.custom(babel => {
delete loader.isModern delete loader.isModern
delete loader.hasModern delete loader.hasModern
delete loader.pagesDir delete loader.pagesDir
delete loader.babelPresetPlugins
return { loader, custom } return { loader, custom }
}, },
config ( config (
cfg, cfg,
{ {
source, source,
customOptions: { isServer, isModern, hasModern, pagesDir } customOptions: {
isServer,
isModern,
hasModern,
pagesDir,
babelPresetPlugins
}
} }
) { ) {
const filename = this.resourcePath const filename = this.resourcePath
...@@ -183,6 +191,13 @@ module.exports = babelLoader.custom(babel => { ...@@ -183,6 +191,13 @@ module.exports = babelLoader.custom(babel => {
} }
] ]
for (const plugin of babelPresetPlugins) {
require(join(plugin.dir, 'src', 'babel-preset-build.js'))(
options,
plugin.config || {}
)
}
return options return options
} }
} }
......
import { loader } from 'webpack'
import { parse } from 'querystring'
import { PluginMetaData, getPluginId } from '../../plugins/collect-plugins'
export type NextPluginLoaderQuery = {
middleware: string
}
export const pluginLoaderOptions: {
plugins: PluginMetaData[]
} = {
plugins: [],
}
const nextPluginLoader: loader.Loader = function(source) {
const { middleware }: NextPluginLoaderQuery =
typeof this.query === 'string' ? parse(this.query.substr(1)) : this.query
const plugins = pluginLoaderOptions.plugins.filter(plugin => {
return plugin.middleware.includes(middleware)
})
const pluginIds: string[] = []
const pluginConfigs: any[] = []
return `
${plugins
.map(plugin => {
const pluginId = getPluginId(plugin.pkgName)
pluginIds.push(pluginId)
pluginConfigs.push(plugin.config || {})
return `import ${pluginId} from '${plugin.directory}/src/${middleware}'`
})
.join('\n')}
export default function (ctx) {
return Promise.all([${pluginIds
.map((id, idx) => `${id}(ctx, ${JSON.stringify(pluginConfigs[idx])})`)
.join(',')}])
}
`
}
export default nextPluginLoader
...@@ -56,8 +56,12 @@ const nextServerlessLoader: loader.Loader = function() { ...@@ -56,8 +56,12 @@ const nextServerlessLoader: loader.Loader = function() {
} }
import { parse } from 'url' import { parse } from 'url'
import { apiResolver } from 'next/dist/next-server/server/api-utils' import { apiResolver } from 'next/dist/next-server/server/api-utils'
import initServer from 'next-plugin-loader?middleware=on-init-server!'
import onError from 'next-plugin-loader?middleware=on-error-server!'
export default (req, res) => { export default async (req, res) => {
try {
await initServer()
const params = ${ const params = ${
isDynamicRoute(page) isDynamicRoute(page)
? `getRouteMatcher(getRouteRegex('${page}'))(parse(req.url).pathname)` ? `getRouteMatcher(getRouteRegex('${page}'))(parse(req.url).pathname)`
...@@ -65,6 +69,12 @@ const nextServerlessLoader: loader.Loader = function() { ...@@ -65,6 +69,12 @@ const nextServerlessLoader: loader.Loader = function() {
} }
const resolver = require('${absolutePagePath}') const resolver = require('${absolutePagePath}')
apiResolver(req, res, params, resolver) apiResolver(req, res, params, resolver)
} catch (error) {
await onError(err)
console.error(err)
res.statusCode = 500
res.end('Internal Server Error')
}
} }
` `
} else { } else {
...@@ -73,6 +83,8 @@ const nextServerlessLoader: loader.Loader = function() { ...@@ -73,6 +83,8 @@ const nextServerlessLoader: loader.Loader = function() {
import {parse as parseQs} from 'querystring' import {parse as parseQs} from 'querystring'
import {renderToHTML} from 'next/dist/next-server/server/render'; import {renderToHTML} from 'next/dist/next-server/server/render';
import {sendHTML} from 'next/dist/next-server/server/send-html'; import {sendHTML} from 'next/dist/next-server/server/send-html';
import initServer from 'next-plugin-loader?middleware=on-init-server!'
import onError from 'next-plugin-loader?middleware=on-error-server!'
${ ${
isDynamicRoute(page) isDynamicRoute(page)
? `import {getRouteMatcher, getRouteRegex} from 'next/dist/next-server/lib/router/utils';` ? `import {getRouteMatcher, getRouteRegex} from 'next/dist/next-server/lib/router/utils';`
...@@ -201,11 +213,13 @@ const nextServerlessLoader: loader.Loader = function() { ...@@ -201,11 +213,13 @@ const nextServerlessLoader: loader.Loader = function() {
} }
export async function render (req, res) { export async function render (req, res) {
try { try {
await initServer()
const html = await renderReqToHTML(req, res) const html = await renderReqToHTML(req, res)
if (html) { if (html) {
sendHTML(req, res, html, {generateEtags: ${generateEtags}}) sendHTML(req, res, html, {generateEtags: ${generateEtags}})
} }
} catch(err) { } catch(err) {
await onError(err)
console.error(err) console.error(err)
res.statusCode = 500 res.statusCode = 500
res.end('Internal Server Error') res.end('Internal Server Error')
......
...@@ -87,6 +87,17 @@ class Container extends React.Component { ...@@ -87,6 +87,17 @@ class Container extends React.Component {
componentDidMount () { componentDidMount () {
this.scrollToHash() this.scrollToHash()
if (process.env.__NEXT_PLUGINS) {
// eslint-disable-next-line
import('next-plugin-loader?middleware=unstable-post-hydration!')
.then(mod => {
return mod.default()
})
.catch(err => {
console.error('Error calling post-hydration for plugins', err)
})
}
// If page was exported and has a querystring // If page was exported and has a querystring
// If it's a dynamic route or has a querystring // If it's a dynamic route or has a querystring
if ( if (
...@@ -182,6 +193,19 @@ export default async ({ webpackHMR: passedWebpackHMR } = {}) => { ...@@ -182,6 +193,19 @@ export default async ({ webpackHMR: passedWebpackHMR } = {}) => {
render({ App, Component, props, err, emitter }) render({ App, Component, props, err, emitter })
} }
}) })
// call init-client middleware
if (process.env.__NEXT_PLUGINS) {
// eslint-disable-next-line
import('next-plugin-loader?middleware=on-init-client!')
.then(mod => {
return mod.default({ router })
})
.catch(err => {
console.error('Error calling client-init for plugins', err)
})
}
const renderCtx = { App, Component, props, err: initialErr, emitter } const renderCtx = { App, Component, props, err: initialErr, emitter }
render(renderCtx) render(renderCtx)
...@@ -212,6 +236,16 @@ export async function renderError (props) { ...@@ -212,6 +236,16 @@ export async function renderError (props) {
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
return webpackHMR.reportRuntimeError(webpackHMR.prepareError(err)) return webpackHMR.reportRuntimeError(webpackHMR.prepareError(err))
} }
if (process.env.__NEXT_PLUGINS) {
// eslint-disable-next-line
import('next-plugin-loader?middleware=on-error-client!')
.then(mod => {
return mod.default({ err })
})
.catch(err => {
console.error('error calling on-error-client for plugins', err)
})
}
// Make sure we log the error to the console, otherwise users can't track down issues. // Make sure we log the error to the console, otherwise users can't track down issues.
console.error(err) console.error(err)
......
...@@ -153,6 +153,9 @@ export type DocumentProps = DocumentInitialProps & { ...@@ -153,6 +153,9 @@ export type DocumentProps = DocumentInitialProps & {
dynamicImports: ManifestItem[] dynamicImports: ManifestItem[]
assetPrefix?: string assetPrefix?: string
canonicalBase: string canonicalBase: string
htmlProps: any
bodyTags: any[]
headTags: any[]
} }
/** /**
...@@ -200,11 +203,14 @@ export type NextApiResponse<T = any> = ServerResponse & { ...@@ -200,11 +203,14 @@ export type NextApiResponse<T = any> = ServerResponse & {
*/ */
export function execOnce(this: any, fn: (...args: any) => any) { export function execOnce(this: any, fn: (...args: any) => any) {
let used = false let used = false
let result: any = null
return (...args: any) => { return (...args: any) => {
if (!used) { if (!used) {
used = true used = true
fn.apply(this, args) result = fn.apply(this, args)
} }
return result
} }
} }
......
...@@ -46,6 +46,7 @@ const defaultConfig: { [key: string]: any } = { ...@@ -46,6 +46,7 @@ const defaultConfig: { [key: string]: any } = {
documentMiddleware: false, documentMiddleware: false,
granularChunks: false, granularChunks: false,
modern: false, modern: false,
plugins: false,
profiling: false, profiling: false,
publicDirectory: false, publicDirectory: false,
sprFlushToDisk: true, sprFlushToDisk: true,
......
...@@ -84,6 +84,7 @@ export default class Server { ...@@ -84,6 +84,7 @@ export default class Server {
dev?: boolean dev?: boolean
} }
private compression?: Middleware private compression?: Middleware
private onErrorMiddleware?: ({ err }: { err: Error }) => void
router: Router router: Router
protected dynamicRoutes?: Array<{ page: string; match: RouteMatch }> protected dynamicRoutes?: Array<{ page: string; match: RouteMatch }>
...@@ -154,6 +155,21 @@ export default class Server { ...@@ -154,6 +155,21 @@ export default class Server {
this.router = new Router(routes) this.router = new Router(routes)
this.setAssetPrefix(assetPrefix) this.setAssetPrefix(assetPrefix)
// call init-server middleware, this is also handled
// individually in serverless bundles when deployed
if (!dev && this.nextConfig.experimental.plugins) {
const serverPath = join(
this.distDir,
this._isLikeServerless ? 'serverless' : 'server'
)
const initServer = require(join(serverPath, 'init-server.js')).default
this.onErrorMiddleware = require(join(
serverPath,
'on-error-server.js'
)).default
initServer()
}
initializeSprCache({ initializeSprCache({
dev, dev,
distDir: this.distDir, distDir: this.distDir,
...@@ -172,10 +188,13 @@ export default class Server { ...@@ -172,10 +188,13 @@ export default class Server {
return PHASE_PRODUCTION_SERVER return PHASE_PRODUCTION_SERVER
} }
private logError(...args: any): void { private logError(err: Error): void {
if (this.onErrorMiddleware) {
this.onErrorMiddleware({ err })
}
if (this.quiet) return if (this.quiet) return
// tslint:disable-next-line // tslint:disable-next-line
console.error(...args) console.error(err)
} }
private handleRequest( private handleRequest(
......
...@@ -189,6 +189,9 @@ function renderDocument( ...@@ -189,6 +189,9 @@ function renderDocument(
devFiles, devFiles,
files, files,
dynamicImports, dynamicImports,
htmlProps,
bodyTags,
headTags,
}: RenderOpts & { }: RenderOpts & {
dataManagerData: string dataManagerData: string
props: any props: any
...@@ -204,6 +207,9 @@ function renderDocument( ...@@ -204,6 +207,9 @@ function renderDocument(
dynamicImports: ManifestItem[] dynamicImports: ManifestItem[]
files: string[] files: string[]
devFiles: string[] devFiles: string[]
htmlProps: any
bodyTags: any
headTags: any
} }
): string { ): string {
return ( return (
...@@ -238,6 +244,9 @@ function renderDocument( ...@@ -238,6 +244,9 @@ function renderDocument(
files, files,
dynamicImports, dynamicImports,
assetPrefix, assetPrefix,
htmlProps,
bodyTags,
headTags,
...docProps, ...docProps,
})} })}
</AmpStateContext.Provider> </AmpStateContext.Provider>
...@@ -272,6 +281,29 @@ export async function renderToHTML( ...@@ -272,6 +281,29 @@ export async function renderToHTML(
unstable_getStaticParams, unstable_getStaticParams,
} = renderOpts } = renderOpts
const callMiddleware = async (method: string, args: any[], props = false) => {
let results: any = props ? {} : []
if ((Document as any)[`${method}Middleware`]) {
const curResults = await (Document as any)[`${method}Middleware`](...args)
if (props) {
for (const result of curResults) {
results = {
...results,
...result,
}
}
} else {
results = curResults
}
}
return results
}
const headTags = (...args: any) => callMiddleware('headTags', args)
const bodyTags = (...args: any) => callMiddleware('bodyTags', args)
const htmlProps = (...args: any) => callMiddleware('htmlProps', args, true)
const isSpr = !!unstable_getStaticProps const isSpr = !!unstable_getStaticProps
const defaultAppGetInitialProps = const defaultAppGetInitialProps =
App.getInitialProps === (App as any).origGetInitialProps App.getInitialProps === (App as any).origGetInitialProps
...@@ -547,8 +579,8 @@ export async function renderToHTML( ...@@ -547,8 +579,8 @@ export async function renderToHTML(
) )
} }
} }
const documentCtx = { ...ctx, renderPage }
const docProps = await loadGetInitialProps(Document, { ...ctx, renderPage }) const docProps = await loadGetInitialProps(Document, documentCtx)
// the response might be finished on the getInitialProps call // the response might be finished on the getInitialProps call
if (isResSent(res) && !isSpr) return null if (isResSent(res) && !isSpr) return null
...@@ -596,6 +628,9 @@ export async function renderToHTML( ...@@ -596,6 +628,9 @@ export async function renderToHTML(
dataManagerData, dataManagerData,
ampState, ampState,
props, props,
headTags: await headTags(documentCtx),
bodyTags: await bodyTags(documentCtx),
htmlProps: await htmlProps(documentCtx),
docProps, docProps,
pathname, pathname,
ampPath, ampPath,
......
...@@ -14,6 +14,16 @@ import { ...@@ -14,6 +14,16 @@ import {
CLIENT_STATIC_FILES_RUNTIME_WEBPACK, CLIENT_STATIC_FILES_RUNTIME_WEBPACK,
} from '../next-server/lib/constants' } from '../next-server/lib/constants'
import { DocumentContext as DocumentComponentContext } from '../next-server/lib/document-context' import { DocumentContext as DocumentComponentContext } from '../next-server/lib/document-context'
// @ts-ignore
import headTagsMiddleware from 'next-plugin-loader?middleware=document-head-tags-server!'
// @ts-ignore
import bodyTagsMiddleware from 'next-plugin-loader?middleware=document-body-tags-server!'
// @ts-ignore
import htmlPropsMiddleware from 'next-plugin-loader?middleware=document-html-props-server!'
// @ts-ignore
import enhanceAppMiddleware from 'next-plugin-loader?middleware=unstable-enhance-app-server!'
// @ts-ignore
import getStylesMiddleware from 'next-plugin-loader?middleware=unstable-get-styles-server!'
export { DocumentContext, DocumentInitialProps, DocumentProps } export { DocumentContext, DocumentInitialProps, DocumentProps }
...@@ -48,15 +58,27 @@ function getOptionalModernScriptVariant(path: string) { ...@@ -48,15 +58,27 @@ function getOptionalModernScriptVariant(path: string) {
* Commonly used for implementing server side rendering for `css-in-js` libraries. * Commonly used for implementing server side rendering for `css-in-js` libraries.
*/ */
export default class Document<P = {}> extends Component<DocumentProps & P> { export default class Document<P = {}> extends Component<DocumentProps & P> {
static headTagsMiddleware = headTagsMiddleware
static bodyTagsMiddleware = bodyTagsMiddleware
static htmlPropsMiddleware = htmlPropsMiddleware
/** /**
* `getInitialProps` hook returns the context object with the addition of `renderPage`. * `getInitialProps` hook returns the context object with the addition of `renderPage`.
* `renderPage` callback executes `React` rendering logic synchronously to support server-rendering wrappers * `renderPage` callback executes `React` rendering logic synchronously to support server-rendering wrappers
*/ */
static async getInitialProps({ static async getInitialProps(
renderPage, ctx: DocumentContext
}: DocumentContext): Promise<DocumentInitialProps> { ): Promise<DocumentInitialProps> {
const { html, head, dataOnly } = await renderPage() const enhancers = await enhanceAppMiddleware(ctx)
const styles = flush() const enhanceApp = (App: any) => {
for (const enhancer of enhancers) {
App = enhancer(App)
}
return (props: any) => <App {...props} />
}
const { html, head, dataOnly } = await ctx.renderPage({ enhanceApp })
const styles = [...flush(), ...(await getStylesMiddleware(ctx))]
return { html, head, styles, dataOnly } return { html, head, styles, dataOnly }
} }
...@@ -108,9 +130,10 @@ export class Html extends Component< ...@@ -108,9 +130,10 @@ export class Html extends Component<
context!: React.ContextType<typeof DocumentComponentContext> context!: React.ContextType<typeof DocumentComponentContext>
render() { render() {
const { inAmpMode } = this.context._documentProps const { inAmpMode, htmlProps } = this.context._documentProps
return ( return (
<html <html
{...htmlProps}
{...this.props} {...this.props}
amp={inAmpMode ? '' : undefined} amp={inAmpMode ? '' : undefined}
data-ampdevmode={ data-ampdevmode={
...@@ -246,6 +269,7 @@ export class Head extends Component< ...@@ -246,6 +269,7 @@ export class Head extends Component<
canonicalBase, canonicalBase,
__NEXT_DATA__, __NEXT_DATA__,
dangerousAsPath, dangerousAsPath,
headTags,
} = this.context._documentProps } = this.context._documentProps
const { _devOnlyInvalidateCacheQueryString } = this.context const { _devOnlyInvalidateCacheQueryString } = this.context
const { page, buildId } = __NEXT_DATA__ const { page, buildId } = __NEXT_DATA__
...@@ -474,6 +498,7 @@ export class Head extends Component< ...@@ -474,6 +498,7 @@ export class Head extends Component<
{styles || null} {styles || null}
</> </>
)} )}
{React.createElement(React.Fragment, {}, ...(headTags || []))}
</head> </head>
) )
} }
...@@ -595,6 +620,7 @@ export class NextScript extends Component<OriginProps> { ...@@ -595,6 +620,7 @@ export class NextScript extends Component<OriginProps> {
inAmpMode, inAmpMode,
devFiles, devFiles,
__NEXT_DATA__, __NEXT_DATA__,
bodyTags,
} = this.context._documentProps } = this.context._documentProps
const deferScripts: any = process.env.__NEXT_DEFER_SCRIPTS const deferScripts: any = process.env.__NEXT_DEFER_SCRIPTS
const { _devOnlyInvalidateCacheQueryString } = this.context const { _devOnlyInvalidateCacheQueryString } = this.context
...@@ -636,6 +662,7 @@ export class NextScript extends Component<OriginProps> { ...@@ -636,6 +662,7 @@ export class NextScript extends Component<OriginProps> {
/> />
)) ))
: null} : null}
{React.createElement(React.Fragment, {}, ...(bodyTags || []))}
</> </>
) )
} }
...@@ -761,6 +788,7 @@ export class NextScript extends Component<OriginProps> { ...@@ -761,6 +788,7 @@ export class NextScript extends Component<OriginProps> {
{appScript} {appScript}
{staticMarkup ? null : this.getDynamicChunks()} {staticMarkup ? null : this.getDynamicChunks()}
{staticMarkup ? null : this.getScripts()} {staticMarkup ? null : this.getScripts()}
{React.createElement(React.Fragment, {}, ...(bodyTags || []))}
</> </>
) )
} }
......
...@@ -18,6 +18,8 @@ const babelClientOpts = { ...@@ -18,6 +18,8 @@ const babelClientOpts = {
'@babel/preset-react' '@babel/preset-react'
], ],
plugins: [ plugins: [
// workaround for @taskr/esnext bug replacing `-import` with `-require(`
'@babel/plugin-syntax-dynamic-impor' + 't',
['@babel/plugin-proposal-class-properties', { loose: true }], ['@babel/plugin-proposal-class-properties', { loose: true }],
[ [
'@babel/plugin-transform-runtime', '@babel/plugin-transform-runtime',
......
{
"name": "@next/plugin-google-analytics",
"version": "0.0.1",
"nextjs": {
"name": "Google Analytics",
"required-env": [
"GA_TRACKING_ID"
]
},
"peerDependencies": {
"next": "*"
}
}
module.exports = function babelPresetBuild(ctx, config) {
// options.plugins
// options.presets
}
export default async function bodyTags () {
return (
<>
<script dangerouslySetInnerHTML={{ __html: 'console.log("hi") ' }} />
</>
)
}
export default async function headTags () {
return (
<>
<script
async
src={`https://www.googletagmanager.com/gtag/js?id=${
process.env.GA_TRACKING_ID
}`}
/>
<script
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${process.env.GA_TRACKING_ID}');
`
}}
/>
</>
)
}
export default async function initClient(ctx, config) {
window.didClientInit = true
window.initClientConfig = config.hello
}
export default async function initServer() {
console.log('hi from init server')
}
\ No newline at end of file
{
"name": "@zeit/next-plugin-scope",
"version": "0.0.1",
"nextjs": {
"name": "Scoped Package Test",
"required-env": []
},
"peerDependencies": {
"next": "*"
}
}
export default async function initClient() {
window.didScopedInit = true
}
\ No newline at end of file
{
"name": "next-plugin-normal",
"version": "0.0.1",
"nextjs": {
"name": "Normal Package Test",
"required-env": []
},
"peerDependencies": {
"next": "*"
}
}
export default async function initClient() {
window.didNormalInit = true
}
\ No newline at end of file
{
"dependencies": {
"@next/plugin-google-analytics": "latest",
"@zeit/next-plugin-scope": "latest",
"next-plugin-normal": "latest"
}
}
import Link from 'next/link'
import Head from 'next/head'
export default () => (
<>
<Head>
<title>Another | next-plugins</title>
</Head>
<p id='another'>Another</p>
<Link href='/'>
<a id='to-home'>home</a>
</Link>
<Link href='/something'>
<a id='to-something'>something</a>
</Link>
</>
)
import Link from 'next/link'
import Head from 'next/head'
const Page = () => (
<>
<Head>
<title>Home | next-plugins</title>
</Head>
<p id='home'>Home</p>
<Link href='/another'>
<a id='to-another'>another</a>
</Link>
<Link href='/something'>
<a id='to-something'>something</a>
</Link>
</>
)
Page.getInitialProps = () => ({})
export default Page
import Link from 'next/link'
import Head from 'next/head'
export default () => (
<>
<Head>
<title>Something | next-plugins</title>
</Head>
<p id='something'>something</p>
<Link href='/'>
<a id='to-home'>home</a>
</Link>
<Link href='/another'>
<a id='to-another'>another</a>
</Link>
</>
)
/* eslint-env jest */
/* global jasmine */
import fs from 'fs-extra'
import { join } from 'path'
import cheerio from 'cheerio'
import webdriver from 'next-webdriver'
import {
findPort,
launchApp,
killApp,
waitFor,
nextBuild,
nextStart,
renderViaHTTP
} from 'next-test-utils'
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 2
let app
let appPort
let stdout
const appDir = join(__dirname, '../app')
const nextConfigPath = join(appDir, 'next.config.js')
function runTests () {
it('should render tha page without error', async () => {
const html = await renderViaHTTP(appPort, '/')
expect(html).toMatch(/home/)
})
it('should apply htmlProps from plugin correctly', async () => {
const html = await renderViaHTTP(appPort, '/')
const $ = cheerio.load(html)
expect($('html').attr('lang')).toBe('en')
})
it('should apply headTags from plugin correctly', async () => {
const html = await renderViaHTTP(appPort, '/')
const $ = cheerio.load(html)
const found = Array.from($('head').children()).find(el => {
return (el.attribs.src || '').match(/googletagmanager.*?my-tracking-id/)
})
expect(found).toBeTruthy()
})
it('should apply bodyTags from plugin correctly', async () => {
const html = await renderViaHTTP(appPort, '/')
const $ = cheerio.load(html)
const found = Array.from($('body').children()).find(
el =>
el.type === 'script' &&
el.children[0] &&
el.children[0].data.includes('console.log')
)
expect(found).toBeTruthy()
})
it('should call clientInit from plugin correctly', async () => {
const browser = await webdriver(appPort, '/')
await waitFor(250)
expect(await browser.eval('window.didClientInit')).toBe(true)
})
it('should list loaded plugins', async () => {
expect(stdout).toMatch(/loaded plugin: @next\/plugin-google-analytics/i)
expect(stdout).toMatch(/loaded plugin: @zeit\/next-plugin-scope/i)
expect(stdout).toMatch(/loaded plugin: next-plugin-normal/i)
})
}
describe('Next.js plugins', () => {
describe('dev mode', () => {
beforeAll(async () => {
await fs.writeFile(
nextConfigPath,
`module.exports = { env: { GA_TRACKING_ID: 'my-tracking-id' }, experimental: { plugins: true } }`
)
appPort = await findPort()
app = await launchApp(appDir, appPort, {
onStdout (msg) {
stdout += msg
}
})
})
afterAll(() => killApp(app))
runTests(true)
describe('with plugin config', () => {
beforeAll(async () => {
await killApp(app)
await fs.writeFile(
nextConfigPath,
`
module.exports = {
experimental: {
plugins: true
},
plugins: [
{
name: '@next/plugin-google-analytics',
config: { hello: 'world' }
}
],
env: {
GA_TRACKING_ID: 'my-tracking-id'
}
}`
)
appPort = await findPort()
stdout = ''
app = await launchApp(appDir, appPort, {
onStdout (msg) {
stdout += msg
}
})
})
afterAll(() => killApp(app))
it('should disable auto detecting plugins when plugin config is used', async () => {
expect(stdout).toMatch(/loaded plugin: @next\/plugin-google-analytics/i)
expect(stdout).not.toMatch(/loaded plugin: @zeit\/next-plugin-scope/i)
expect(stdout).not.toMatch(/loaded plugin: next-plugin-normal/i)
})
it('should expose a plugins config', async () => {
const browser = await webdriver(appPort, '/')
await waitFor(500)
expect(await browser.eval('window.initClientConfig')).toBe('world')
})
})
})
describe('production mode', () => {
beforeAll(async () => {
await fs.writeFile(
nextConfigPath,
`module.exports = { env: { GA_TRACKING_ID: 'my-tracking-id' }, experimental: { plugins: true } }`
)
const results = await nextBuild(appDir, undefined, {
stdout: true
})
stdout = results.stdout
appPort = await findPort()
app = await nextStart(appDir, appPort)
})
afterAll(async () => {
await killApp(app)
await fs.remove(nextConfigPath)
})
runTests()
})
describe('serverless mode', () => {
beforeAll(async () => {
await fs.writeFile(
nextConfigPath,
`module.exports = { target: 'serverless', env: { GA_TRACKING_ID: 'my-tracking-id' }, experimental: { plugins: true } }`
)
const results = await nextBuild(appDir, undefined, {
stdout: true
})
stdout = results.stdout
appPort = await findPort()
app = await nextStart(appDir, appPort)
})
afterAll(async () => {
await killApp(app)
await fs.remove(nextConfigPath)
})
runTests()
})
})
...@@ -2129,6 +2129,72 @@ ...@@ -2129,6 +2129,72 @@
dependencies: dependencies:
any-observable "^0.3.0" any-observable "^0.3.0"
"@sentry/browser@5.7.1":
version "5.7.1"
resolved "https://registry.yarnpkg.com/@sentry/browser/-/browser-5.7.1.tgz#1f8435e2a325d7a09f830065ebce40a2b3c708a4"
integrity sha512-K0x1XhsHS8PPdtlVOLrKZyYvi5Vexs9WApdd214bO6KaGF296gJvH1mG8XOY0+7aA5i2A7T3ttcaJNDYS49lzw==
dependencies:
"@sentry/core" "5.7.1"
"@sentry/types" "5.7.1"
"@sentry/utils" "5.7.1"
tslib "^1.9.3"
"@sentry/core@5.7.1":
version "5.7.1"
resolved "https://registry.yarnpkg.com/@sentry/core/-/core-5.7.1.tgz#3eb2b7662cac68245931ee939ec809bf7a639d0e"
integrity sha512-AOn3k3uVWh2VyajcHbV9Ta4ieDIeLckfo7UMLM+CTk2kt7C89SayDGayJMSsIrsZlL4qxBoLB9QY4W2FgAGJrg==
dependencies:
"@sentry/hub" "5.7.1"
"@sentry/minimal" "5.7.1"
"@sentry/types" "5.7.1"
"@sentry/utils" "5.7.1"
tslib "^1.9.3"
"@sentry/hub@5.7.1":
version "5.7.1"
resolved "https://registry.yarnpkg.com/@sentry/hub/-/hub-5.7.1.tgz#a52acd9fead7f3779d96e9965c6978aecc8b9cad"
integrity sha512-evGh323WR073WSBCg/RkhlUmCQyzU0xzBzCZPscvcoy5hd4SsLE6t9Zin+WACHB9JFsRQIDwNDn+D+pj3yKsig==
dependencies:
"@sentry/types" "5.7.1"
"@sentry/utils" "5.7.1"
tslib "^1.9.3"
"@sentry/minimal@5.7.1":
version "5.7.1"
resolved "https://registry.yarnpkg.com/@sentry/minimal/-/minimal-5.7.1.tgz#56afc537737586929e25349765e37a367958c1e1"
integrity sha512-nS/Dg+jWAZtcxQW8wKbkkw4dYvF6uyY/vDiz/jFCaux0LX0uhgXAC9gMOJmgJ/tYBLJ64l0ca5LzpZa7BMJQ0g==
dependencies:
"@sentry/hub" "5.7.1"
"@sentry/types" "5.7.1"
tslib "^1.9.3"
"@sentry/node@5.7.1":
version "5.7.1"
resolved "https://registry.yarnpkg.com/@sentry/node/-/node-5.7.1.tgz#94e2fbac94f6cc061be3bc14b22813536c59698d"
integrity sha512-hVM10asFStrOhYZzMqFM7V1lrHkr1ydc2n/SFG0ZmIQxfTjCVElyXV/BJASIdqadM1fFIvvtD/EfgkTcZmub1g==
dependencies:
"@sentry/core" "5.7.1"
"@sentry/hub" "5.7.1"
"@sentry/types" "5.7.1"
"@sentry/utils" "5.7.1"
cookie "^0.3.1"
https-proxy-agent "^3.0.0"
lru_map "^0.3.3"
tslib "^1.9.3"
"@sentry/types@5.7.1":
version "5.7.1"
resolved "https://registry.yarnpkg.com/@sentry/types/-/types-5.7.1.tgz#4c4c1d4d891b6b8c2c3c7b367d306a8b1350f090"
integrity sha512-tbUnTYlSliXvnou5D4C8Zr+7/wJrHLbpYX1YkLXuIJRU0NSi81bHMroAuHWILcQKWhVjaV/HZzr7Y/hhWtbXVQ==
"@sentry/utils@5.7.1":
version "5.7.1"
resolved "https://registry.yarnpkg.com/@sentry/utils/-/utils-5.7.1.tgz#cf37ad55f78e317665cd8680f202d307fa77f1d0"
integrity sha512-nhirUKj/qFLsR1i9kJ5BRvNyzdx/E2vorIsukuDrbo8e3iZ11JMgCOVrmC8Eq9YkHBqgwX4UnrPumjFyvGMZ2Q==
dependencies:
"@sentry/types" "5.7.1"
tslib "^1.9.3"
"@sindresorhus/is@^0.14.0": "@sindresorhus/is@^0.14.0":
version "0.14.0" version "0.14.0"
resolved "https://registry.yarnpkg.com/@sindresorhus/is/-/is-0.14.0.tgz#9fb3a3cf3132328151f353de4632e01e52102bea" resolved "https://registry.yarnpkg.com/@sindresorhus/is/-/is-0.14.0.tgz#9fb3a3cf3132328151f353de4632e01e52102bea"
...@@ -2886,6 +2952,13 @@ agent-base@4, agent-base@^4.1.0, agent-base@~4.2.1: ...@@ -2886,6 +2952,13 @@ agent-base@4, agent-base@^4.1.0, agent-base@~4.2.1:
dependencies: dependencies:
es6-promisify "^5.0.0" es6-promisify "^5.0.0"
agent-base@^4.3.0:
version "4.3.0"
resolved "https://registry.yarnpkg.com/agent-base/-/agent-base-4.3.0.tgz#8165f01c436009bccad0b1d122f05ed770efc6ee"
integrity sha512-salcGninV0nPrwpGNn4VTXBb1SOuXQBiqbrNXoeizJsHrsL6ERFM2Ne3JUSBWRE6aeNJI2ROP/WEEIDUiDe3cg==
dependencies:
es6-promisify "^5.0.0"
agentkeepalive@^3.4.1: agentkeepalive@^3.4.1:
version "3.5.2" version "3.5.2"
resolved "https://registry.yarnpkg.com/agentkeepalive/-/agentkeepalive-3.5.2.tgz#a113924dd3fa24a0bc3b78108c450c2abee00f67" resolved "https://registry.yarnpkg.com/agentkeepalive/-/agentkeepalive-3.5.2.tgz#a113924dd3fa24a0bc3b78108c450c2abee00f67"
...@@ -4705,6 +4778,11 @@ cookie@0.4.0: ...@@ -4705,6 +4778,11 @@ cookie@0.4.0:
resolved "https://registry.yarnpkg.com/cookie/-/cookie-0.4.0.tgz#beb437e7022b3b6d49019d088665303ebe9c14ba" resolved "https://registry.yarnpkg.com/cookie/-/cookie-0.4.0.tgz#beb437e7022b3b6d49019d088665303ebe9c14ba"
integrity sha512-+Hp8fLp57wnUSt0tY0tHEXh4voZRDnoIrZPqlo3DPiI4y9lwg/jqx+1Om94/W6ZaPDOUbnjOt/99w66zk+l1Xg== integrity sha512-+Hp8fLp57wnUSt0tY0tHEXh4voZRDnoIrZPqlo3DPiI4y9lwg/jqx+1Om94/W6ZaPDOUbnjOt/99w66zk+l1Xg==
cookie@^0.3.1:
version "0.3.1"
resolved "https://registry.yarnpkg.com/cookie/-/cookie-0.3.1.tgz#e7e0a1f9ef43b4c8ba925c5c5a96e806d16873bb"
integrity sha1-5+Ch+e9DtMi6klxcWpboBtFoc7s=
cookiejar@^2.1.0: cookiejar@^2.1.0:
version "2.1.2" version "2.1.2"
resolved "https://registry.yarnpkg.com/cookiejar/-/cookiejar-2.1.2.tgz#dd8a235530752f988f9a0844f3fc589e3111125c" resolved "https://registry.yarnpkg.com/cookiejar/-/cookiejar-2.1.2.tgz#dd8a235530752f988f9a0844f3fc589e3111125c"
...@@ -7627,6 +7705,14 @@ https-proxy-agent@^2.2.0, https-proxy-agent@^2.2.1: ...@@ -7627,6 +7705,14 @@ https-proxy-agent@^2.2.0, https-proxy-agent@^2.2.1:
agent-base "^4.1.0" agent-base "^4.1.0"
debug "^3.1.0" debug "^3.1.0"
https-proxy-agent@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/https-proxy-agent/-/https-proxy-agent-3.0.0.tgz#0106efa5d63d6d6f3ab87c999fa4877a3fd1ff97"
integrity sha512-y4jAxNEihqvBI5F3SaO2rtsjIOnnNA8sEbuiP+UhJZJHeM2NRm6c09ax2tgqme+SgUUvjao2fJXF4h3D6Cb2HQ==
dependencies:
agent-base "^4.3.0"
debug "^3.1.0"
humanize-ms@^1.2.1: humanize-ms@^1.2.1:
version "1.2.1" version "1.2.1"
resolved "https://registry.yarnpkg.com/humanize-ms/-/humanize-ms-1.2.1.tgz#c46e3159a293f6b896da29316d8b6fe8bb79bbed" resolved "https://registry.yarnpkg.com/humanize-ms/-/humanize-ms-1.2.1.tgz#c46e3159a293f6b896da29316d8b6fe8bb79bbed"
...@@ -9588,6 +9674,11 @@ lru-cache@^4.0.1, lru-cache@^4.1.2, lru-cache@^4.1.3: ...@@ -9588,6 +9674,11 @@ lru-cache@^4.0.1, lru-cache@^4.1.2, lru-cache@^4.1.3:
pseudomap "^1.0.2" pseudomap "^1.0.2"
yallist "^2.1.2" yallist "^2.1.2"
lru_map@^0.3.3:
version "0.3.3"
resolved "https://registry.yarnpkg.com/lru_map/-/lru_map-0.3.3.tgz#b5c8351b9464cbd750335a79650a0ec0e56118dd"
integrity sha1-tcg1G5Rky9dQM1p5ZQoOwOVhGN0=
macos-release@^2.2.0: macos-release@^2.2.0:
version "2.2.0" version "2.2.0"
resolved "https://registry.yarnpkg.com/macos-release/-/macos-release-2.2.0.tgz#ab58d55dd4714f0a05ad4b0e90f4370fef5cdea8" resolved "https://registry.yarnpkg.com/macos-release/-/macos-release-2.2.0.tgz#ab58d55dd4714f0a05ad4b0e90f4370fef5cdea8"
...@@ -14486,7 +14577,7 @@ ts-pnp@^1.1.2: ...@@ -14486,7 +14577,7 @@ ts-pnp@^1.1.2:
resolved "https://registry.yarnpkg.com/ts-pnp/-/ts-pnp-1.1.4.tgz#ae27126960ebaefb874c6d7fa4729729ab200d90" resolved "https://registry.yarnpkg.com/ts-pnp/-/ts-pnp-1.1.4.tgz#ae27126960ebaefb874c6d7fa4729729ab200d90"
integrity sha512-1J/vefLC+BWSo+qe8OnJQfWTYRS6ingxjwqmHMqaMxXMj7kFtKLgAaYW3JeX3mktjgUL+etlU8/B4VUAUI9QGw== integrity sha512-1J/vefLC+BWSo+qe8OnJQfWTYRS6ingxjwqmHMqaMxXMj7kFtKLgAaYW3JeX3mktjgUL+etlU8/B4VUAUI9QGw==
tslib@1.10.0: tslib@1.10.0, tslib@^1.9.3:
version "1.10.0" version "1.10.0"
resolved "https://registry.yarnpkg.com/tslib/-/tslib-1.10.0.tgz#c3c19f95973fb0a62973fb09d90d961ee43e5c8a" resolved "https://registry.yarnpkg.com/tslib/-/tslib-1.10.0.tgz#c3c19f95973fb0a62973fb09d90d961ee43e5c8a"
integrity sha512-qOebF53frne81cf0S9B41ByenJ3/IuH8yJKngAX35CmiZySA0khhkovshKK+jGCaMnVomla7gVlIcc3EvKPbTQ== integrity sha512-qOebF53frne81cf0S9B41ByenJ3/IuH8yJKngAX35CmiZySA0khhkovshKK+jGCaMnVomla7gVlIcc3EvKPbTQ==
......
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