rsnext/packages/next/build/webpack-config.ts

1113 lines
38 KiB
TypeScript
Raw Normal View History

import chalk from 'chalk'
import crypto from 'crypto'
import ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin'
import MiniCssExtractPlugin from 'mini-css-extract-plugin'
import path from 'path'
// @ts-ignore: Currently missing types
import PnpWebpackPlugin from 'pnp-webpack-plugin'
import webpack from 'webpack'
import {
DOT_NEXT_ALIAS,
NEXT_PROJECT_ROOT,
NEXT_PROJECT_ROOT_DIST_CLIENT,
PAGES_DIR_ALIAS,
} from '../lib/constants'
import { fileExists } from '../lib/file-exists'
import { resolveRequest } from '../lib/resolve-request'
import {
CLIENT_STATIC_FILES_RUNTIME_MAIN,
CLIENT_STATIC_FILES_RUNTIME_POLYFILLS,
CLIENT_STATIC_FILES_RUNTIME_WEBPACK,
REACT_LOADABLE_MANIFEST,
SERVER_DIRECTORY,
SERVERLESS_DIRECTORY,
} from '../next-server/lib/constants'
import { findPageFile } from '../server/lib/find-page-file'
import { WebpackEntrypoints } from './entries'
import {
collectPlugins,
PluginMetaData,
VALID_MIDDLEWARE,
} from './plugins/collect-plugins'
// @ts-ignore: JS file
import { pluginLoaderOptions } from './webpack/loaders/next-plugin-loader'
import BuildManifestPlugin from './webpack/plugins/build-manifest-plugin'
import ChunkNamesPlugin from './webpack/plugins/chunk-names-plugin'
import { CssMinimizerPlugin } from './webpack/plugins/css-minimizer-plugin'
import { importAutoDllPlugin } from './webpack/plugins/dll-import'
import { DropClientPage } from './webpack/plugins/next-drop-client-page-plugin'
import NextEsmPlugin from './webpack/plugins/next-esm-plugin'
import NextJsSsrImportPlugin from './webpack/plugins/nextjs-ssr-import'
import NextJsSSRModuleCachePlugin from './webpack/plugins/nextjs-ssr-module-cache'
import PagesManifestPlugin from './webpack/plugins/pages-manifest-plugin'
import { ProfilingPlugin } from './webpack/plugins/profiling-plugin'
import { ReactLoadablePlugin } from './webpack/plugins/react-loadable-plugin'
import { ServerlessPlugin } from './webpack/plugins/serverless-plugin'
import { TerserPlugin } from './webpack/plugins/terser-webpack-plugin/src/index'
type ExcludesFalse = <T>(x: T | false) => x is T
const escapePathVariables = (value: any) => {
return typeof value === 'string'
? value.replace(/\[(\\*[\w:]+\\*)\]/gi, '[\\$1\\]')
: value
}
function getOptimizedAliases(isServer: boolean): { [pkg: string]: string } {
if (isServer) {
return {}
}
const stubWindowFetch = path.join(__dirname, 'polyfills', 'fetch.js')
return {
__next_polyfill__fetch: require.resolve('whatwg-fetch'),
unfetch$: stubWindowFetch,
'isomorphic-unfetch$': stubWindowFetch,
'whatwg-fetch$': stubWindowFetch,
}
}
export default async function getBaseWebpackConfig(
dir: string,
{
buildId,
config,
dev = false,
isServer = false,
pagesDir,
tracer,
target = 'server',
entrypoints,
}: {
buildId: string
config: any
dev?: boolean
isServer?: boolean
pagesDir: string
target?: string
tracer?: any
entrypoints: WebpackEntrypoints
}
): Promise<webpack.Configuration> {
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
2019-11-01 20:13:13 +01:00
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)
Universal Webpack (#3578) * Speed up next build * Document webpack config * Speed up next build * Remove comment * Add comment * Clean up rules * Add comments * Run in parallel * Push plugins seperately * Create a new chunk for react * Don’t uglify react since it’s already uglified. Move react to commons in development * Use the minified version directly * Re-add globpattern * Move loaders into a separate variable * Add comment linking to Dan’s explanation * Remove dot * Add universal webpack * Initial dev support * Fix linting * Add changes from Arunoda's work * Made next dev works. But super slow and no HMR support. * Fix client side hot reload * Server side hmr * Only in dev * Add on-demand-entries client + hot-middleware * Add .babelrc support * Speed up on demand entries by running in parallel * Serve static generated files * Add missing config in dev * Add sass support * Add support for .map * Add cssloader config and fix .jsx support * Rename * use same defaults as css-loader. Fix linting * Add NoEmitErrorsPlugin * Add clientBootstrap * Use webpackhotmiddleware on the multi compiler * alpha.3 * Use babel 16.2.x * Fix reloading after error * Remove comment * Release 5.0.0-univeral-alpha.1 * Remove check for React 16 * Release 5.0.0-universal-alpha.2 * React hot loader v4 * Use our static file rendering machanism to serve pages. This should work well since the file path for a page is predictable. * Release 5.0.0-universal-alpha.3 * Remove optional loaders * Release 5.0.0-universal-alpha.4 * Remove clientBootstrap * Remove renderScript * Make sure pages bundles are served correctly * Remove unused import * Revert to using the same code as canary * Fix hot loader * Release 5.0.0-universal-alpha.5 * Check if externals dir exist before applying config * Add typescript support * Add support for transpiling certain packages in node_modules Thanks to @giuseppeg’s work in https://github.com/zeit/next.js/pull/3319 * Add BABEL_DISABLE_CACHE support * Make sourcemaps in production opt-in * Revert "Add support for transpiling certain packages in node_modules" This reverts commit d4b1d9babfb4b9ed4f4b12d56d52dee233e862da. In favor of a better api around this. * Support typescript through next.config.js * Remove comments * Bring back commons.js calculation * Remove unused dependencies * Move base.config.js to webpack.js * Make sure to only invalidate webpackDevMiddleware one after other. * Allow babel-loder caching by default. * Add comment about preact support * Bring back buildir replace * Remove obsolete plugin * Remove build replace, speed up build * Resolve page entries like pages/day/index.js to pages/day.js * Add componentDidCatch back * Compile to bundles * Use config.distDir everywhere * Make sure the file is an array * Remove console.log * Apply optimization to uglifyjs * Add comment pointing to source * Create entries the same way in dev and production * Remove unused and broken pagesGlobPattern * day/index.js is automatically turned into day.js at build time * Remove poweredByHeader option * Load pages with the correct path. * Release 5.0.0-universal-alpha.6 * Make sure react-dom/server can be overwritten by module-alias * Only add react-hot-loader babel plugin in dev * Release 5.0.0-universal-alpha.7 * Revert tests * Release 5.0.0-universal-alpha.10 * Make sure next/head is working properly. * Add wepack alias for 'next' back. * Make sure overriding className in next/head works * Alias react too * Add missing r * Fragment fallback has to wrap the children * Use min.js * Remove css.js * Remove wallaby.js * Release 5.0.0-universal-alpha.11 * Resolve relative to workdir instead of next * Make sure we touch the right file * Resolve next modules * Remove dotjsx removal plugins since we use webpack on the server * Revert "Resolve relative to workdir instead of next" This reverts commit a13f3e4ab565df9e2c9a3dfc8eb4009c0c2e02ed. * Externalize any locally loaded module lives outside of app dir. * Remove server aliases * Check node_modules reliably * Add symlink to next for tests * Make sure dynamic imports work locally. This is why we need it: https://github.com/webpack/webpack/blob/b545b519b2024e3f8be3041385bd326bf5d24449/lib/MainTemplate.js#L68 We need to have the finally clause in the above in __webpack_require__. webpack output option strictModuleExceptionHandling does that. * dynmaic -> dynamic * Remove webpack-node-externals * Make sure dynamic imports support SSR. * Remove css support in favor of next-css * Make sure we load path from `/` since it’s included in the path matching * Catch when ensurepage couldn’t be fulfilled for `.js.map` * Register require cache flusher for both client and server * Add comment explaining this is to facilitate hot reloading * Only load module when needed * Remove unused modules * Release 5.0.0-universal-alpha.12 * Only log the `found babel` message once * Make sure ondemand entries working correctly. Now we are just using a single instance of OnDemandEntryHandler. * Better sourcemaps * Release 5.0.0-universal-alpha.13 * Lock uglify version to 1.1.6 * Release 5.0.0-universal-alpha.14 * Fix a typo. * Introduce multi-zones support for mircofrontends * Add section on css
2018-01-30 16:40:52 +01:00
const defaultLoaders = {
babel: {
loader: 'next-babel-loader',
options: {
isServer,
distDir,
pagesDir,
cwd: dir,
cache: true,
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
2019-11-01 20:13:13 +01:00
babelPresetPlugins,
hasModern: !!config.experimental.modern,
},
},
// Backwards compat
hotSelfAccept: {
loader: 'noop-loader',
},
Universal Webpack (#3578) * Speed up next build * Document webpack config * Speed up next build * Remove comment * Add comment * Clean up rules * Add comments * Run in parallel * Push plugins seperately * Create a new chunk for react * Don’t uglify react since it’s already uglified. Move react to commons in development * Use the minified version directly * Re-add globpattern * Move loaders into a separate variable * Add comment linking to Dan’s explanation * Remove dot * Add universal webpack * Initial dev support * Fix linting * Add changes from Arunoda's work * Made next dev works. But super slow and no HMR support. * Fix client side hot reload * Server side hmr * Only in dev * Add on-demand-entries client + hot-middleware * Add .babelrc support * Speed up on demand entries by running in parallel * Serve static generated files * Add missing config in dev * Add sass support * Add support for .map * Add cssloader config and fix .jsx support * Rename * use same defaults as css-loader. Fix linting * Add NoEmitErrorsPlugin * Add clientBootstrap * Use webpackhotmiddleware on the multi compiler * alpha.3 * Use babel 16.2.x * Fix reloading after error * Remove comment * Release 5.0.0-univeral-alpha.1 * Remove check for React 16 * Release 5.0.0-universal-alpha.2 * React hot loader v4 * Use our static file rendering machanism to serve pages. This should work well since the file path for a page is predictable. * Release 5.0.0-universal-alpha.3 * Remove optional loaders * Release 5.0.0-universal-alpha.4 * Remove clientBootstrap * Remove renderScript * Make sure pages bundles are served correctly * Remove unused import * Revert to using the same code as canary * Fix hot loader * Release 5.0.0-universal-alpha.5 * Check if externals dir exist before applying config * Add typescript support * Add support for transpiling certain packages in node_modules Thanks to @giuseppeg’s work in https://github.com/zeit/next.js/pull/3319 * Add BABEL_DISABLE_CACHE support * Make sourcemaps in production opt-in * Revert "Add support for transpiling certain packages in node_modules" This reverts commit d4b1d9babfb4b9ed4f4b12d56d52dee233e862da. In favor of a better api around this. * Support typescript through next.config.js * Remove comments * Bring back commons.js calculation * Remove unused dependencies * Move base.config.js to webpack.js * Make sure to only invalidate webpackDevMiddleware one after other. * Allow babel-loder caching by default. * Add comment about preact support * Bring back buildir replace * Remove obsolete plugin * Remove build replace, speed up build * Resolve page entries like pages/day/index.js to pages/day.js * Add componentDidCatch back * Compile to bundles * Use config.distDir everywhere * Make sure the file is an array * Remove console.log * Apply optimization to uglifyjs * Add comment pointing to source * Create entries the same way in dev and production * Remove unused and broken pagesGlobPattern * day/index.js is automatically turned into day.js at build time * Remove poweredByHeader option * Load pages with the correct path. * Release 5.0.0-universal-alpha.6 * Make sure react-dom/server can be overwritten by module-alias * Only add react-hot-loader babel plugin in dev * Release 5.0.0-universal-alpha.7 * Revert tests * Release 5.0.0-universal-alpha.10 * Make sure next/head is working properly. * Add wepack alias for 'next' back. * Make sure overriding className in next/head works * Alias react too * Add missing r * Fragment fallback has to wrap the children * Use min.js * Remove css.js * Remove wallaby.js * Release 5.0.0-universal-alpha.11 * Resolve relative to workdir instead of next * Make sure we touch the right file * Resolve next modules * Remove dotjsx removal plugins since we use webpack on the server * Revert "Resolve relative to workdir instead of next" This reverts commit a13f3e4ab565df9e2c9a3dfc8eb4009c0c2e02ed. * Externalize any locally loaded module lives outside of app dir. * Remove server aliases * Check node_modules reliably * Add symlink to next for tests * Make sure dynamic imports work locally. This is why we need it: https://github.com/webpack/webpack/blob/b545b519b2024e3f8be3041385bd326bf5d24449/lib/MainTemplate.js#L68 We need to have the finally clause in the above in __webpack_require__. webpack output option strictModuleExceptionHandling does that. * dynmaic -> dynamic * Remove webpack-node-externals * Make sure dynamic imports support SSR. * Remove css support in favor of next-css * Make sure we load path from `/` since it’s included in the path matching * Catch when ensurepage couldn’t be fulfilled for `.js.map` * Register require cache flusher for both client and server * Add comment explaining this is to facilitate hot reloading * Only load module when needed * Remove unused modules * Release 5.0.0-universal-alpha.12 * Only log the `found babel` message once * Make sure ondemand entries working correctly. Now we are just using a single instance of OnDemandEntryHandler. * Better sourcemaps * Release 5.0.0-universal-alpha.13 * Lock uglify version to 1.1.6 * Release 5.0.0-universal-alpha.14 * Fix a typo. * Introduce multi-zones support for mircofrontends * Add section on css
2018-01-30 16:40:52 +01:00
}
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
2019-11-01 20:13:13 +01:00
const babelIncludeRegexes: RegExp[] = [
/next[\\/]dist[\\/]next-server[\\/]lib/,
/next[\\/]dist[\\/]client/,
/next[\\/]dist[\\/]pages/,
/[\\/](strip-ansi|ansi-regex)[\\/]/,
...(config.experimental.plugins
2019-11-02 04:06:34 +01:00
? VALID_MIDDLEWARE.map(name => new RegExp(`src(\\\\|/)${name}`))
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
2019-11-01 20:13:13 +01:00
: []),
]
2018-02-01 16:21:18 +01:00
// Support for NODE_PATH
const nodePathList = (process.env.NODE_PATH || '')
.split(process.platform === 'win32' ? ';' : ':')
.filter(p => !!p)
2018-02-01 16:21:18 +01:00
const isServerless = target === 'serverless'
const isServerlessTrace = target === 'experimental-serverless-trace'
// Intentionally not using isTargetLikeServerless helper
const isLikeServerless = isServerless || isServerlessTrace
const outputDir = isLikeServerless ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY
Serverless Next.js (#5927) **This does not change existing behavior.** building to serverless is completely opt-in. - Implements `target: 'serverless'` in `next.config.js` - Removes `next build --lambdas` (was only available on next@canary so far) This implements the concept of build targets. Currently there will be 2 build targets: - server (This is the target that already existed / the default, no changes here) - serverless (New target aimed at compiling pages to serverless handlers) The serverless target will output a single file per `page` in the `pages` directory: - `pages/index.js` => `.next/serverless/index.js` - `pages/about.js` => `.next/serverless/about.js` So what is inside `.next/serverless/about.js`? All the code needed to render that specific page. It has the Node.js `http.Server` request handler function signature: ```ts (req: http.IncomingMessage, res: http.ServerResponse) => void ``` So how do you use it? Generally you **don't** want to use the below example, but for illustration purposes it's shown how the handler is called using a plain `http.Server`: ```js const http = require('http') // Note that `.default` is needed because the exported module is an esmodule const handler = require('./.next/serverless/about.js').default const server = new http.Server((req, res) => handler(req, res)) server.listen(3000, () => console.log('Listening on http://localhost:3000')) ``` Generally you'll upload this handler function to an external service like [Now v2](https://zeit.co/now-2), the `@now/next` builder will be updated to reflect these changes. This means that it'll be no longer neccesary for `@now/next` to do some of the guesswork in creating smaller handler functions. As Next.js will output the smallest possible serverless handler function automatically. The function has 0 dependencies so no node_modules are required to run it, and is generally very small. 45Kb zipped is the baseline, but I'm sure we can make it even smaller in the future. One important thing to note is that the function won't try to load `next.config.js`, so `publicRuntimeConfig` / `serverRuntimeConfig` are not supported. Reasons are outlined here: #5846 So to summarize: - every page becomes a serverless function - the serverless function has 0 dependencies (they're all inlined) - "just" uses the `req` and `res` coming from Node.js - opt-in using `target: 'serverless'` in `next.config.js` - Does not load next.config.js when executing the function TODO: - [x] Compile next/dynamic / `import()` into the function file, so that no extra files have to be uploaded. - [x] Setting `assetPrefix` at build time for serverless target - [x] Support custom /_app - [x] Support custom /_document - [x] Support custom /_error - [x] Add `next.config.js` property for `target` Need discussion: - [ ] Since the serverless target won't support `publicRuntimeConfig` / `serverRuntimeConfig` as they're runtime values. I think we should support build-time env var replacement with webpack.DefinePlugin or similar. - [ ] Serving static files with the correct cache-control, as there is no static file serving in the serverless target
2018-12-28 11:39:12 +01:00
const outputPath = path.join(distDir, isServer ? outputDir : '')
const totalPages = Object.keys(entrypoints).length
const clientEntries = !isServer
? {
// Backwards compatibility
'main.js': [],
[CLIENT_STATIC_FILES_RUNTIME_MAIN]:
`.${path.sep}` +
path.relative(
dir,
path.join(
NEXT_PROJECT_ROOT_DIST_CLIENT,
dev ? `next-dev.js` : 'next.js'
)
),
[CLIENT_STATIC_FILES_RUNTIME_POLYFILLS]: path.join(
NEXT_PROJECT_ROOT_DIST_CLIENT,
'polyfills.js'
),
}
: undefined
2016-10-19 14:41:45 +02:00
let typeScriptPath
try {
typeScriptPath = resolveRequest('typescript', `${dir}/`)
} catch (_) {}
const tsConfigPath = path.join(dir, 'tsconfig.json')
const useTypeScript = Boolean(
typeScriptPath && (await fileExists(tsConfigPath))
)
const ignoreTypeScriptErrors = dev
? config.typescript && config.typescript.ignoreDevErrors
: config.typescript && config.typescript.ignoreBuildErrors
const resolveConfig = {
// Disable .mjs for node_modules bundling
extensions: isServer
? [
...(useTypeScript ? ['.tsx', '.ts'] : []),
'.js',
'.mjs',
'.jsx',
'.json',
'.wasm',
]
: [
...(useTypeScript ? ['.tsx', '.ts'] : []),
'.mjs',
'.js',
'.jsx',
'.json',
'.wasm',
],
modules: [
'node_modules',
...nodePathList, // Support for NODE_PATH environment variable
],
alias: {
// These aliases make sure the wrapper module is not included in the bundles
// Which makes bundles slightly smaller, but also skips parsing a module that we know will result in this alias
'next/head': 'next/dist/next-server/lib/head.js',
'next/router': 'next/dist/client/router.js',
'next/config': 'next/dist/next-server/lib/runtime-config.js',
'next/dynamic': 'next/dist/next-server/lib/dynamic.js',
Serverless Next.js (#5927) **This does not change existing behavior.** building to serverless is completely opt-in. - Implements `target: 'serverless'` in `next.config.js` - Removes `next build --lambdas` (was only available on next@canary so far) This implements the concept of build targets. Currently there will be 2 build targets: - server (This is the target that already existed / the default, no changes here) - serverless (New target aimed at compiling pages to serverless handlers) The serverless target will output a single file per `page` in the `pages` directory: - `pages/index.js` => `.next/serverless/index.js` - `pages/about.js` => `.next/serverless/about.js` So what is inside `.next/serverless/about.js`? All the code needed to render that specific page. It has the Node.js `http.Server` request handler function signature: ```ts (req: http.IncomingMessage, res: http.ServerResponse) => void ``` So how do you use it? Generally you **don't** want to use the below example, but for illustration purposes it's shown how the handler is called using a plain `http.Server`: ```js const http = require('http') // Note that `.default` is needed because the exported module is an esmodule const handler = require('./.next/serverless/about.js').default const server = new http.Server((req, res) => handler(req, res)) server.listen(3000, () => console.log('Listening on http://localhost:3000')) ``` Generally you'll upload this handler function to an external service like [Now v2](https://zeit.co/now-2), the `@now/next` builder will be updated to reflect these changes. This means that it'll be no longer neccesary for `@now/next` to do some of the guesswork in creating smaller handler functions. As Next.js will output the smallest possible serverless handler function automatically. The function has 0 dependencies so no node_modules are required to run it, and is generally very small. 45Kb zipped is the baseline, but I'm sure we can make it even smaller in the future. One important thing to note is that the function won't try to load `next.config.js`, so `publicRuntimeConfig` / `serverRuntimeConfig` are not supported. Reasons are outlined here: #5846 So to summarize: - every page becomes a serverless function - the serverless function has 0 dependencies (they're all inlined) - "just" uses the `req` and `res` coming from Node.js - opt-in using `target: 'serverless'` in `next.config.js` - Does not load next.config.js when executing the function TODO: - [x] Compile next/dynamic / `import()` into the function file, so that no extra files have to be uploaded. - [x] Setting `assetPrefix` at build time for serverless target - [x] Support custom /_app - [x] Support custom /_document - [x] Support custom /_error - [x] Add `next.config.js` property for `target` Need discussion: - [ ] Since the serverless target won't support `publicRuntimeConfig` / `serverRuntimeConfig` as they're runtime values. I think we should support build-time env var replacement with webpack.DefinePlugin or similar. - [ ] Serving static files with the correct cache-control, as there is no static file serving in the serverless target
2018-12-28 11:39:12 +01:00
next: NEXT_PROJECT_ROOT,
[PAGES_DIR_ALIAS]: pagesDir,
[DOT_NEXT_ALIAS]: distDir,
...getOptimizedAliases(isServer),
},
mainFields: isServer ? ['main', 'module'] : ['browser', 'module', 'main'],
plugins: [PnpWebpackPlugin],
}
2018-08-30 12:27:22 +02:00
const webpackMode = dev ? 'development' : 'production'
const terserPluginConfig = {
cache: true,
cpus: config.experimental.cpus,
distDir: distDir,
parallel: true,
sourceMap: false,
workerThreads: config.experimental.workerThreads,
}
const terserOptions = {
parse: {
ecma: 8,
},
compress: {
ecma: 5,
warnings: false,
// The following two options are known to break valid JavaScript code
comparisons: false,
inline: 2, // https://github.com/zeit/next.js/issues/7178#issuecomment-493048965
},
mangle: { safari10: true },
output: {
ecma: 5,
safari10: true,
comments: false,
// Fixes usage of Emoji and certain Regex
ascii_only: true,
},
}
2019-07-01 19:13:06 +02:00
const devtool = dev ? 'cheap-module-source-map' : false
// Contains various versions of the Webpack SplitChunksPlugin used in different build types
const splitChunksConfigs: {
[propName: string]: webpack.Options.SplitChunksOptions
} = {
dev: {
cacheGroups: {
default: false,
vendors: false,
},
},
prod: {
chunks: 'all',
cacheGroups: {
default: false,
vendors: false,
commons: {
name: 'commons',
chunks: 'all',
minChunks: totalPages > 2 ? totalPages * 0.5 : 2,
},
react: {
name: 'commons',
chunks: 'all',
test: /[\\/]node_modules[\\/](react|react-dom|scheduler|use-subscription)[\\/]/,
},
},
},
Experimental: Granular build chunking (#7696) * Refactor SplitChunksPlugin configs and add experimental chunking strategy * Use typeDefs for SplitChunksConfig * Modify build manifest plugin to create runtime build manifest * Add support for granular chunks to page-loader * Ensure normal behavior if experimental granularChunks flag is false * Update client build manifest to remove iife & implicit global * Factor out '/_next/' prepending into getDependencies * Update packages/next/build/webpack-config.ts filepath regex Co-Authored-By: Jason Miller <developit@users.noreply.github.com> * Simplify dependency load ordering in page-loader.js * Use SHA1 hash to shorten filenames for dependency modules * Add scheduler to framework cacheGroup in webpack-config * Update page loader to not duplicate script tags with query parameters * Ensure no slashes end up in the file hashes * Add prop-types to framework chunk * Fix issue with mis-attributed events * Increase modern build size budget--possibly decrement after consulting with @janicklasralph * Use module.rawRequest for lib chunks Co-Authored-By: Daniel Stockman <daniel.stockman@gmail.com> * Dasherize lib chunk names Co-Authored-By: Daniel Stockman <daniel.stockman@gmail.com> * Fix typescript errors, reorganize lib name logic * Dasherize rawRequest, short circuit name logic when rawRequest found * Add `scheduler` package to test regex * Fix a nit * Adjust build manifest plugin * Shorten key name * Extract createPreloadLink helper * Extract getDependencies helper * Move method * Minimize diff * Minimize diff x2 * Fix Array.from polyfill * Simplify page loader code * Remove async=false for script tags * Code golf `getDependencies` implementation * Require lib chunks be in node_modules * Update packages/next/build/webpack-config.ts Co-Authored-By: Joe Haddad <timer150@gmail.com> * Replace remaining missed windows compat regex * Trim client manifest * Prevent duplicate link preload tags * Revert size test changes * Squash manifest size even further * Add comment for clarity * Code golfing 🏌️‍♂️ * Correctly select modern dependencies * Ship separate modern client manifest when module/module enabled * Update packages/next/build/webpack/plugins/build-manifest-plugin.ts Co-Authored-By: Joe Haddad <timer150@gmail.com> * Remove unneccessary filter from page-loader * Add lookbehind to file extension regex in page-loader * v9.0.3 * Update examples for Apollo with AppTree (#8180) * Update examples for Apollo with AppTree * Fix apolloClient being overwritten when rendering AppTree * Golf page-loader (#8190) * Remove lookbehind for module replacement * Wait for build manifest promise before page load or prefetch * Updating modern-only chunks inside the right entry point * Fixing ts errors * Rename variable * Revert "Wait for build manifest promise before page load or prefetch" This reverts commit c370528c6888ba7fa71162a0854534ed280224ef. * Use proper typedef for webpack chunk * Re-enable promisified client build manifest * Fix bug in getDependencies map * Insert check for granularChunks in page-loader * Increase size limit temporarily for granular chunks * Add 50ms delay to flaky test * Set env.__NEXT_GRANULAR_CHUNKS in webpack config * Reset size limit to 187 * Set process.env.__NEXT_GRANULAR_CHUNKS to false if selectivePageBuilding * Update test/integration/production/test/index.test.js Co-Authored-By: Joe Haddad <timer150@gmail.com> * Do not create promise if not using chunking PR
2019-08-08 19:14:33 +02:00
prodGranular: {
chunks: 'all',
Experimental: Granular build chunking (#7696) * Refactor SplitChunksPlugin configs and add experimental chunking strategy * Use typeDefs for SplitChunksConfig * Modify build manifest plugin to create runtime build manifest * Add support for granular chunks to page-loader * Ensure normal behavior if experimental granularChunks flag is false * Update client build manifest to remove iife & implicit global * Factor out '/_next/' prepending into getDependencies * Update packages/next/build/webpack-config.ts filepath regex Co-Authored-By: Jason Miller <developit@users.noreply.github.com> * Simplify dependency load ordering in page-loader.js * Use SHA1 hash to shorten filenames for dependency modules * Add scheduler to framework cacheGroup in webpack-config * Update page loader to not duplicate script tags with query parameters * Ensure no slashes end up in the file hashes * Add prop-types to framework chunk * Fix issue with mis-attributed events * Increase modern build size budget--possibly decrement after consulting with @janicklasralph * Use module.rawRequest for lib chunks Co-Authored-By: Daniel Stockman <daniel.stockman@gmail.com> * Dasherize lib chunk names Co-Authored-By: Daniel Stockman <daniel.stockman@gmail.com> * Fix typescript errors, reorganize lib name logic * Dasherize rawRequest, short circuit name logic when rawRequest found * Add `scheduler` package to test regex * Fix a nit * Adjust build manifest plugin * Shorten key name * Extract createPreloadLink helper * Extract getDependencies helper * Move method * Minimize diff * Minimize diff x2 * Fix Array.from polyfill * Simplify page loader code * Remove async=false for script tags * Code golf `getDependencies` implementation * Require lib chunks be in node_modules * Update packages/next/build/webpack-config.ts Co-Authored-By: Joe Haddad <timer150@gmail.com> * Replace remaining missed windows compat regex * Trim client manifest * Prevent duplicate link preload tags * Revert size test changes * Squash manifest size even further * Add comment for clarity * Code golfing 🏌️‍♂️ * Correctly select modern dependencies * Ship separate modern client manifest when module/module enabled * Update packages/next/build/webpack/plugins/build-manifest-plugin.ts Co-Authored-By: Joe Haddad <timer150@gmail.com> * Remove unneccessary filter from page-loader * Add lookbehind to file extension regex in page-loader * v9.0.3 * Update examples for Apollo with AppTree (#8180) * Update examples for Apollo with AppTree * Fix apolloClient being overwritten when rendering AppTree * Golf page-loader (#8190) * Remove lookbehind for module replacement * Wait for build manifest promise before page load or prefetch * Updating modern-only chunks inside the right entry point * Fixing ts errors * Rename variable * Revert "Wait for build manifest promise before page load or prefetch" This reverts commit c370528c6888ba7fa71162a0854534ed280224ef. * Use proper typedef for webpack chunk * Re-enable promisified client build manifest * Fix bug in getDependencies map * Insert check for granularChunks in page-loader * Increase size limit temporarily for granular chunks * Add 50ms delay to flaky test * Set env.__NEXT_GRANULAR_CHUNKS in webpack config * Reset size limit to 187 * Set process.env.__NEXT_GRANULAR_CHUNKS to false if selectivePageBuilding * Update test/integration/production/test/index.test.js Co-Authored-By: Joe Haddad <timer150@gmail.com> * Do not create promise if not using chunking PR
2019-08-08 19:14:33 +02:00
cacheGroups: {
default: false,
vendors: false,
framework: {
chunks: 'all',
Experimental: Granular build chunking (#7696) * Refactor SplitChunksPlugin configs and add experimental chunking strategy * Use typeDefs for SplitChunksConfig * Modify build manifest plugin to create runtime build manifest * Add support for granular chunks to page-loader * Ensure normal behavior if experimental granularChunks flag is false * Update client build manifest to remove iife & implicit global * Factor out '/_next/' prepending into getDependencies * Update packages/next/build/webpack-config.ts filepath regex Co-Authored-By: Jason Miller <developit@users.noreply.github.com> * Simplify dependency load ordering in page-loader.js * Use SHA1 hash to shorten filenames for dependency modules * Add scheduler to framework cacheGroup in webpack-config * Update page loader to not duplicate script tags with query parameters * Ensure no slashes end up in the file hashes * Add prop-types to framework chunk * Fix issue with mis-attributed events * Increase modern build size budget--possibly decrement after consulting with @janicklasralph * Use module.rawRequest for lib chunks Co-Authored-By: Daniel Stockman <daniel.stockman@gmail.com> * Dasherize lib chunk names Co-Authored-By: Daniel Stockman <daniel.stockman@gmail.com> * Fix typescript errors, reorganize lib name logic * Dasherize rawRequest, short circuit name logic when rawRequest found * Add `scheduler` package to test regex * Fix a nit * Adjust build manifest plugin * Shorten key name * Extract createPreloadLink helper * Extract getDependencies helper * Move method * Minimize diff * Minimize diff x2 * Fix Array.from polyfill * Simplify page loader code * Remove async=false for script tags * Code golf `getDependencies` implementation * Require lib chunks be in node_modules * Update packages/next/build/webpack-config.ts Co-Authored-By: Joe Haddad <timer150@gmail.com> * Replace remaining missed windows compat regex * Trim client manifest * Prevent duplicate link preload tags * Revert size test changes * Squash manifest size even further * Add comment for clarity * Code golfing 🏌️‍♂️ * Correctly select modern dependencies * Ship separate modern client manifest when module/module enabled * Update packages/next/build/webpack/plugins/build-manifest-plugin.ts Co-Authored-By: Joe Haddad <timer150@gmail.com> * Remove unneccessary filter from page-loader * Add lookbehind to file extension regex in page-loader * v9.0.3 * Update examples for Apollo with AppTree (#8180) * Update examples for Apollo with AppTree * Fix apolloClient being overwritten when rendering AppTree * Golf page-loader (#8190) * Remove lookbehind for module replacement * Wait for build manifest promise before page load or prefetch * Updating modern-only chunks inside the right entry point * Fixing ts errors * Rename variable * Revert "Wait for build manifest promise before page load or prefetch" This reverts commit c370528c6888ba7fa71162a0854534ed280224ef. * Use proper typedef for webpack chunk * Re-enable promisified client build manifest * Fix bug in getDependencies map * Insert check for granularChunks in page-loader * Increase size limit temporarily for granular chunks * Add 50ms delay to flaky test * Set env.__NEXT_GRANULAR_CHUNKS in webpack config * Reset size limit to 187 * Set process.env.__NEXT_GRANULAR_CHUNKS to false if selectivePageBuilding * Update test/integration/production/test/index.test.js Co-Authored-By: Joe Haddad <timer150@gmail.com> * Do not create promise if not using chunking PR
2019-08-08 19:14:33 +02:00
name: 'framework',
// This regex ignores nested copies of framework libraries so they're
// bundled with their issuer.
// https://github.com/zeit/next.js/pull/9012
test: /(?<!node_modules.*)[\\/]node_modules[\\/](react|react-dom|scheduler|prop-types|use-subscription)[\\/]/,
Experimental: Granular build chunking (#7696) * Refactor SplitChunksPlugin configs and add experimental chunking strategy * Use typeDefs for SplitChunksConfig * Modify build manifest plugin to create runtime build manifest * Add support for granular chunks to page-loader * Ensure normal behavior if experimental granularChunks flag is false * Update client build manifest to remove iife & implicit global * Factor out '/_next/' prepending into getDependencies * Update packages/next/build/webpack-config.ts filepath regex Co-Authored-By: Jason Miller <developit@users.noreply.github.com> * Simplify dependency load ordering in page-loader.js * Use SHA1 hash to shorten filenames for dependency modules * Add scheduler to framework cacheGroup in webpack-config * Update page loader to not duplicate script tags with query parameters * Ensure no slashes end up in the file hashes * Add prop-types to framework chunk * Fix issue with mis-attributed events * Increase modern build size budget--possibly decrement after consulting with @janicklasralph * Use module.rawRequest for lib chunks Co-Authored-By: Daniel Stockman <daniel.stockman@gmail.com> * Dasherize lib chunk names Co-Authored-By: Daniel Stockman <daniel.stockman@gmail.com> * Fix typescript errors, reorganize lib name logic * Dasherize rawRequest, short circuit name logic when rawRequest found * Add `scheduler` package to test regex * Fix a nit * Adjust build manifest plugin * Shorten key name * Extract createPreloadLink helper * Extract getDependencies helper * Move method * Minimize diff * Minimize diff x2 * Fix Array.from polyfill * Simplify page loader code * Remove async=false for script tags * Code golf `getDependencies` implementation * Require lib chunks be in node_modules * Update packages/next/build/webpack-config.ts Co-Authored-By: Joe Haddad <timer150@gmail.com> * Replace remaining missed windows compat regex * Trim client manifest * Prevent duplicate link preload tags * Revert size test changes * Squash manifest size even further * Add comment for clarity * Code golfing 🏌️‍♂️ * Correctly select modern dependencies * Ship separate modern client manifest when module/module enabled * Update packages/next/build/webpack/plugins/build-manifest-plugin.ts Co-Authored-By: Joe Haddad <timer150@gmail.com> * Remove unneccessary filter from page-loader * Add lookbehind to file extension regex in page-loader * v9.0.3 * Update examples for Apollo with AppTree (#8180) * Update examples for Apollo with AppTree * Fix apolloClient being overwritten when rendering AppTree * Golf page-loader (#8190) * Remove lookbehind for module replacement * Wait for build manifest promise before page load or prefetch * Updating modern-only chunks inside the right entry point * Fixing ts errors * Rename variable * Revert "Wait for build manifest promise before page load or prefetch" This reverts commit c370528c6888ba7fa71162a0854534ed280224ef. * Use proper typedef for webpack chunk * Re-enable promisified client build manifest * Fix bug in getDependencies map * Insert check for granularChunks in page-loader * Increase size limit temporarily for granular chunks * Add 50ms delay to flaky test * Set env.__NEXT_GRANULAR_CHUNKS in webpack config * Reset size limit to 187 * Set process.env.__NEXT_GRANULAR_CHUNKS to false if selectivePageBuilding * Update test/integration/production/test/index.test.js Co-Authored-By: Joe Haddad <timer150@gmail.com> * Do not create promise if not using chunking PR
2019-08-08 19:14:33 +02:00
priority: 40,
2019-11-04 17:25:14 +01:00
// Don't let webpack eliminate this chunk (prevents this chunk from
// becoming a part of the commons chunk)
enforce: true,
Experimental: Granular build chunking (#7696) * Refactor SplitChunksPlugin configs and add experimental chunking strategy * Use typeDefs for SplitChunksConfig * Modify build manifest plugin to create runtime build manifest * Add support for granular chunks to page-loader * Ensure normal behavior if experimental granularChunks flag is false * Update client build manifest to remove iife & implicit global * Factor out '/_next/' prepending into getDependencies * Update packages/next/build/webpack-config.ts filepath regex Co-Authored-By: Jason Miller <developit@users.noreply.github.com> * Simplify dependency load ordering in page-loader.js * Use SHA1 hash to shorten filenames for dependency modules * Add scheduler to framework cacheGroup in webpack-config * Update page loader to not duplicate script tags with query parameters * Ensure no slashes end up in the file hashes * Add prop-types to framework chunk * Fix issue with mis-attributed events * Increase modern build size budget--possibly decrement after consulting with @janicklasralph * Use module.rawRequest for lib chunks Co-Authored-By: Daniel Stockman <daniel.stockman@gmail.com> * Dasherize lib chunk names Co-Authored-By: Daniel Stockman <daniel.stockman@gmail.com> * Fix typescript errors, reorganize lib name logic * Dasherize rawRequest, short circuit name logic when rawRequest found * Add `scheduler` package to test regex * Fix a nit * Adjust build manifest plugin * Shorten key name * Extract createPreloadLink helper * Extract getDependencies helper * Move method * Minimize diff * Minimize diff x2 * Fix Array.from polyfill * Simplify page loader code * Remove async=false for script tags * Code golf `getDependencies` implementation * Require lib chunks be in node_modules * Update packages/next/build/webpack-config.ts Co-Authored-By: Joe Haddad <timer150@gmail.com> * Replace remaining missed windows compat regex * Trim client manifest * Prevent duplicate link preload tags * Revert size test changes * Squash manifest size even further * Add comment for clarity * Code golfing 🏌️‍♂️ * Correctly select modern dependencies * Ship separate modern client manifest when module/module enabled * Update packages/next/build/webpack/plugins/build-manifest-plugin.ts Co-Authored-By: Joe Haddad <timer150@gmail.com> * Remove unneccessary filter from page-loader * Add lookbehind to file extension regex in page-loader * v9.0.3 * Update examples for Apollo with AppTree (#8180) * Update examples for Apollo with AppTree * Fix apolloClient being overwritten when rendering AppTree * Golf page-loader (#8190) * Remove lookbehind for module replacement * Wait for build manifest promise before page load or prefetch * Updating modern-only chunks inside the right entry point * Fixing ts errors * Rename variable * Revert "Wait for build manifest promise before page load or prefetch" This reverts commit c370528c6888ba7fa71162a0854534ed280224ef. * Use proper typedef for webpack chunk * Re-enable promisified client build manifest * Fix bug in getDependencies map * Insert check for granularChunks in page-loader * Increase size limit temporarily for granular chunks * Add 50ms delay to flaky test * Set env.__NEXT_GRANULAR_CHUNKS in webpack config * Reset size limit to 187 * Set process.env.__NEXT_GRANULAR_CHUNKS to false if selectivePageBuilding * Update test/integration/production/test/index.test.js Co-Authored-By: Joe Haddad <timer150@gmail.com> * Do not create promise if not using chunking PR
2019-08-08 19:14:33 +02:00
},
lib: {
test(module: { size: Function; identifier: Function }): boolean {
return (
module.size() > 160000 &&
/node_modules[/\\]/.test(module.identifier())
)
},
name(module: { libIdent: Function }): string {
return crypto
.createHash('sha1')
.update(module.libIdent({ context: dir }))
.digest('hex')
.substring(0, 8)
Experimental: Granular build chunking (#7696) * Refactor SplitChunksPlugin configs and add experimental chunking strategy * Use typeDefs for SplitChunksConfig * Modify build manifest plugin to create runtime build manifest * Add support for granular chunks to page-loader * Ensure normal behavior if experimental granularChunks flag is false * Update client build manifest to remove iife & implicit global * Factor out '/_next/' prepending into getDependencies * Update packages/next/build/webpack-config.ts filepath regex Co-Authored-By: Jason Miller <developit@users.noreply.github.com> * Simplify dependency load ordering in page-loader.js * Use SHA1 hash to shorten filenames for dependency modules * Add scheduler to framework cacheGroup in webpack-config * Update page loader to not duplicate script tags with query parameters * Ensure no slashes end up in the file hashes * Add prop-types to framework chunk * Fix issue with mis-attributed events * Increase modern build size budget--possibly decrement after consulting with @janicklasralph * Use module.rawRequest for lib chunks Co-Authored-By: Daniel Stockman <daniel.stockman@gmail.com> * Dasherize lib chunk names Co-Authored-By: Daniel Stockman <daniel.stockman@gmail.com> * Fix typescript errors, reorganize lib name logic * Dasherize rawRequest, short circuit name logic when rawRequest found * Add `scheduler` package to test regex * Fix a nit * Adjust build manifest plugin * Shorten key name * Extract createPreloadLink helper * Extract getDependencies helper * Move method * Minimize diff * Minimize diff x2 * Fix Array.from polyfill * Simplify page loader code * Remove async=false for script tags * Code golf `getDependencies` implementation * Require lib chunks be in node_modules * Update packages/next/build/webpack-config.ts Co-Authored-By: Joe Haddad <timer150@gmail.com> * Replace remaining missed windows compat regex * Trim client manifest * Prevent duplicate link preload tags * Revert size test changes * Squash manifest size even further * Add comment for clarity * Code golfing 🏌️‍♂️ * Correctly select modern dependencies * Ship separate modern client manifest when module/module enabled * Update packages/next/build/webpack/plugins/build-manifest-plugin.ts Co-Authored-By: Joe Haddad <timer150@gmail.com> * Remove unneccessary filter from page-loader * Add lookbehind to file extension regex in page-loader * v9.0.3 * Update examples for Apollo with AppTree (#8180) * Update examples for Apollo with AppTree * Fix apolloClient being overwritten when rendering AppTree * Golf page-loader (#8190) * Remove lookbehind for module replacement * Wait for build manifest promise before page load or prefetch * Updating modern-only chunks inside the right entry point * Fixing ts errors * Rename variable * Revert "Wait for build manifest promise before page load or prefetch" This reverts commit c370528c6888ba7fa71162a0854534ed280224ef. * Use proper typedef for webpack chunk * Re-enable promisified client build manifest * Fix bug in getDependencies map * Insert check for granularChunks in page-loader * Increase size limit temporarily for granular chunks * Add 50ms delay to flaky test * Set env.__NEXT_GRANULAR_CHUNKS in webpack config * Reset size limit to 187 * Set process.env.__NEXT_GRANULAR_CHUNKS to false if selectivePageBuilding * Update test/integration/production/test/index.test.js Co-Authored-By: Joe Haddad <timer150@gmail.com> * Do not create promise if not using chunking PR
2019-08-08 19:14:33 +02:00
},
priority: 30,
minChunks: 1,
reuseExistingChunk: true,
},
commons: {
name: 'commons',
minChunks: totalPages,
priority: 20,
},
shared: {
name(module, chunks) {
return crypto
.createHash('sha1')
.update(
chunks.reduce(
(acc: string, chunk: webpack.compilation.Chunk) => {
return acc + chunk.name
},
''
)
)
.digest('hex')
Experimental: Granular build chunking (#7696) * Refactor SplitChunksPlugin configs and add experimental chunking strategy * Use typeDefs for SplitChunksConfig * Modify build manifest plugin to create runtime build manifest * Add support for granular chunks to page-loader * Ensure normal behavior if experimental granularChunks flag is false * Update client build manifest to remove iife & implicit global * Factor out '/_next/' prepending into getDependencies * Update packages/next/build/webpack-config.ts filepath regex Co-Authored-By: Jason Miller <developit@users.noreply.github.com> * Simplify dependency load ordering in page-loader.js * Use SHA1 hash to shorten filenames for dependency modules * Add scheduler to framework cacheGroup in webpack-config * Update page loader to not duplicate script tags with query parameters * Ensure no slashes end up in the file hashes * Add prop-types to framework chunk * Fix issue with mis-attributed events * Increase modern build size budget--possibly decrement after consulting with @janicklasralph * Use module.rawRequest for lib chunks Co-Authored-By: Daniel Stockman <daniel.stockman@gmail.com> * Dasherize lib chunk names Co-Authored-By: Daniel Stockman <daniel.stockman@gmail.com> * Fix typescript errors, reorganize lib name logic * Dasherize rawRequest, short circuit name logic when rawRequest found * Add `scheduler` package to test regex * Fix a nit * Adjust build manifest plugin * Shorten key name * Extract createPreloadLink helper * Extract getDependencies helper * Move method * Minimize diff * Minimize diff x2 * Fix Array.from polyfill * Simplify page loader code * Remove async=false for script tags * Code golf `getDependencies` implementation * Require lib chunks be in node_modules * Update packages/next/build/webpack-config.ts Co-Authored-By: Joe Haddad <timer150@gmail.com> * Replace remaining missed windows compat regex * Trim client manifest * Prevent duplicate link preload tags * Revert size test changes * Squash manifest size even further * Add comment for clarity * Code golfing 🏌️‍♂️ * Correctly select modern dependencies * Ship separate modern client manifest when module/module enabled * Update packages/next/build/webpack/plugins/build-manifest-plugin.ts Co-Authored-By: Joe Haddad <timer150@gmail.com> * Remove unneccessary filter from page-loader * Add lookbehind to file extension regex in page-loader * v9.0.3 * Update examples for Apollo with AppTree (#8180) * Update examples for Apollo with AppTree * Fix apolloClient being overwritten when rendering AppTree * Golf page-loader (#8190) * Remove lookbehind for module replacement * Wait for build manifest promise before page load or prefetch * Updating modern-only chunks inside the right entry point * Fixing ts errors * Rename variable * Revert "Wait for build manifest promise before page load or prefetch" This reverts commit c370528c6888ba7fa71162a0854534ed280224ef. * Use proper typedef for webpack chunk * Re-enable promisified client build manifest * Fix bug in getDependencies map * Insert check for granularChunks in page-loader * Increase size limit temporarily for granular chunks * Add 50ms delay to flaky test * Set env.__NEXT_GRANULAR_CHUNKS in webpack config * Reset size limit to 187 * Set process.env.__NEXT_GRANULAR_CHUNKS to false if selectivePageBuilding * Update test/integration/production/test/index.test.js Co-Authored-By: Joe Haddad <timer150@gmail.com> * Do not create promise if not using chunking PR
2019-08-08 19:14:33 +02:00
},
priority: 10,
minChunks: 2,
reuseExistingChunk: true,
},
},
maxInitialRequests: 25,
minSize: 20000,
Experimental: Granular build chunking (#7696) * Refactor SplitChunksPlugin configs and add experimental chunking strategy * Use typeDefs for SplitChunksConfig * Modify build manifest plugin to create runtime build manifest * Add support for granular chunks to page-loader * Ensure normal behavior if experimental granularChunks flag is false * Update client build manifest to remove iife & implicit global * Factor out '/_next/' prepending into getDependencies * Update packages/next/build/webpack-config.ts filepath regex Co-Authored-By: Jason Miller <developit@users.noreply.github.com> * Simplify dependency load ordering in page-loader.js * Use SHA1 hash to shorten filenames for dependency modules * Add scheduler to framework cacheGroup in webpack-config * Update page loader to not duplicate script tags with query parameters * Ensure no slashes end up in the file hashes * Add prop-types to framework chunk * Fix issue with mis-attributed events * Increase modern build size budget--possibly decrement after consulting with @janicklasralph * Use module.rawRequest for lib chunks Co-Authored-By: Daniel Stockman <daniel.stockman@gmail.com> * Dasherize lib chunk names Co-Authored-By: Daniel Stockman <daniel.stockman@gmail.com> * Fix typescript errors, reorganize lib name logic * Dasherize rawRequest, short circuit name logic when rawRequest found * Add `scheduler` package to test regex * Fix a nit * Adjust build manifest plugin * Shorten key name * Extract createPreloadLink helper * Extract getDependencies helper * Move method * Minimize diff * Minimize diff x2 * Fix Array.from polyfill * Simplify page loader code * Remove async=false for script tags * Code golf `getDependencies` implementation * Require lib chunks be in node_modules * Update packages/next/build/webpack-config.ts Co-Authored-By: Joe Haddad <timer150@gmail.com> * Replace remaining missed windows compat regex * Trim client manifest * Prevent duplicate link preload tags * Revert size test changes * Squash manifest size even further * Add comment for clarity * Code golfing 🏌️‍♂️ * Correctly select modern dependencies * Ship separate modern client manifest when module/module enabled * Update packages/next/build/webpack/plugins/build-manifest-plugin.ts Co-Authored-By: Joe Haddad <timer150@gmail.com> * Remove unneccessary filter from page-loader * Add lookbehind to file extension regex in page-loader * v9.0.3 * Update examples for Apollo with AppTree (#8180) * Update examples for Apollo with AppTree * Fix apolloClient being overwritten when rendering AppTree * Golf page-loader (#8190) * Remove lookbehind for module replacement * Wait for build manifest promise before page load or prefetch * Updating modern-only chunks inside the right entry point * Fixing ts errors * Rename variable * Revert "Wait for build manifest promise before page load or prefetch" This reverts commit c370528c6888ba7fa71162a0854534ed280224ef. * Use proper typedef for webpack chunk * Re-enable promisified client build manifest * Fix bug in getDependencies map * Insert check for granularChunks in page-loader * Increase size limit temporarily for granular chunks * Add 50ms delay to flaky test * Set env.__NEXT_GRANULAR_CHUNKS in webpack config * Reset size limit to 187 * Set process.env.__NEXT_GRANULAR_CHUNKS to false if selectivePageBuilding * Update test/integration/production/test/index.test.js Co-Authored-By: Joe Haddad <timer150@gmail.com> * Do not create promise if not using chunking PR
2019-08-08 19:14:33 +02:00
},
}
// Select appropriate SplitChunksPlugin config for this build
let splitChunksConfig: webpack.Options.SplitChunksOptions
if (dev) {
splitChunksConfig = splitChunksConfigs.dev
} else {
Experimental: Granular build chunking (#7696) * Refactor SplitChunksPlugin configs and add experimental chunking strategy * Use typeDefs for SplitChunksConfig * Modify build manifest plugin to create runtime build manifest * Add support for granular chunks to page-loader * Ensure normal behavior if experimental granularChunks flag is false * Update client build manifest to remove iife & implicit global * Factor out '/_next/' prepending into getDependencies * Update packages/next/build/webpack-config.ts filepath regex Co-Authored-By: Jason Miller <developit@users.noreply.github.com> * Simplify dependency load ordering in page-loader.js * Use SHA1 hash to shorten filenames for dependency modules * Add scheduler to framework cacheGroup in webpack-config * Update page loader to not duplicate script tags with query parameters * Ensure no slashes end up in the file hashes * Add prop-types to framework chunk * Fix issue with mis-attributed events * Increase modern build size budget--possibly decrement after consulting with @janicklasralph * Use module.rawRequest for lib chunks Co-Authored-By: Daniel Stockman <daniel.stockman@gmail.com> * Dasherize lib chunk names Co-Authored-By: Daniel Stockman <daniel.stockman@gmail.com> * Fix typescript errors, reorganize lib name logic * Dasherize rawRequest, short circuit name logic when rawRequest found * Add `scheduler` package to test regex * Fix a nit * Adjust build manifest plugin * Shorten key name * Extract createPreloadLink helper * Extract getDependencies helper * Move method * Minimize diff * Minimize diff x2 * Fix Array.from polyfill * Simplify page loader code * Remove async=false for script tags * Code golf `getDependencies` implementation * Require lib chunks be in node_modules * Update packages/next/build/webpack-config.ts Co-Authored-By: Joe Haddad <timer150@gmail.com> * Replace remaining missed windows compat regex * Trim client manifest * Prevent duplicate link preload tags * Revert size test changes * Squash manifest size even further * Add comment for clarity * Code golfing 🏌️‍♂️ * Correctly select modern dependencies * Ship separate modern client manifest when module/module enabled * Update packages/next/build/webpack/plugins/build-manifest-plugin.ts Co-Authored-By: Joe Haddad <timer150@gmail.com> * Remove unneccessary filter from page-loader * Add lookbehind to file extension regex in page-loader * v9.0.3 * Update examples for Apollo with AppTree (#8180) * Update examples for Apollo with AppTree * Fix apolloClient being overwritten when rendering AppTree * Golf page-loader (#8190) * Remove lookbehind for module replacement * Wait for build manifest promise before page load or prefetch * Updating modern-only chunks inside the right entry point * Fixing ts errors * Rename variable * Revert "Wait for build manifest promise before page load or prefetch" This reverts commit c370528c6888ba7fa71162a0854534ed280224ef. * Use proper typedef for webpack chunk * Re-enable promisified client build manifest * Fix bug in getDependencies map * Insert check for granularChunks in page-loader * Increase size limit temporarily for granular chunks * Add 50ms delay to flaky test * Set env.__NEXT_GRANULAR_CHUNKS in webpack config * Reset size limit to 187 * Set process.env.__NEXT_GRANULAR_CHUNKS to false if selectivePageBuilding * Update test/integration/production/test/index.test.js Co-Authored-By: Joe Haddad <timer150@gmail.com> * Do not create promise if not using chunking PR
2019-08-08 19:14:33 +02:00
splitChunksConfig = config.experimental.granularChunks
? splitChunksConfigs.prodGranular
: splitChunksConfigs.prod
}
const crossOrigin =
!config.crossOrigin && config.experimental.modern
? 'anonymous'
: config.crossOrigin
let customAppFile: string | null = config.experimental.css
? await findPageFile(pagesDir, '/_app', config.pageExtensions)
: null
if (customAppFile) {
customAppFile = path.resolve(path.join(pagesDir, customAppFile))
}
let webpackConfig: webpack.Configuration = {
devtool,
2018-08-30 12:27:22 +02:00
mode: webpackMode,
Universal Webpack (#3578) * Speed up next build * Document webpack config * Speed up next build * Remove comment * Add comment * Clean up rules * Add comments * Run in parallel * Push plugins seperately * Create a new chunk for react * Don’t uglify react since it’s already uglified. Move react to commons in development * Use the minified version directly * Re-add globpattern * Move loaders into a separate variable * Add comment linking to Dan’s explanation * Remove dot * Add universal webpack * Initial dev support * Fix linting * Add changes from Arunoda's work * Made next dev works. But super slow and no HMR support. * Fix client side hot reload * Server side hmr * Only in dev * Add on-demand-entries client + hot-middleware * Add .babelrc support * Speed up on demand entries by running in parallel * Serve static generated files * Add missing config in dev * Add sass support * Add support for .map * Add cssloader config and fix .jsx support * Rename * use same defaults as css-loader. Fix linting * Add NoEmitErrorsPlugin * Add clientBootstrap * Use webpackhotmiddleware on the multi compiler * alpha.3 * Use babel 16.2.x * Fix reloading after error * Remove comment * Release 5.0.0-univeral-alpha.1 * Remove check for React 16 * Release 5.0.0-universal-alpha.2 * React hot loader v4 * Use our static file rendering machanism to serve pages. This should work well since the file path for a page is predictable. * Release 5.0.0-universal-alpha.3 * Remove optional loaders * Release 5.0.0-universal-alpha.4 * Remove clientBootstrap * Remove renderScript * Make sure pages bundles are served correctly * Remove unused import * Revert to using the same code as canary * Fix hot loader * Release 5.0.0-universal-alpha.5 * Check if externals dir exist before applying config * Add typescript support * Add support for transpiling certain packages in node_modules Thanks to @giuseppeg’s work in https://github.com/zeit/next.js/pull/3319 * Add BABEL_DISABLE_CACHE support * Make sourcemaps in production opt-in * Revert "Add support for transpiling certain packages in node_modules" This reverts commit d4b1d9babfb4b9ed4f4b12d56d52dee233e862da. In favor of a better api around this. * Support typescript through next.config.js * Remove comments * Bring back commons.js calculation * Remove unused dependencies * Move base.config.js to webpack.js * Make sure to only invalidate webpackDevMiddleware one after other. * Allow babel-loder caching by default. * Add comment about preact support * Bring back buildir replace * Remove obsolete plugin * Remove build replace, speed up build * Resolve page entries like pages/day/index.js to pages/day.js * Add componentDidCatch back * Compile to bundles * Use config.distDir everywhere * Make sure the file is an array * Remove console.log * Apply optimization to uglifyjs * Add comment pointing to source * Create entries the same way in dev and production * Remove unused and broken pagesGlobPattern * day/index.js is automatically turned into day.js at build time * Remove poweredByHeader option * Load pages with the correct path. * Release 5.0.0-universal-alpha.6 * Make sure react-dom/server can be overwritten by module-alias * Only add react-hot-loader babel plugin in dev * Release 5.0.0-universal-alpha.7 * Revert tests * Release 5.0.0-universal-alpha.10 * Make sure next/head is working properly. * Add wepack alias for 'next' back. * Make sure overriding className in next/head works * Alias react too * Add missing r * Fragment fallback has to wrap the children * Use min.js * Remove css.js * Remove wallaby.js * Release 5.0.0-universal-alpha.11 * Resolve relative to workdir instead of next * Make sure we touch the right file * Resolve next modules * Remove dotjsx removal plugins since we use webpack on the server * Revert "Resolve relative to workdir instead of next" This reverts commit a13f3e4ab565df9e2c9a3dfc8eb4009c0c2e02ed. * Externalize any locally loaded module lives outside of app dir. * Remove server aliases * Check node_modules reliably * Add symlink to next for tests * Make sure dynamic imports work locally. This is why we need it: https://github.com/webpack/webpack/blob/b545b519b2024e3f8be3041385bd326bf5d24449/lib/MainTemplate.js#L68 We need to have the finally clause in the above in __webpack_require__. webpack output option strictModuleExceptionHandling does that. * dynmaic -> dynamic * Remove webpack-node-externals * Make sure dynamic imports support SSR. * Remove css support in favor of next-css * Make sure we load path from `/` since it’s included in the path matching * Catch when ensurepage couldn’t be fulfilled for `.js.map` * Register require cache flusher for both client and server * Add comment explaining this is to facilitate hot reloading * Only load module when needed * Remove unused modules * Release 5.0.0-universal-alpha.12 * Only log the `found babel` message once * Make sure ondemand entries working correctly. Now we are just using a single instance of OnDemandEntryHandler. * Better sourcemaps * Release 5.0.0-universal-alpha.13 * Lock uglify version to 1.1.6 * Release 5.0.0-universal-alpha.14 * Fix a typo. * Introduce multi-zones support for mircofrontends * Add section on css
2018-01-30 16:40:52 +01:00
name: isServer ? 'server' : 'client',
target: isServer ? 'node' : 'web',
externals: !isServer
? undefined
: !isServerless
? [
(context, request, callback) => {
const notExternalModules = [
'next/app',
'next/document',
'next/link',
'next/error',
'string-hash',
'next/constants',
]
if (notExternalModules.indexOf(request) !== -1) {
return callback()
}
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
2019-11-01 20:13:13 +01:00
// 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
// are relative to requests we've already resolved here.
// Absolute requires (require('/foo')) are extremely uncommon, but
// also have no need for customization as they're already resolved.
const start = request.charAt(0)
if (start === '.' || start === '/') {
return callback()
}
// Resolve the import with the webpack provided context, this
// ensures we're resolving the correct version when multiple
// exist.
let res
try {
res = resolveRequest(request, `${context}/`)
} catch (err) {
// This is a special case for the Next.js data experiment. This
// will be removed in the future.
// We're telling webpack to externalize a package that doesn't
// exist because we know it won't ever be used at runtime.
if (
request === 'react-ssr-prepass' &&
!config.experimental.ampBindInitData
) {
if (
context.replace(/\\/g, '/').includes('next-server/server')
) {
return callback(undefined, `commonjs ${request}`)
}
}
// If the request cannot be resolved, we need to tell webpack to
// "bundle" it so that webpack shows an error (that it cannot be
// resolved).
return callback()
}
// Same as above, if the request cannot be resolved we need to have
// webpack "bundle" it so it surfaces the not found error.
if (!res) {
return callback()
}
// Bundled Node.js code is relocated without its node_modules tree.
// This means we need to make sure its request resolves to the same
// package that'll be available at runtime. If it's not identical,
// we need to bundle the code (even if it _should_ be external).
let baseRes
try {
baseRes = resolveRequest(request, `${dir}/`)
} catch (err) {}
// Same as above: if the package, when required from the root,
// would be different from what the real resolution would use, we
// cannot externalize it.
if (baseRes !== res) {
return callback()
}
// Default pages have to be transpiled
if (
!res.match(/next[/\\]dist[/\\]next-server[/\\]/) &&
(res.match(/next[/\\]dist[/\\]/) ||
res.match(/node_modules[/\\]@babel[/\\]runtime[/\\]/) ||
res.match(/node_modules[/\\]@babel[/\\]runtime-corejs2[/\\]/))
) {
return callback()
}
// Webpack itself has to be compiled because it doesn't always use module relative paths
if (
res.match(/node_modules[/\\]webpack/) ||
res.match(/node_modules[/\\]css-loader/)
) {
return callback()
}
// Anything else that is standard JavaScript within `node_modules`
// can be externalized.
if (res.match(/node_modules[/\\].*\.js$/)) {
return callback(undefined, `commonjs ${request}`)
}
// Default behavior: bundle the code!
callback()
},
]
: [
// When the 'serverless' target is used all node_modules will be compiled into the output bundles
// So that the 'serverless' bundles have 0 runtime dependencies
'@ampproject/toolbox-optimizer', // except this one
(context, request, callback) => {
if (
request === 'react-ssr-prepass' &&
!config.experimental.ampBindInitData
) {
// if it's the Next.js' require mark it as external
// since it's not used
if (context.replace(/\\/g, '/').includes('next-server/server')) {
return callback(undefined, `commonjs ${request}`)
}
}
return callback()
},
],
optimization: {
checkWasmTypes: false,
nodeEnv: false,
splitChunks: isServer ? false : splitChunksConfig,
runtimeChunk: isServer
? undefined
: { name: CLIENT_STATIC_FILES_RUNTIME_WEBPACK },
minimize: !(dev || isServer),
minimizer: [
// Minify JavaScript
new TerserPlugin({
...terserPluginConfig,
terserOptions,
}),
// Minify CSS
config.experimental.css &&
new CssMinimizerPlugin({
postcssOptions: {
map: {
// `inline: false` generates the source map in a separate file.
// Otherwise, the CSS file is needlessly large.
inline: false,
// `annotation: false` skips appending the `sourceMappingURL`
// to the end of the CSS file. Webpack already handles this.
annotation: false,
},
},
}),
].filter(Boolean),
},
recordsPath: path.join(outputPath, 'records.json'),
2016-10-14 17:05:08 +02:00
context: dir,
// Kept as function to be backwards compatible
Universal Webpack (#3578) * Speed up next build * Document webpack config * Speed up next build * Remove comment * Add comment * Clean up rules * Add comments * Run in parallel * Push plugins seperately * Create a new chunk for react * Don’t uglify react since it’s already uglified. Move react to commons in development * Use the minified version directly * Re-add globpattern * Move loaders into a separate variable * Add comment linking to Dan’s explanation * Remove dot * Add universal webpack * Initial dev support * Fix linting * Add changes from Arunoda's work * Made next dev works. But super slow and no HMR support. * Fix client side hot reload * Server side hmr * Only in dev * Add on-demand-entries client + hot-middleware * Add .babelrc support * Speed up on demand entries by running in parallel * Serve static generated files * Add missing config in dev * Add sass support * Add support for .map * Add cssloader config and fix .jsx support * Rename * use same defaults as css-loader. Fix linting * Add NoEmitErrorsPlugin * Add clientBootstrap * Use webpackhotmiddleware on the multi compiler * alpha.3 * Use babel 16.2.x * Fix reloading after error * Remove comment * Release 5.0.0-univeral-alpha.1 * Remove check for React 16 * Release 5.0.0-universal-alpha.2 * React hot loader v4 * Use our static file rendering machanism to serve pages. This should work well since the file path for a page is predictable. * Release 5.0.0-universal-alpha.3 * Remove optional loaders * Release 5.0.0-universal-alpha.4 * Remove clientBootstrap * Remove renderScript * Make sure pages bundles are served correctly * Remove unused import * Revert to using the same code as canary * Fix hot loader * Release 5.0.0-universal-alpha.5 * Check if externals dir exist before applying config * Add typescript support * Add support for transpiling certain packages in node_modules Thanks to @giuseppeg’s work in https://github.com/zeit/next.js/pull/3319 * Add BABEL_DISABLE_CACHE support * Make sourcemaps in production opt-in * Revert "Add support for transpiling certain packages in node_modules" This reverts commit d4b1d9babfb4b9ed4f4b12d56d52dee233e862da. In favor of a better api around this. * Support typescript through next.config.js * Remove comments * Bring back commons.js calculation * Remove unused dependencies * Move base.config.js to webpack.js * Make sure to only invalidate webpackDevMiddleware one after other. * Allow babel-loder caching by default. * Add comment about preact support * Bring back buildir replace * Remove obsolete plugin * Remove build replace, speed up build * Resolve page entries like pages/day/index.js to pages/day.js * Add componentDidCatch back * Compile to bundles * Use config.distDir everywhere * Make sure the file is an array * Remove console.log * Apply optimization to uglifyjs * Add comment pointing to source * Create entries the same way in dev and production * Remove unused and broken pagesGlobPattern * day/index.js is automatically turned into day.js at build time * Remove poweredByHeader option * Load pages with the correct path. * Release 5.0.0-universal-alpha.6 * Make sure react-dom/server can be overwritten by module-alias * Only add react-hot-loader babel plugin in dev * Release 5.0.0-universal-alpha.7 * Revert tests * Release 5.0.0-universal-alpha.10 * Make sure next/head is working properly. * Add wepack alias for 'next' back. * Make sure overriding className in next/head works * Alias react too * Add missing r * Fragment fallback has to wrap the children * Use min.js * Remove css.js * Remove wallaby.js * Release 5.0.0-universal-alpha.11 * Resolve relative to workdir instead of next * Make sure we touch the right file * Resolve next modules * Remove dotjsx removal plugins since we use webpack on the server * Revert "Resolve relative to workdir instead of next" This reverts commit a13f3e4ab565df9e2c9a3dfc8eb4009c0c2e02ed. * Externalize any locally loaded module lives outside of app dir. * Remove server aliases * Check node_modules reliably * Add symlink to next for tests * Make sure dynamic imports work locally. This is why we need it: https://github.com/webpack/webpack/blob/b545b519b2024e3f8be3041385bd326bf5d24449/lib/MainTemplate.js#L68 We need to have the finally clause in the above in __webpack_require__. webpack output option strictModuleExceptionHandling does that. * dynmaic -> dynamic * Remove webpack-node-externals * Make sure dynamic imports support SSR. * Remove css support in favor of next-css * Make sure we load path from `/` since it’s included in the path matching * Catch when ensurepage couldn’t be fulfilled for `.js.map` * Register require cache flusher for both client and server * Add comment explaining this is to facilitate hot reloading * Only load module when needed * Remove unused modules * Release 5.0.0-universal-alpha.12 * Only log the `found babel` message once * Make sure ondemand entries working correctly. Now we are just using a single instance of OnDemandEntryHandler. * Better sourcemaps * Release 5.0.0-universal-alpha.13 * Lock uglify version to 1.1.6 * Release 5.0.0-universal-alpha.14 * Fix a typo. * Introduce multi-zones support for mircofrontends * Add section on css
2018-01-30 16:40:52 +01:00
entry: async () => {
return {
...(clientEntries ? clientEntries : {}),
...entrypoints,
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
2019-11-01 20:13:13 +01:00
...(isServer
? {
'init-server.js': 'next-plugin-loader?middleware=on-init-server!',
'on-error-server.js':
'next-plugin-loader?middleware=on-error-server!',
}
: {}),
Universal Webpack (#3578) * Speed up next build * Document webpack config * Speed up next build * Remove comment * Add comment * Clean up rules * Add comments * Run in parallel * Push plugins seperately * Create a new chunk for react * Don’t uglify react since it’s already uglified. Move react to commons in development * Use the minified version directly * Re-add globpattern * Move loaders into a separate variable * Add comment linking to Dan’s explanation * Remove dot * Add universal webpack * Initial dev support * Fix linting * Add changes from Arunoda's work * Made next dev works. But super slow and no HMR support. * Fix client side hot reload * Server side hmr * Only in dev * Add on-demand-entries client + hot-middleware * Add .babelrc support * Speed up on demand entries by running in parallel * Serve static generated files * Add missing config in dev * Add sass support * Add support for .map * Add cssloader config and fix .jsx support * Rename * use same defaults as css-loader. Fix linting * Add NoEmitErrorsPlugin * Add clientBootstrap * Use webpackhotmiddleware on the multi compiler * alpha.3 * Use babel 16.2.x * Fix reloading after error * Remove comment * Release 5.0.0-univeral-alpha.1 * Remove check for React 16 * Release 5.0.0-universal-alpha.2 * React hot loader v4 * Use our static file rendering machanism to serve pages. This should work well since the file path for a page is predictable. * Release 5.0.0-universal-alpha.3 * Remove optional loaders * Release 5.0.0-universal-alpha.4 * Remove clientBootstrap * Remove renderScript * Make sure pages bundles are served correctly * Remove unused import * Revert to using the same code as canary * Fix hot loader * Release 5.0.0-universal-alpha.5 * Check if externals dir exist before applying config * Add typescript support * Add support for transpiling certain packages in node_modules Thanks to @giuseppeg’s work in https://github.com/zeit/next.js/pull/3319 * Add BABEL_DISABLE_CACHE support * Make sourcemaps in production opt-in * Revert "Add support for transpiling certain packages in node_modules" This reverts commit d4b1d9babfb4b9ed4f4b12d56d52dee233e862da. In favor of a better api around this. * Support typescript through next.config.js * Remove comments * Bring back commons.js calculation * Remove unused dependencies * Move base.config.js to webpack.js * Make sure to only invalidate webpackDevMiddleware one after other. * Allow babel-loder caching by default. * Add comment about preact support * Bring back buildir replace * Remove obsolete plugin * Remove build replace, speed up build * Resolve page entries like pages/day/index.js to pages/day.js * Add componentDidCatch back * Compile to bundles * Use config.distDir everywhere * Make sure the file is an array * Remove console.log * Apply optimization to uglifyjs * Add comment pointing to source * Create entries the same way in dev and production * Remove unused and broken pagesGlobPattern * day/index.js is automatically turned into day.js at build time * Remove poweredByHeader option * Load pages with the correct path. * Release 5.0.0-universal-alpha.6 * Make sure react-dom/server can be overwritten by module-alias * Only add react-hot-loader babel plugin in dev * Release 5.0.0-universal-alpha.7 * Revert tests * Release 5.0.0-universal-alpha.10 * Make sure next/head is working properly. * Add wepack alias for 'next' back. * Make sure overriding className in next/head works * Alias react too * Add missing r * Fragment fallback has to wrap the children * Use min.js * Remove css.js * Remove wallaby.js * Release 5.0.0-universal-alpha.11 * Resolve relative to workdir instead of next * Make sure we touch the right file * Resolve next modules * Remove dotjsx removal plugins since we use webpack on the server * Revert "Resolve relative to workdir instead of next" This reverts commit a13f3e4ab565df9e2c9a3dfc8eb4009c0c2e02ed. * Externalize any locally loaded module lives outside of app dir. * Remove server aliases * Check node_modules reliably * Add symlink to next for tests * Make sure dynamic imports work locally. This is why we need it: https://github.com/webpack/webpack/blob/b545b519b2024e3f8be3041385bd326bf5d24449/lib/MainTemplate.js#L68 We need to have the finally clause in the above in __webpack_require__. webpack output option strictModuleExceptionHandling does that. * dynmaic -> dynamic * Remove webpack-node-externals * Make sure dynamic imports support SSR. * Remove css support in favor of next-css * Make sure we load path from `/` since it’s included in the path matching * Catch when ensurepage couldn’t be fulfilled for `.js.map` * Register require cache flusher for both client and server * Add comment explaining this is to facilitate hot reloading * Only load module when needed * Remove unused modules * Release 5.0.0-universal-alpha.12 * Only log the `found babel` message once * Make sure ondemand entries working correctly. Now we are just using a single instance of OnDemandEntryHandler. * Better sourcemaps * Release 5.0.0-universal-alpha.13 * Lock uglify version to 1.1.6 * Release 5.0.0-universal-alpha.14 * Fix a typo. * Introduce multi-zones support for mircofrontends * Add section on css
2018-01-30 16:40:52 +01:00
}
},
2016-10-14 17:05:08 +02:00
output: {
path: outputPath,
filename: ({ chunk }: { chunk: { name: string } }) => {
// Use `[name]-[contenthash].js` in production
if (
!dev &&
(chunk.name === CLIENT_STATIC_FILES_RUNTIME_MAIN ||
chunk.name === CLIENT_STATIC_FILES_RUNTIME_WEBPACK ||
chunk.name === CLIENT_STATIC_FILES_RUNTIME_POLYFILLS)
) {
2018-08-04 20:18:20 +02:00
return chunk.name.replace(/\.js$/, '-[contenthash].js')
}
return '[name]'
},
libraryTarget: isServer ? 'commonjs2' : 'var',
hotUpdateChunkFilename: 'static/webpack/[id].[hash].hot-update.js',
hotUpdateMainFilename: 'static/webpack/[hash].hot-update.json',
// This saves chunks with the name given via `import()`
chunkFilename: isServer
? `${dev ? '[name]' : '[name].[contenthash]'}.js`
: `static/chunks/${dev ? '[name]' : '[name].[contenthash]'}.js`,
strictModuleExceptionHandling: true,
crossOriginLoading: crossOrigin,
futureEmitAssets: !dev,
webassemblyModuleFilename: 'static/wasm/[modulehash].wasm',
2016-10-14 17:05:08 +02:00
},
performance: false,
resolve: resolveConfig,
2016-10-14 17:05:08 +02:00
resolveLoader: {
// The loaders Next.js provides
alias: [
'emit-file-loader',
'error-loader',
'next-babel-loader',
'next-client-pages-loader',
'next-data-loader',
'next-serverless-loader',
'noop-loader',
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
2019-11-01 20:13:13 +01:00
'next-plugin-loader',
].reduce((alias, loader) => {
// using multiple aliases to replace `resolveLoader.modules`
alias[loader] = path.join(__dirname, 'webpack', 'loaders', loader)
return alias
}, {} as Record<string, string>),
modules: [
'node_modules',
...nodePathList, // Support for NODE_PATH environment variable
],
plugins: [PnpWebpackPlugin],
2016-10-14 17:05:08 +02:00
},
2019-04-02 16:09:34 +02:00
// @ts-ignore this is filtered
2016-10-14 17:05:08 +02:00
module: {
strictExportPresence: true,
rules: [
config.experimental.ampBindInitData &&
!isServer && {
test: /\.(tsx|ts|js|mjs|jsx)$/,
include: [path.join(dir, 'data')],
use: 'next-data-loader',
},
Universal Webpack (#3578) * Speed up next build * Document webpack config * Speed up next build * Remove comment * Add comment * Clean up rules * Add comments * Run in parallel * Push plugins seperately * Create a new chunk for react * Don’t uglify react since it’s already uglified. Move react to commons in development * Use the minified version directly * Re-add globpattern * Move loaders into a separate variable * Add comment linking to Dan’s explanation * Remove dot * Add universal webpack * Initial dev support * Fix linting * Add changes from Arunoda's work * Made next dev works. But super slow and no HMR support. * Fix client side hot reload * Server side hmr * Only in dev * Add on-demand-entries client + hot-middleware * Add .babelrc support * Speed up on demand entries by running in parallel * Serve static generated files * Add missing config in dev * Add sass support * Add support for .map * Add cssloader config and fix .jsx support * Rename * use same defaults as css-loader. Fix linting * Add NoEmitErrorsPlugin * Add clientBootstrap * Use webpackhotmiddleware on the multi compiler * alpha.3 * Use babel 16.2.x * Fix reloading after error * Remove comment * Release 5.0.0-univeral-alpha.1 * Remove check for React 16 * Release 5.0.0-universal-alpha.2 * React hot loader v4 * Use our static file rendering machanism to serve pages. This should work well since the file path for a page is predictable. * Release 5.0.0-universal-alpha.3 * Remove optional loaders * Release 5.0.0-universal-alpha.4 * Remove clientBootstrap * Remove renderScript * Make sure pages bundles are served correctly * Remove unused import * Revert to using the same code as canary * Fix hot loader * Release 5.0.0-universal-alpha.5 * Check if externals dir exist before applying config * Add typescript support * Add support for transpiling certain packages in node_modules Thanks to @giuseppeg’s work in https://github.com/zeit/next.js/pull/3319 * Add BABEL_DISABLE_CACHE support * Make sourcemaps in production opt-in * Revert "Add support for transpiling certain packages in node_modules" This reverts commit d4b1d9babfb4b9ed4f4b12d56d52dee233e862da. In favor of a better api around this. * Support typescript through next.config.js * Remove comments * Bring back commons.js calculation * Remove unused dependencies * Move base.config.js to webpack.js * Make sure to only invalidate webpackDevMiddleware one after other. * Allow babel-loder caching by default. * Add comment about preact support * Bring back buildir replace * Remove obsolete plugin * Remove build replace, speed up build * Resolve page entries like pages/day/index.js to pages/day.js * Add componentDidCatch back * Compile to bundles * Use config.distDir everywhere * Make sure the file is an array * Remove console.log * Apply optimization to uglifyjs * Add comment pointing to source * Create entries the same way in dev and production * Remove unused and broken pagesGlobPattern * day/index.js is automatically turned into day.js at build time * Remove poweredByHeader option * Load pages with the correct path. * Release 5.0.0-universal-alpha.6 * Make sure react-dom/server can be overwritten by module-alias * Only add react-hot-loader babel plugin in dev * Release 5.0.0-universal-alpha.7 * Revert tests * Release 5.0.0-universal-alpha.10 * Make sure next/head is working properly. * Add wepack alias for 'next' back. * Make sure overriding className in next/head works * Alias react too * Add missing r * Fragment fallback has to wrap the children * Use min.js * Remove css.js * Remove wallaby.js * Release 5.0.0-universal-alpha.11 * Resolve relative to workdir instead of next * Make sure we touch the right file * Resolve next modules * Remove dotjsx removal plugins since we use webpack on the server * Revert "Resolve relative to workdir instead of next" This reverts commit a13f3e4ab565df9e2c9a3dfc8eb4009c0c2e02ed. * Externalize any locally loaded module lives outside of app dir. * Remove server aliases * Check node_modules reliably * Add symlink to next for tests * Make sure dynamic imports work locally. This is why we need it: https://github.com/webpack/webpack/blob/b545b519b2024e3f8be3041385bd326bf5d24449/lib/MainTemplate.js#L68 We need to have the finally clause in the above in __webpack_require__. webpack output option strictModuleExceptionHandling does that. * dynmaic -> dynamic * Remove webpack-node-externals * Make sure dynamic imports support SSR. * Remove css support in favor of next-css * Make sure we load path from `/` since it’s included in the path matching * Catch when ensurepage couldn’t be fulfilled for `.js.map` * Register require cache flusher for both client and server * Add comment explaining this is to facilitate hot reloading * Only load module when needed * Remove unused modules * Release 5.0.0-universal-alpha.12 * Only log the `found babel` message once * Make sure ondemand entries working correctly. Now we are just using a single instance of OnDemandEntryHandler. * Better sourcemaps * Release 5.0.0-universal-alpha.13 * Lock uglify version to 1.1.6 * Release 5.0.0-universal-alpha.14 * Fix a typo. * Introduce multi-zones support for mircofrontends * Add section on css
2018-01-30 16:40:52 +01:00
{
2019-04-23 11:54:08 +02:00
test: /\.(tsx|ts|js|mjs|jsx)$/,
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
2019-11-01 20:13:13 +01:00
include: [dir, ...babelIncludeRegexes],
exclude: (path: string) => {
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
2019-11-01 20:13:13 +01:00
if (babelIncludeRegexes.some(r => r.test(path))) {
return false
}
return /node_modules/.test(path)
},
use: defaultLoaders.babel,
},
config.experimental.css &&
// Support CSS imports
({
oneOf: [
{
test: /\.css$/,
issuer: { include: [customAppFile].filter(Boolean) },
use: isServer
? // Global CSS is ignored on the server because it's only needed
// on the client-side.
require.resolve('ignore-loader')
: [
// During development we load CSS via JavaScript so we can
// hot reload it without refreshing the page.
dev && {
loader: require.resolve('style-loader'),
options: {
// By default, style-loader injects CSS into the bottom
// of <head>. This causes ordering problems between dev
// and prod. To fix this, we render a <noscript> tag as
// an anchor for the styles to be placed before. These
// styles will be applied _before_ <style jsx global>.
insert: function(element: Node) {
// These elements should always exist. If they do not,
// this code should fail.
var anchorElement = document.querySelector(
'#__next_css__DO_NOT_USE__'
)!
var parentNode = anchorElement.parentNode! // Normally <head>
// Each style tag should be placed right before our
// anchor. By inserting before and not after, we do not
// need to track the last inserted element.
parentNode.insertBefore(element, anchorElement)
// Remember: this is development only code.
//
// After styles are injected, we need to remove the
// <style> tags that set `body { display: none; }`.
//
// We use `requestAnimationFrame` as a way to defer
// this operation since there may be multiple style
// tags.
;(self.requestAnimationFrame || setTimeout)(
function() {
for (
var x = document.querySelectorAll(
'[data-next-hide-fouc]'
),
i = x.length;
i--;
) {
x[i].parentNode!.removeChild(x[i])
}
}
)
},
},
},
// When building for production we extract CSS into
// separate files.
!dev && {
loader: MiniCssExtractPlugin.loader,
options: {},
},
// Resolve CSS `@import`s and `url()`s
{
loader: require.resolve('css-loader'),
options: { importLoaders: 1, sourceMap: true },
},
// Compile CSS
{
loader: require.resolve('postcss-loader'),
options: {
ident: 'postcss',
plugins: () => [
// Make Flexbox behave like the spec cross-browser.
require('postcss-flexbugs-fixes'),
// Run Autoprefixer and compile new CSS features.
require('postcss-preset-env')({
autoprefixer: {
// Disable legacy flexbox support
flexbox: 'no-2009',
},
// Enable CSS features that have shipped to the
// web platform, i.e. in 2+ browsers unflagged.
stage: 3,
}),
],
sourceMap: true,
},
},
].filter(Boolean),
// A global CSS import always has side effects. Webpack will tree
// shake the CSS without this option if the issuer claims to have
// no side-effects.
// See https://github.com/webpack/webpack/issues/6571
sideEffects: true,
},
{
test: /\.css$/,
use: isServer
? require.resolve('ignore-loader')
: {
loader: 'error-loader',
options: {
reason:
`Global CSS ${chalk.bold(
'cannot'
)} be imported from files other than your ${chalk.bold(
'Custom <App>'
)}. Please move all global CSS imports to ${chalk.cyan(
customAppFile
? path.relative(dir, customAppFile)
: 'pages/_app.js'
)}.\n` +
`Read more: https://err.sh/next.js/global-css`,
},
},
},
],
} as webpack.RuleSetRule),
config.experimental.css &&
({
loader: require.resolve('file-loader'),
issuer: {
// file-loader is only used for CSS files, e.g. url() for a SVG
// or font files
test: /\.css$/,
},
// Exclude extensions that webpack handles by default
exclude: [/\.(js|mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/],
options: {
name: 'static/media/[name].[hash].[ext]',
},
} as webpack.RuleSetRule),
].filter(Boolean),
2016-10-16 06:01:17 +02:00
},
Universal Webpack (#3578) * Speed up next build * Document webpack config * Speed up next build * Remove comment * Add comment * Clean up rules * Add comments * Run in parallel * Push plugins seperately * Create a new chunk for react * Don’t uglify react since it’s already uglified. Move react to commons in development * Use the minified version directly * Re-add globpattern * Move loaders into a separate variable * Add comment linking to Dan’s explanation * Remove dot * Add universal webpack * Initial dev support * Fix linting * Add changes from Arunoda's work * Made next dev works. But super slow and no HMR support. * Fix client side hot reload * Server side hmr * Only in dev * Add on-demand-entries client + hot-middleware * Add .babelrc support * Speed up on demand entries by running in parallel * Serve static generated files * Add missing config in dev * Add sass support * Add support for .map * Add cssloader config and fix .jsx support * Rename * use same defaults as css-loader. Fix linting * Add NoEmitErrorsPlugin * Add clientBootstrap * Use webpackhotmiddleware on the multi compiler * alpha.3 * Use babel 16.2.x * Fix reloading after error * Remove comment * Release 5.0.0-univeral-alpha.1 * Remove check for React 16 * Release 5.0.0-universal-alpha.2 * React hot loader v4 * Use our static file rendering machanism to serve pages. This should work well since the file path for a page is predictable. * Release 5.0.0-universal-alpha.3 * Remove optional loaders * Release 5.0.0-universal-alpha.4 * Remove clientBootstrap * Remove renderScript * Make sure pages bundles are served correctly * Remove unused import * Revert to using the same code as canary * Fix hot loader * Release 5.0.0-universal-alpha.5 * Check if externals dir exist before applying config * Add typescript support * Add support for transpiling certain packages in node_modules Thanks to @giuseppeg’s work in https://github.com/zeit/next.js/pull/3319 * Add BABEL_DISABLE_CACHE support * Make sourcemaps in production opt-in * Revert "Add support for transpiling certain packages in node_modules" This reverts commit d4b1d9babfb4b9ed4f4b12d56d52dee233e862da. In favor of a better api around this. * Support typescript through next.config.js * Remove comments * Bring back commons.js calculation * Remove unused dependencies * Move base.config.js to webpack.js * Make sure to only invalidate webpackDevMiddleware one after other. * Allow babel-loder caching by default. * Add comment about preact support * Bring back buildir replace * Remove obsolete plugin * Remove build replace, speed up build * Resolve page entries like pages/day/index.js to pages/day.js * Add componentDidCatch back * Compile to bundles * Use config.distDir everywhere * Make sure the file is an array * Remove console.log * Apply optimization to uglifyjs * Add comment pointing to source * Create entries the same way in dev and production * Remove unused and broken pagesGlobPattern * day/index.js is automatically turned into day.js at build time * Remove poweredByHeader option * Load pages with the correct path. * Release 5.0.0-universal-alpha.6 * Make sure react-dom/server can be overwritten by module-alias * Only add react-hot-loader babel plugin in dev * Release 5.0.0-universal-alpha.7 * Revert tests * Release 5.0.0-universal-alpha.10 * Make sure next/head is working properly. * Add wepack alias for 'next' back. * Make sure overriding className in next/head works * Alias react too * Add missing r * Fragment fallback has to wrap the children * Use min.js * Remove css.js * Remove wallaby.js * Release 5.0.0-universal-alpha.11 * Resolve relative to workdir instead of next * Make sure we touch the right file * Resolve next modules * Remove dotjsx removal plugins since we use webpack on the server * Revert "Resolve relative to workdir instead of next" This reverts commit a13f3e4ab565df9e2c9a3dfc8eb4009c0c2e02ed. * Externalize any locally loaded module lives outside of app dir. * Remove server aliases * Check node_modules reliably * Add symlink to next for tests * Make sure dynamic imports work locally. This is why we need it: https://github.com/webpack/webpack/blob/b545b519b2024e3f8be3041385bd326bf5d24449/lib/MainTemplate.js#L68 We need to have the finally clause in the above in __webpack_require__. webpack output option strictModuleExceptionHandling does that. * dynmaic -> dynamic * Remove webpack-node-externals * Make sure dynamic imports support SSR. * Remove css support in favor of next-css * Make sure we load path from `/` since it’s included in the path matching * Catch when ensurepage couldn’t be fulfilled for `.js.map` * Register require cache flusher for both client and server * Add comment explaining this is to facilitate hot reloading * Only load module when needed * Remove unused modules * Release 5.0.0-universal-alpha.12 * Only log the `found babel` message once * Make sure ondemand entries working correctly. Now we are just using a single instance of OnDemandEntryHandler. * Better sourcemaps * Release 5.0.0-universal-alpha.13 * Lock uglify version to 1.1.6 * Release 5.0.0-universal-alpha.14 * Fix a typo. * Introduce multi-zones support for mircofrontends * Add section on css
2018-01-30 16:40:52 +01:00
plugins: [
// This plugin makes sure `output.filename` is used for entry chunks
new ChunkNamesPlugin(),
new webpack.DefinePlugin({
...Object.keys(config.env).reduce((acc, key) => {
if (/^(?:NODE_.+)|^(?:__.+)$/i.test(key)) {
throw new Error(
`The key "${key}" under "env" in next.config.js is not allowed. https://err.sh/zeit/next.js/env-key-not-allowed`
)
}
return {
...acc,
[`process.env.${key}`]: JSON.stringify(config.env[key]),
}
}, {}),
'process.env.NODE_ENV': JSON.stringify(webpackMode),
'process.crossOrigin': JSON.stringify(crossOrigin),
'process.browser': JSON.stringify(!isServer),
'process.env.__NEXT_TEST_MODE': JSON.stringify(
process.env.__NEXT_TEST_MODE
),
// This is used in client/dev-error-overlay/hot-dev-client.js to replace the dist directory
...(dev && !isServer
? {
'process.env.__NEXT_DIST_DIR': JSON.stringify(distDir),
}
: {}),
'process.env.__NEXT_EXPORT_TRAILING_SLASH': JSON.stringify(
config.exportTrailingSlash
),
'process.env.__NEXT_DEFER_SCRIPTS': JSON.stringify(
config.experimental.deferScripts
),
'process.env.__NEXT_MODERN_BUILD': JSON.stringify(
config.experimental.modern && !dev
),
'process.env.__NEXT_GRANULAR_CHUNKS': JSON.stringify(
config.experimental.granularChunks && !dev
),
'process.env.__NEXT_BUILD_INDICATOR': JSON.stringify(
config.devIndicators.buildActivity
),
'process.env.__NEXT_PRERENDER_INDICATOR': JSON.stringify(
config.devIndicators.autoPrerender
),
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
2019-11-01 20:13:13 +01:00
'process.env.__NEXT_PLUGINS': JSON.stringify(
config.experimental.plugins
),
'process.env.__NEXT_STRICT_MODE': JSON.stringify(
config.reactStrictMode
),
'process.env.__NEXT_REACT_MODE': JSON.stringify(
config.experimental.reactMode
),
...(isServer
? {
// Fix bad-actors in the npm ecosystem (e.g. `node-formidable`)
// This is typically found in unmaintained modules from the
// pre-webpack era (common in server-side code)
'global.GENTLY': JSON.stringify(false),
}
: undefined),
}),
!isServer &&
new ReactLoadablePlugin({
filename: REACT_LOADABLE_MANIFEST,
}),
!isServer && new DropClientPage(),
// Moment.js is an extremely popular library that bundles large locale files
// by default due to how Webpack interprets its code. This is a practical
// solution that requires the user to opt into importing specific locales.
// https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
config.future.excludeDefaultMomentLocales &&
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
...(dev
? (() => {
// Even though require.cache is server only we have to clear assets from both compilations
// This is because the client compilation generates the build manifest that's used on the server side
const {
NextJsRequireCacheHotReloader,
} = require('./webpack/plugins/nextjs-require-cache-hot-reloader')
const {
UnlinkRemovedPagesPlugin,
} = require('./webpack/plugins/unlink-removed-pages-plugin')
const devPlugins = [
new UnlinkRemovedPagesPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new NextJsRequireCacheHotReloader(),
]
if (!isServer) {
const AutoDllPlugin = importAutoDllPlugin({ distDir })
devPlugins.push(
new AutoDllPlugin({
filename: '[name]_[hash].js',
path: './static/development/dll',
context: dir,
entry: {
dll: ['react', 'react-dom'],
},
config: {
devtool,
mode: webpackMode,
resolve: resolveConfig,
},
})
)
devPlugins.push(new webpack.HotModuleReplacementPlugin())
}
return devPlugins
})()
: []),
!dev && new webpack.HashedModuleIdsPlugin(),
!dev &&
new webpack.IgnorePlugin({
checkResource: (resource: string) => {
return /react-is/.test(resource)
},
checkContext: (context: string) => {
return (
/next-server[\\/]dist[\\/]/.test(context) ||
/next[\\/]dist[\\/]/.test(context)
)
},
}),
isServerless && isServer && new ServerlessPlugin(),
isServer && new PagesManifestPlugin(isLikeServerless),
target === 'server' &&
isServer &&
new NextJsSSRModuleCachePlugin({ outputPath }),
isServer && new NextJsSsrImportPlugin(),
Experimental: Granular build chunking (#7696) * Refactor SplitChunksPlugin configs and add experimental chunking strategy * Use typeDefs for SplitChunksConfig * Modify build manifest plugin to create runtime build manifest * Add support for granular chunks to page-loader * Ensure normal behavior if experimental granularChunks flag is false * Update client build manifest to remove iife & implicit global * Factor out '/_next/' prepending into getDependencies * Update packages/next/build/webpack-config.ts filepath regex Co-Authored-By: Jason Miller <developit@users.noreply.github.com> * Simplify dependency load ordering in page-loader.js * Use SHA1 hash to shorten filenames for dependency modules * Add scheduler to framework cacheGroup in webpack-config * Update page loader to not duplicate script tags with query parameters * Ensure no slashes end up in the file hashes * Add prop-types to framework chunk * Fix issue with mis-attributed events * Increase modern build size budget--possibly decrement after consulting with @janicklasralph * Use module.rawRequest for lib chunks Co-Authored-By: Daniel Stockman <daniel.stockman@gmail.com> * Dasherize lib chunk names Co-Authored-By: Daniel Stockman <daniel.stockman@gmail.com> * Fix typescript errors, reorganize lib name logic * Dasherize rawRequest, short circuit name logic when rawRequest found * Add `scheduler` package to test regex * Fix a nit * Adjust build manifest plugin * Shorten key name * Extract createPreloadLink helper * Extract getDependencies helper * Move method * Minimize diff * Minimize diff x2 * Fix Array.from polyfill * Simplify page loader code * Remove async=false for script tags * Code golf `getDependencies` implementation * Require lib chunks be in node_modules * Update packages/next/build/webpack-config.ts Co-Authored-By: Joe Haddad <timer150@gmail.com> * Replace remaining missed windows compat regex * Trim client manifest * Prevent duplicate link preload tags * Revert size test changes * Squash manifest size even further * Add comment for clarity * Code golfing 🏌️‍♂️ * Correctly select modern dependencies * Ship separate modern client manifest when module/module enabled * Update packages/next/build/webpack/plugins/build-manifest-plugin.ts Co-Authored-By: Joe Haddad <timer150@gmail.com> * Remove unneccessary filter from page-loader * Add lookbehind to file extension regex in page-loader * v9.0.3 * Update examples for Apollo with AppTree (#8180) * Update examples for Apollo with AppTree * Fix apolloClient being overwritten when rendering AppTree * Golf page-loader (#8190) * Remove lookbehind for module replacement * Wait for build manifest promise before page load or prefetch * Updating modern-only chunks inside the right entry point * Fixing ts errors * Rename variable * Revert "Wait for build manifest promise before page load or prefetch" This reverts commit c370528c6888ba7fa71162a0854534ed280224ef. * Use proper typedef for webpack chunk * Re-enable promisified client build manifest * Fix bug in getDependencies map * Insert check for granularChunks in page-loader * Increase size limit temporarily for granular chunks * Add 50ms delay to flaky test * Set env.__NEXT_GRANULAR_CHUNKS in webpack config * Reset size limit to 187 * Set process.env.__NEXT_GRANULAR_CHUNKS to false if selectivePageBuilding * Update test/integration/production/test/index.test.js Co-Authored-By: Joe Haddad <timer150@gmail.com> * Do not create promise if not using chunking PR
2019-08-08 19:14:33 +02:00
!isServer &&
new BuildManifestPlugin({
buildId,
clientManifest: config.experimental.granularChunks,
modern: config.experimental.modern,
}),
// Extract CSS as CSS file(s) in the client-side production bundle.
config.experimental.css &&
!isServer &&
!dev &&
new MiniCssExtractPlugin({
filename: 'static/css/[contenthash].css',
chunkFilename: 'static/css/[contenthash].chunk.css',
}),
tracer &&
new ProfilingPlugin({
tracer,
}),
!isServer &&
useTypeScript &&
!ignoreTypeScriptErrors &&
new ForkTsCheckerWebpackPlugin(
PnpWebpackPlugin.forkTsCheckerOptions({
typescript: typeScriptPath,
async: dev,
useTypescriptIncrementalApi: true,
checkSyntacticErrors: true,
tsconfig: tsConfigPath,
reportFiles: ['**', '!**/__tests__/**', '!**/?(*.)(spec|test).*'],
compilerOptions: { isolatedModules: true, noEmit: true },
silent: true,
formatter: 'codeframe',
})
),
config.experimental.modern &&
!isServer &&
!dev &&
new NextEsmPlugin({
filename: (getFileName: Function | string) => (...args: any[]) => {
const name =
typeof getFileName === 'function'
? getFileName(...args)
: getFileName
return name.includes('.js')
? name.replace(/\.js$/, '.module.js')
: escapePathVariables(
args[0].chunk.name.replace(/\.js$/, '.module.js')
)
},
chunkFilename: (inputChunkName: string) =>
inputChunkName.replace(/\.js$/, '.module.js'),
}),
].filter((Boolean as any) as ExcludesFalse),
}
Universal Webpack (#3578) * Speed up next build * Document webpack config * Speed up next build * Remove comment * Add comment * Clean up rules * Add comments * Run in parallel * Push plugins seperately * Create a new chunk for react * Don’t uglify react since it’s already uglified. Move react to commons in development * Use the minified version directly * Re-add globpattern * Move loaders into a separate variable * Add comment linking to Dan’s explanation * Remove dot * Add universal webpack * Initial dev support * Fix linting * Add changes from Arunoda's work * Made next dev works. But super slow and no HMR support. * Fix client side hot reload * Server side hmr * Only in dev * Add on-demand-entries client + hot-middleware * Add .babelrc support * Speed up on demand entries by running in parallel * Serve static generated files * Add missing config in dev * Add sass support * Add support for .map * Add cssloader config and fix .jsx support * Rename * use same defaults as css-loader. Fix linting * Add NoEmitErrorsPlugin * Add clientBootstrap * Use webpackhotmiddleware on the multi compiler * alpha.3 * Use babel 16.2.x * Fix reloading after error * Remove comment * Release 5.0.0-univeral-alpha.1 * Remove check for React 16 * Release 5.0.0-universal-alpha.2 * React hot loader v4 * Use our static file rendering machanism to serve pages. This should work well since the file path for a page is predictable. * Release 5.0.0-universal-alpha.3 * Remove optional loaders * Release 5.0.0-universal-alpha.4 * Remove clientBootstrap * Remove renderScript * Make sure pages bundles are served correctly * Remove unused import * Revert to using the same code as canary * Fix hot loader * Release 5.0.0-universal-alpha.5 * Check if externals dir exist before applying config * Add typescript support * Add support for transpiling certain packages in node_modules Thanks to @giuseppeg’s work in https://github.com/zeit/next.js/pull/3319 * Add BABEL_DISABLE_CACHE support * Make sourcemaps in production opt-in * Revert "Add support for transpiling certain packages in node_modules" This reverts commit d4b1d9babfb4b9ed4f4b12d56d52dee233e862da. In favor of a better api around this. * Support typescript through next.config.js * Remove comments * Bring back commons.js calculation * Remove unused dependencies * Move base.config.js to webpack.js * Make sure to only invalidate webpackDevMiddleware one after other. * Allow babel-loder caching by default. * Add comment about preact support * Bring back buildir replace * Remove obsolete plugin * Remove build replace, speed up build * Resolve page entries like pages/day/index.js to pages/day.js * Add componentDidCatch back * Compile to bundles * Use config.distDir everywhere * Make sure the file is an array * Remove console.log * Apply optimization to uglifyjs * Add comment pointing to source * Create entries the same way in dev and production * Remove unused and broken pagesGlobPattern * day/index.js is automatically turned into day.js at build time * Remove poweredByHeader option * Load pages with the correct path. * Release 5.0.0-universal-alpha.6 * Make sure react-dom/server can be overwritten by module-alias * Only add react-hot-loader babel plugin in dev * Release 5.0.0-universal-alpha.7 * Revert tests * Release 5.0.0-universal-alpha.10 * Make sure next/head is working properly. * Add wepack alias for 'next' back. * Make sure overriding className in next/head works * Alias react too * Add missing r * Fragment fallback has to wrap the children * Use min.js * Remove css.js * Remove wallaby.js * Release 5.0.0-universal-alpha.11 * Resolve relative to workdir instead of next * Make sure we touch the right file * Resolve next modules * Remove dotjsx removal plugins since we use webpack on the server * Revert "Resolve relative to workdir instead of next" This reverts commit a13f3e4ab565df9e2c9a3dfc8eb4009c0c2e02ed. * Externalize any locally loaded module lives outside of app dir. * Remove server aliases * Check node_modules reliably * Add symlink to next for tests * Make sure dynamic imports work locally. This is why we need it: https://github.com/webpack/webpack/blob/b545b519b2024e3f8be3041385bd326bf5d24449/lib/MainTemplate.js#L68 We need to have the finally clause in the above in __webpack_require__. webpack output option strictModuleExceptionHandling does that. * dynmaic -> dynamic * Remove webpack-node-externals * Make sure dynamic imports support SSR. * Remove css support in favor of next-css * Make sure we load path from `/` since it’s included in the path matching * Catch when ensurepage couldn’t be fulfilled for `.js.map` * Register require cache flusher for both client and server * Add comment explaining this is to facilitate hot reloading * Only load module when needed * Remove unused modules * Release 5.0.0-universal-alpha.12 * Only log the `found babel` message once * Make sure ondemand entries working correctly. Now we are just using a single instance of OnDemandEntryHandler. * Better sourcemaps * Release 5.0.0-universal-alpha.13 * Lock uglify version to 1.1.6 * Release 5.0.0-universal-alpha.14 * Fix a typo. * Introduce multi-zones support for mircofrontends * Add section on css
2018-01-30 16:40:52 +01:00
if (typeof config.webpack === 'function') {
webpackConfig = config.webpack(webpackConfig, {
dir,
dev,
isServer,
buildId,
config,
defaultLoaders,
totalPages,
webpack,
})
// @ts-ignore: Property 'then' does not exist on type 'Configuration'
if (typeof webpackConfig.then === 'function') {
console.warn(
'> Promise returned in next config. https://err.sh/zeit/next.js/promise-in-next-config'
)
}
}
Universal Webpack (#3578) * Speed up next build * Document webpack config * Speed up next build * Remove comment * Add comment * Clean up rules * Add comments * Run in parallel * Push plugins seperately * Create a new chunk for react * Don’t uglify react since it’s already uglified. Move react to commons in development * Use the minified version directly * Re-add globpattern * Move loaders into a separate variable * Add comment linking to Dan’s explanation * Remove dot * Add universal webpack * Initial dev support * Fix linting * Add changes from Arunoda's work * Made next dev works. But super slow and no HMR support. * Fix client side hot reload * Server side hmr * Only in dev * Add on-demand-entries client + hot-middleware * Add .babelrc support * Speed up on demand entries by running in parallel * Serve static generated files * Add missing config in dev * Add sass support * Add support for .map * Add cssloader config and fix .jsx support * Rename * use same defaults as css-loader. Fix linting * Add NoEmitErrorsPlugin * Add clientBootstrap * Use webpackhotmiddleware on the multi compiler * alpha.3 * Use babel 16.2.x * Fix reloading after error * Remove comment * Release 5.0.0-univeral-alpha.1 * Remove check for React 16 * Release 5.0.0-universal-alpha.2 * React hot loader v4 * Use our static file rendering machanism to serve pages. This should work well since the file path for a page is predictable. * Release 5.0.0-universal-alpha.3 * Remove optional loaders * Release 5.0.0-universal-alpha.4 * Remove clientBootstrap * Remove renderScript * Make sure pages bundles are served correctly * Remove unused import * Revert to using the same code as canary * Fix hot loader * Release 5.0.0-universal-alpha.5 * Check if externals dir exist before applying config * Add typescript support * Add support for transpiling certain packages in node_modules Thanks to @giuseppeg’s work in https://github.com/zeit/next.js/pull/3319 * Add BABEL_DISABLE_CACHE support * Make sourcemaps in production opt-in * Revert "Add support for transpiling certain packages in node_modules" This reverts commit d4b1d9babfb4b9ed4f4b12d56d52dee233e862da. In favor of a better api around this. * Support typescript through next.config.js * Remove comments * Bring back commons.js calculation * Remove unused dependencies * Move base.config.js to webpack.js * Make sure to only invalidate webpackDevMiddleware one after other. * Allow babel-loder caching by default. * Add comment about preact support * Bring back buildir replace * Remove obsolete plugin * Remove build replace, speed up build * Resolve page entries like pages/day/index.js to pages/day.js * Add componentDidCatch back * Compile to bundles * Use config.distDir everywhere * Make sure the file is an array * Remove console.log * Apply optimization to uglifyjs * Add comment pointing to source * Create entries the same way in dev and production * Remove unused and broken pagesGlobPattern * day/index.js is automatically turned into day.js at build time * Remove poweredByHeader option * Load pages with the correct path. * Release 5.0.0-universal-alpha.6 * Make sure react-dom/server can be overwritten by module-alias * Only add react-hot-loader babel plugin in dev * Release 5.0.0-universal-alpha.7 * Revert tests * Release 5.0.0-universal-alpha.10 * Make sure next/head is working properly. * Add wepack alias for 'next' back. * Make sure overriding className in next/head works * Alias react too * Add missing r * Fragment fallback has to wrap the children * Use min.js * Remove css.js * Remove wallaby.js * Release 5.0.0-universal-alpha.11 * Resolve relative to workdir instead of next * Make sure we touch the right file * Resolve next modules * Remove dotjsx removal plugins since we use webpack on the server * Revert "Resolve relative to workdir instead of next" This reverts commit a13f3e4ab565df9e2c9a3dfc8eb4009c0c2e02ed. * Externalize any locally loaded module lives outside of app dir. * Remove server aliases * Check node_modules reliably * Add symlink to next for tests * Make sure dynamic imports work locally. This is why we need it: https://github.com/webpack/webpack/blob/b545b519b2024e3f8be3041385bd326bf5d24449/lib/MainTemplate.js#L68 We need to have the finally clause in the above in __webpack_require__. webpack output option strictModuleExceptionHandling does that. * dynmaic -> dynamic * Remove webpack-node-externals * Make sure dynamic imports support SSR. * Remove css support in favor of next-css * Make sure we load path from `/` since it’s included in the path matching * Catch when ensurepage couldn’t be fulfilled for `.js.map` * Register require cache flusher for both client and server * Add comment explaining this is to facilitate hot reloading * Only load module when needed * Remove unused modules * Release 5.0.0-universal-alpha.12 * Only log the `found babel` message once * Make sure ondemand entries working correctly. Now we are just using a single instance of OnDemandEntryHandler. * Better sourcemaps * Release 5.0.0-universal-alpha.13 * Lock uglify version to 1.1.6 * Release 5.0.0-universal-alpha.14 * Fix a typo. * Introduce multi-zones support for mircofrontends * Add section on css
2018-01-30 16:40:52 +01:00
// check if using @zeit/next-typescript and show warning
if (
isServer &&
webpackConfig.module &&
Array.isArray(webpackConfig.module.rules)
) {
let foundTsRule = false
webpackConfig.module.rules = webpackConfig.module.rules.filter(
(rule): boolean => {
if (!(rule.test instanceof RegExp)) return true
if ('noop.ts'.match(rule.test) && !'noop.js'.match(rule.test)) {
// remove if it matches @zeit/next-typescript
foundTsRule = rule.use === defaultLoaders.babel
return !foundTsRule
}
return true
}
)
if (foundTsRule) {
console.warn(
'\n@zeit/next-typescript is no longer needed since Next.js has built-in support for TypeScript now. Please remove it from your next.config.js and your .babelrc\n'
)
}
}
// Patch `@zeit/next-sass` and `@zeit/next-less` compatibility
if (webpackConfig.module && Array.isArray(webpackConfig.module.rules)) {
;[].forEach.call(webpackConfig.module.rules, function(
rule: webpack.RuleSetRule
) {
if (!(rule.test instanceof RegExp && Array.isArray(rule.use))) {
return
}
const isSass =
rule.test.source === '\\.scss$' || rule.test.source === '\\.sass$'
const isLess = rule.test.source === '\\.less$'
const isCss = rule.test.source === '\\.css$'
// Check if the rule we're iterating over applies to Sass, Less, or CSS
if (!(isSass || isLess || isCss)) {
return
}
;[].forEach.call(rule.use, function(use: webpack.RuleSetUseItem) {
if (
!(
use &&
typeof use === 'object' &&
// Identify use statements only pertaining to `css-loader`
(use.loader === 'css-loader' ||
use.loader === 'css-loader/locals') &&
use.options &&
typeof use.options === 'object' &&
// The `minimize` property is a good heuristic that we need to
// perform this hack. The `minimize` property was only valid on
// old `css-loader` versions. Custom setups (that aren't next-sass
// or next-less) likely have the newer version.
// We still handle this gracefully below.
(Object.prototype.hasOwnProperty.call(use.options, 'minimize') ||
Object.prototype.hasOwnProperty.call(
use.options,
'exportOnlyLocals'
))
)
) {
return
}
// Try to monkey patch within a try-catch. We shouldn't fail the build
// if we cannot pull this off.
// The user may not even be using the `next-sass` or `next-less`
// plugins.
// If it does work, great!
try {
// Resolve the version of `@zeit/next-css` as depended on by the Sass
// or Less plugin.
const correctNextCss = resolveRequest(
'@zeit/next-css',
isCss
? // Resolve `@zeit/next-css` from the base directory
`${dir}/`
: // Else, resolve it from the specific plugins
require.resolve(
isSass
? '@zeit/next-sass'
: isLess
? '@zeit/next-less'
: 'next'
)
)
// If we found `@zeit/next-css` ...
if (correctNextCss) {
// ... resolve the version of `css-loader` shipped with that
// package instead of whichever was hoisted highest in your
// `node_modules` tree.
const correctCssLoader = resolveRequest(use.loader, correctNextCss)
if (correctCssLoader) {
// We saved the user from a failed build!
use.loader = correctCssLoader
}
}
} catch (_) {
// The error is not required to be handled.
}
})
})
}
// Backwards compat for `main.js` entry key
const originalEntry: any = webpackConfig.entry
if (typeof originalEntry !== 'undefined') {
webpackConfig.entry = async () => {
const entry: WebpackEntrypoints =
typeof originalEntry === 'function'
? await originalEntry()
: originalEntry
// Server compilation doesn't have main.js
if (clientEntries && entry['main.js'] && entry['main.js'].length > 0) {
const originalFile = clientEntries[CLIENT_STATIC_FILES_RUNTIME_MAIN]
// @ts-ignore TODO: investigate type error
entry[CLIENT_STATIC_FILES_RUNTIME_MAIN] = [
...entry['main.js'],
originalFile,
]
}
delete entry['main.js']
return entry
}
}
if (!dev) {
// @ts-ignore entry is always a function
webpackConfig.entry = await webpackConfig.entry()
}
Universal Webpack (#3578) * Speed up next build * Document webpack config * Speed up next build * Remove comment * Add comment * Clean up rules * Add comments * Run in parallel * Push plugins seperately * Create a new chunk for react * Don’t uglify react since it’s already uglified. Move react to commons in development * Use the minified version directly * Re-add globpattern * Move loaders into a separate variable * Add comment linking to Dan’s explanation * Remove dot * Add universal webpack * Initial dev support * Fix linting * Add changes from Arunoda's work * Made next dev works. But super slow and no HMR support. * Fix client side hot reload * Server side hmr * Only in dev * Add on-demand-entries client + hot-middleware * Add .babelrc support * Speed up on demand entries by running in parallel * Serve static generated files * Add missing config in dev * Add sass support * Add support for .map * Add cssloader config and fix .jsx support * Rename * use same defaults as css-loader. Fix linting * Add NoEmitErrorsPlugin * Add clientBootstrap * Use webpackhotmiddleware on the multi compiler * alpha.3 * Use babel 16.2.x * Fix reloading after error * Remove comment * Release 5.0.0-univeral-alpha.1 * Remove check for React 16 * Release 5.0.0-universal-alpha.2 * React hot loader v4 * Use our static file rendering machanism to serve pages. This should work well since the file path for a page is predictable. * Release 5.0.0-universal-alpha.3 * Remove optional loaders * Release 5.0.0-universal-alpha.4 * Remove clientBootstrap * Remove renderScript * Make sure pages bundles are served correctly * Remove unused import * Revert to using the same code as canary * Fix hot loader * Release 5.0.0-universal-alpha.5 * Check if externals dir exist before applying config * Add typescript support * Add support for transpiling certain packages in node_modules Thanks to @giuseppeg’s work in https://github.com/zeit/next.js/pull/3319 * Add BABEL_DISABLE_CACHE support * Make sourcemaps in production opt-in * Revert "Add support for transpiling certain packages in node_modules" This reverts commit d4b1d9babfb4b9ed4f4b12d56d52dee233e862da. In favor of a better api around this. * Support typescript through next.config.js * Remove comments * Bring back commons.js calculation * Remove unused dependencies * Move base.config.js to webpack.js * Make sure to only invalidate webpackDevMiddleware one after other. * Allow babel-loder caching by default. * Add comment about preact support * Bring back buildir replace * Remove obsolete plugin * Remove build replace, speed up build * Resolve page entries like pages/day/index.js to pages/day.js * Add componentDidCatch back * Compile to bundles * Use config.distDir everywhere * Make sure the file is an array * Remove console.log * Apply optimization to uglifyjs * Add comment pointing to source * Create entries the same way in dev and production * Remove unused and broken pagesGlobPattern * day/index.js is automatically turned into day.js at build time * Remove poweredByHeader option * Load pages with the correct path. * Release 5.0.0-universal-alpha.6 * Make sure react-dom/server can be overwritten by module-alias * Only add react-hot-loader babel plugin in dev * Release 5.0.0-universal-alpha.7 * Revert tests * Release 5.0.0-universal-alpha.10 * Make sure next/head is working properly. * Add wepack alias for 'next' back. * Make sure overriding className in next/head works * Alias react too * Add missing r * Fragment fallback has to wrap the children * Use min.js * Remove css.js * Remove wallaby.js * Release 5.0.0-universal-alpha.11 * Resolve relative to workdir instead of next * Make sure we touch the right file * Resolve next modules * Remove dotjsx removal plugins since we use webpack on the server * Revert "Resolve relative to workdir instead of next" This reverts commit a13f3e4ab565df9e2c9a3dfc8eb4009c0c2e02ed. * Externalize any locally loaded module lives outside of app dir. * Remove server aliases * Check node_modules reliably * Add symlink to next for tests * Make sure dynamic imports work locally. This is why we need it: https://github.com/webpack/webpack/blob/b545b519b2024e3f8be3041385bd326bf5d24449/lib/MainTemplate.js#L68 We need to have the finally clause in the above in __webpack_require__. webpack output option strictModuleExceptionHandling does that. * dynmaic -> dynamic * Remove webpack-node-externals * Make sure dynamic imports support SSR. * Remove css support in favor of next-css * Make sure we load path from `/` since it’s included in the path matching * Catch when ensurepage couldn’t be fulfilled for `.js.map` * Register require cache flusher for both client and server * Add comment explaining this is to facilitate hot reloading * Only load module when needed * Remove unused modules * Release 5.0.0-universal-alpha.12 * Only log the `found babel` message once * Make sure ondemand entries working correctly. Now we are just using a single instance of OnDemandEntryHandler. * Better sourcemaps * Release 5.0.0-universal-alpha.13 * Lock uglify version to 1.1.6 * Release 5.0.0-universal-alpha.14 * Fix a typo. * Introduce multi-zones support for mircofrontends * Add section on css
2018-01-30 16:40:52 +01:00
return webpackConfig
2016-10-14 17:05:08 +02:00
}