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

218 lines
5.8 KiB
JavaScript
Raw Normal View History

2016-10-15 16:17:27 +00:00
import { resolve, join } from 'path'
import { createHash } from 'crypto'
import { existsSync } from 'fs'
2016-10-14 15:05:08 +00:00
import webpack from 'webpack'
import glob from 'glob-promise'
2016-10-15 19:49:42 +00:00
import WriteFilePlugin from 'write-file-webpack-plugin'
import FriendlyErrorsWebpackPlugin from 'friendly-errors-webpack-plugin'
2016-10-23 16:42:13 +00:00
import UnlinkFilePlugin from './plugins/unlink-file-plugin'
import WatchPagesPlugin from './plugins/watch-pages-plugin'
import WatchRemoveEventPlugin from './plugins/watch-remove-event-plugin'
import DynamicEntryPlugin from './plugins/dynamic-entry-plugin'
import DetachPlugin from './plugins/detach-plugin'
import JsonPagesPlugin from './plugins/json-pages-plugin'
import getConfig from '../config'
2016-10-14 15:05:08 +00:00
const documentPage = join('pages', '_document.js')
const defaultPages = [
'_error.js',
'_error-debug.js',
'_document.js'
]
2016-12-21 14:39:08 +00:00
export default async function createCompiler (dir, { dev = false, quiet = false } = {}) {
2016-10-15 16:17:27 +00:00
dir = resolve(dir)
const config = getConfig(dir)
2016-10-15 16:17:27 +00:00
const pages = await glob('pages/**/*.js', { cwd: dir })
2016-10-14 15:05:08 +00:00
const entry = {
'main.js': dev ? require.resolve('../../client/next-dev') : require.resolve('../../client/next')
}
const defaultEntries = dev
? [join(__dirname, '..', '..', 'client/webpack-hot-middleware-client')] : []
2016-10-14 15:05:08 +00:00
for (const p of pages) {
entry[join('bundles', p)] = defaultEntries.concat([`./${p}?entry`])
2016-10-14 15:05:08 +00:00
}
2016-10-19 12:58:08 +00:00
const nextPagesDir = join(__dirname, '..', '..', 'pages')
const interpolateNames = new Map()
2016-10-19 12:41:45 +00:00
for (const p of defaultPages) {
const entryName = join('bundles', 'pages', p)
const path = join(nextPagesDir, p)
if (!entry[entryName]) {
entry[entryName] = defaultEntries.concat([path + '?entry'])
}
interpolateNames.set(path, `dist/pages/${p}`)
}
2016-10-14 15:05:08 +00:00
const nextNodeModulesDir = join(__dirname, '..', '..', '..', 'node_modules')
const minChunks = pages.filter((p) => p !== documentPage).length
2016-10-14 15:05:08 +00:00
2016-10-16 02:49:09 +00:00
const plugins = [
new webpack.LoaderOptionsPlugin({
options: {
context: dir,
customInterpolateName (url, name, opts) {
return interpolateNames.get(this.resourcePath) || url
}
}
}),
2016-10-18 14:14:00 +00:00
new WriteFilePlugin({
exitOnErrors: false,
2016-10-23 16:42:13 +00:00
log: false,
// required not to cache removed files
useHashIndex: false
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'commons',
filename: 'commons.js',
minChunks: Math.max(2, minChunks)
}),
new JsonPagesPlugin()
]
if (dev) {
plugins.push(
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new DetachPlugin(),
new DynamicEntryPlugin(),
new UnlinkFilePlugin(),
new WatchRemoveEventPlugin(),
2016-12-21 14:39:08 +00:00
new WatchPagesPlugin(dir)
)
2016-12-21 14:39:08 +00:00
if (!quiet) {
plugins.push(new FriendlyErrorsWebpackPlugin())
}
} else {
plugins.push(
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production')
}),
new webpack.optimize.UglifyJsPlugin({
compress: { warnings: false },
sourceMap: false
})
)
}
2016-10-15 19:49:42 +00:00
const mainBabelOptions = {
babelrc: true,
cacheDirectory: true,
sourceMaps: dev ? 'both' : false,
presets: []
}
const hasBabelRc = existsSync(join(dir, '.babelrc'))
if (hasBabelRc) {
console.log('> Using .babelrc defined in your app root')
} else {
mainBabelOptions.presets.push(require.resolve('./babel/preset'))
}
const rules = (dev ? [{
test: /\.js(\?[^?]*)?$/,
loader: 'hot-self-accept-loader',
include: [
join(dir, 'pages'),
nextPagesDir
]
2016-12-05 17:09:38 +00:00
}, {
test: /\.js(\?[^?]*)?$/,
2016-12-05 17:09:38 +00:00
loader: 'react-hot-loader/webpack',
exclude: /node_modules/
}] : [])
.concat([{
test: /\.json$/,
loader: 'json-loader'
}, {
test: /\.(js|json)(\?[^?]*)?$/,
2016-10-15 16:17:27 +00:00
loader: 'emit-file-loader',
2016-10-19 12:41:45 +00:00
include: [dir, nextPagesDir],
2016-10-25 09:11:39 +00:00
exclude (str) {
return /node_modules/.test(str) && str.indexOf(nextPagesDir) !== 0
},
options: {
2016-10-17 03:55:09 +00:00
name: 'dist/[path][name].[ext]'
2016-10-15 16:17:27 +00:00
}
}, {
loader: 'babel-loader',
include: nextPagesDir,
options: {
2016-12-11 09:09:54 +00:00
babelrc: false,
cacheDirectory: true,
sourceMaps: dev ? 'both' : false,
plugins: [
[
require.resolve('babel-plugin-module-resolver'),
{
alias: {
'ansi-html': require.resolve('ansi-html'),
'styled-jsx/style': require.resolve('styled-jsx/style')
}
}
]
]
}
}, {
test: /\.js(\?[^?]*)?$/,
loader: 'babel-loader',
2016-10-19 12:41:45 +00:00
include: [dir, nextPagesDir],
2016-10-25 09:11:39 +00:00
exclude (str) {
return /node_modules/.test(str) && str.indexOf(nextPagesDir) !== 0
2016-10-25 09:11:39 +00:00
},
query: mainBabelOptions
2016-10-19 12:41:45 +00:00
}])
let webpackConfig = {
2016-10-14 15:05:08 +00:00
context: dir,
entry,
output: {
2016-10-19 12:58:08 +00:00
path: join(dir, '.next'),
2016-10-14 15:05:08 +00:00
filename: '[name]',
libraryTarget: 'commonjs2',
publicPath: '/_webpack/',
devtoolModuleFilenameTemplate ({ resourcePath }) {
const hash = createHash('sha1')
hash.update(Date.now() + '')
const id = hash.digest('hex').slice(0, 7)
// append hash id for cache busting
return `webpack:///${resourcePath}?${id}`
}
2016-10-14 15:05:08 +00:00
},
resolve: {
modules: [
nextNodeModulesDir,
2017-01-01 05:57:13 +00:00
'node_modules'
].concat(
(process.env.NODE_PATH || '')
.split(process.platform === 'win32' ? ';' : ':')
.filter((p) => !!p)
)
2016-10-14 15:05:08 +00:00
},
resolveLoader: {
modules: [
nextNodeModulesDir,
2017-01-01 05:57:13 +00:00
'node_modules',
2016-10-19 12:58:08 +00:00
join(__dirname, 'loaders')
2016-10-14 15:05:08 +00:00
]
},
2016-10-15 19:49:42 +00:00
plugins,
2016-10-14 15:05:08 +00:00
module: {
rules
2016-10-16 04:01:17 +00:00
},
devtool: dev ? 'inline-source-map' : false,
performance: { hints: false }
}
if (config.webpack) {
console.log('> Using "webpack" config function defined in next.config.js.')
webpackConfig = await config.webpack(webpackConfig, { dev })
}
return webpack(webpackConfig)
2016-10-14 15:05:08 +00:00
}