1
0
Fork 0
mirror of https://github.com/terribleplan/next.js.git synced 2024-01-19 02:48:18 +00:00
next.js/server/build/webpack.js
Tim Neutkens e093441bad 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: b545b519b2/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:44:44 +01:00

306 lines
9.9 KiB
JavaScript

import path, {sep} from 'path'
import webpack from 'webpack'
import resolve from 'resolve'
import UglifyJSPlugin from 'uglifyjs-webpack-plugin'
import CaseSensitivePathPlugin from 'case-sensitive-paths-webpack-plugin'
import WriteFilePlugin from 'write-file-webpack-plugin'
import FriendlyErrorsWebpackPlugin from 'friendly-errors-webpack-plugin'
import {getPages} from './webpack/utils'
import CombineAssetsPlugin from './plugins/combine-assets-plugin'
import PagesPlugin from './plugins/pages-plugin'
import NextJsSsrImportPlugin from './plugins/nextjs-ssr-import'
import DynamicChunksPlugin from './plugins/dynamic-chunks-plugin'
import UnlinkFilePlugin from './plugins/unlink-file-plugin'
import findBabelConfig from './babel/find-config'
const nextDir = path.join(__dirname, '..', '..', '..')
const nextNodeModulesDir = path.join(nextDir, 'node_modules')
const nextPagesDir = path.join(nextDir, 'pages')
const defaultPages = [
'_error.js',
'_document.js'
]
const interpolateNames = new Map(defaultPages.map((p) => {
return [path.join(nextPagesDir, p), `dist/bundles/pages/${p}`]
}))
function babelConfig (dir, {isServer, dev}) {
const mainBabelOptions = {
cacheDirectory: true,
presets: [],
plugins: [
dev && !isServer && require.resolve('react-hot-loader/babel')
].filter(Boolean)
}
const externalBabelConfig = findBabelConfig(dir)
if (externalBabelConfig) {
// Log it out once
if (!isServer) {
console.log(`> Using external babel configuration`)
console.log(`> Location: "${externalBabelConfig.loc}"`)
}
// It's possible to turn off babelrc support via babelrc itself.
// In that case, we should add our default preset.
// That's why we need to do this.
const { options } = externalBabelConfig
mainBabelOptions.babelrc = options.babelrc !== false
} else {
mainBabelOptions.babelrc = false
}
// Add our default preset if the no "babelrc" found.
if (!mainBabelOptions.babelrc) {
mainBabelOptions.presets.push(require.resolve('./babel/preset'))
}
return mainBabelOptions
}
function externalsConfig (dir, isServer) {
const externals = []
if (!isServer) {
return externals
}
// This will externalize all the 'next/xxx' modules to load from
// node_modules always.
// This is very useful in Next.js development where we use symlinked version
// of Next.js or using next/xxx inside test apps.
externals.push((context, request, callback) => {
resolve(request, { basedir: dir, preserveSymlinks: true }, (err, res) => {
if (err) {
return callback()
}
if (res.match(/node_modules/)) {
return callback(null, `commonjs ${request}`)
}
callback()
})
})
return externals
}
export default async function getBaseWebpackConfig (dir, {dev = false, isServer = false, buildId, config}) {
const babelLoaderOptions = babelConfig(dir, {dev, isServer})
const defaultLoaders = {
babel: {
loader: 'babel-loader',
options: babelLoaderOptions
}
}
let totalPages
let webpackConfig = {
devtool: dev ? 'source-map' : false,
name: isServer ? 'server' : 'client',
cache: true,
target: isServer ? 'node' : 'web',
externals: externalsConfig(dir, isServer),
context: dir,
entry: async () => {
const pages = await getPages(dir, {dev, isServer})
totalPages = Object.keys(pages).length
const mainJS = require.resolve(`../../client/next${dev ? '-dev' : ''}`)
const clientConfig = !isServer ? {
'main.js': [
dev && !isServer && path.join(__dirname, '..', '..', 'client', 'webpack-hot-middleware-client'),
dev && !isServer && path.join(__dirname, '..', '..', 'client', 'on-demand-entries-client'),
mainJS
].filter(Boolean)
} : {}
return {
...clientConfig,
...pages
}
},
output: {
path: path.join(dir, config.distDir, isServer ? 'dist' : ''), // server compilation goes to `.next/dist`
filename: '[name]',
libraryTarget: 'commonjs2',
publicPath: `${config.assetPrefix}/_next/webpack/`,
// This saves chunks with the name given via require.ensure()
chunkFilename: '[name]-[chunkhash].js',
strictModuleExceptionHandling: true,
devtoolModuleFilenameTemplate: '[absolute-resource-path]'
},
performance: { hints: false },
resolve: {
extensions: ['.js', '.jsx', '.json'],
modules: [
nextNodeModulesDir,
'node_modules'
],
alias: {
next: nextDir,
// This bypasses React's check for production mode. Since we know it is in production this way.
// This allows us to exclude React from being uglified. Saving multiple seconds per build.
react: dev ? 'react/cjs/react.development.js' : 'react/cjs/react.production.min.js',
'react-dom': dev ? 'react-dom/cjs/react-dom.development.js' : 'react-dom/cjs/react-dom.production.min.js'
}
},
resolveLoader: {
modules: [
nextNodeModulesDir,
'node_modules',
path.join(__dirname, 'loaders')
]
},
module: {
rules: [
dev && !isServer && {
test: /\.(js|jsx)(\?[^?]*)?$/,
loader: 'hot-self-accept-loader',
include: [
path.join(dir, 'pages'),
nextPagesDir
]
},
{
test: /\.+(js|jsx)$/,
include: [dir],
exclude: /node_modules/,
use: defaultLoaders.babel
}
].filter(Boolean)
},
plugins: [
new webpack.IgnorePlugin(/(precomputed)/, /node_modules.+(elliptic)/),
dev && new webpack.NoEmitOnErrorsPlugin(),
dev && !isServer && new FriendlyErrorsWebpackPlugin(),
dev && new webpack.NamedModulesPlugin(),
dev && !isServer && new webpack.HotModuleReplacementPlugin(), // Hot module replacement
dev && new UnlinkFilePlugin(),
dev && new CaseSensitivePathPlugin(), // Since on macOS the filesystem is case-insensitive this will make sure your path are case-sensitive
dev && new webpack.LoaderOptionsPlugin({
options: {
context: dir,
customInterpolateName (url, name, opts) {
return interpolateNames.get(this.resourcePath) || url
}
}
}),
dev && new WriteFilePlugin({
exitOnErrors: false,
log: false,
// required not to cache removed files
useHashIndex: false
}),
!dev && new webpack.IgnorePlugin(/react-hot-loader/),
!isServer && !dev && new UglifyJSPlugin({
exclude: /react\.js/,
parallel: true,
sourceMap: false,
uglifyOptions: {
compress: {
arrows: false,
booleans: false,
collapse_vars: false,
comparisons: false,
computed_props: false,
hoist_funs: false,
hoist_props: false,
hoist_vars: false,
if_return: false,
inline: false,
join_vars: false,
keep_infinity: true,
loops: false,
negate_iife: false,
properties: false,
reduce_funcs: false,
reduce_vars: false,
sequences: false,
side_effects: false,
switches: false,
top_retain: false,
toplevel: false,
typeofs: false,
unused: false,
conditionals: false,
dead_code: true,
evaluate: false
}
}
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(dev ? 'development' : 'production')
}),
!isServer && new CombineAssetsPlugin({
input: ['manifest.js', 'react.js', 'commons.js', 'main.js'],
output: 'app.js'
}),
!dev && new webpack.optimize.ModuleConcatenationPlugin(),
!isServer && new PagesPlugin(),
!isServer && new DynamicChunksPlugin(),
isServer && new NextJsSsrImportPlugin({ dir, dist: config.distDir }),
!isServer && new webpack.optimize.CommonsChunkPlugin({
name: `commons`,
filename: `commons.js`,
minChunks (module, count) {
// We need to move react-dom explicitly into common chunks.
// Otherwise, if some other page or module uses it, it might
// included in that bundle too.
if (dev && module.context && module.context.indexOf(`${sep}react${sep}`) >= 0) {
return true
}
if (dev && module.context && module.context.indexOf(`${sep}react-dom${sep}`) >= 0) {
return true
}
// In the dev we use on-demand-entries.
// So, it makes no sense to use commonChunks based on the minChunks count.
// Instead, we move all the code in node_modules into each of the pages.
if (dev) {
return false
}
// If there are one or two pages, only move modules to common if they are
// used in all of the pages. Otherwise, move modules used in at-least
// 1/2 of the total pages into commons.
if (totalPages <= 2) {
return count >= totalPages
}
return count >= totalPages * 0.5
}
}),
!isServer && new webpack.optimize.CommonsChunkPlugin({
name: 'react',
filename: 'react.js',
minChunks (module, count) {
if (dev) {
return false
}
if (module.resource && module.resource.includes(`${sep}react-dom${sep}`) && count >= 0) {
return true
}
if (module.resource && module.resource.includes(`${sep}react${sep}`) && count >= 0) {
return true
}
return false
}
}),
!isServer && new webpack.optimize.CommonsChunkPlugin({
name: 'manifest',
filename: 'manifest.js'
})
].filter(Boolean)
}
if (typeof config.webpack === 'function') {
webpackConfig = config.webpack(webpackConfig, {dir, dev, isServer, buildId, config, defaultLoaders})
}
return webpackConfig
}