Commit dbecc2a7 authored by Naoyuki Kanezawa's avatar Naoyuki Kanezawa Committed by Guillermo Rauch

Use dynamic entry feature of webpack (#750)

* update webpack version and use dynamic entry feature of it

* fix typo
parent e3e0a68b
......@@ -79,7 +79,7 @@
"styled-jsx": "0.4.1",
"url": "0.11.0",
"uuid": "3.0.1",
"webpack": "2.2.0-rc.3",
"webpack": "2.2.0-rc.4",
"webpack-dev-middleware": "1.9.0",
"webpack-hot-middleware": "2.15.0",
"write-file-webpack-plugin": "3.4.2"
......
export default class DetachPlugin {
apply (compiler) {
compiler.pluginDetachFns = new Map()
compiler.plugin = plugin(compiler.plugin)
compiler.apply = apply
compiler.detach = detach
compiler.getDetachablePlugins = getDetachablePlugins
}
}
export function detachable (Plugin) {
const { apply } = Plugin.prototype
Plugin.prototype.apply = function (compiler) {
const fns = []
const { plugin } = compiler
compiler.plugin = function (name, fn) {
fns.push(plugin.call(this, name, fn))
}
// collect the result of `plugin` call in `apply`
apply.call(this, compiler)
compiler.plugin = plugin
return fns
}
}
function plugin (original) {
return function (name, fn) {
original.call(this, name, fn)
return () => {
const names = Array.isArray(name) ? name : [name]
for (const n of names) {
const plugins = this._plugins[n] || []
const i = plugins.indexOf(fn)
if (i >= 0) plugins.splice(i, 1)
}
}
}
}
function apply (...plugins) {
for (const p of plugins) {
const fn = p.apply(this)
if (!fn) continue
const fns = this.pluginDetachFns.get(p) || new Set()
const _fns = Array.isArray(fn) ? fn : [fn]
for (const f of _fns) fns.add(f)
this.pluginDetachFns.set(p, fns)
}
}
function detach (...plugins) {
for (const p of plugins) {
const fns = this.pluginDetachFns.get(p) || new Set()
for (const fn of fns) {
if (typeof fn === 'function') fn()
}
this.pluginDetachFns.delete(p)
}
}
function getDetachablePlugins () {
return new Set(this.pluginDetachFns.keys())
}
import SingleEntryPlugin from 'webpack/lib/SingleEntryPlugin'
import MultiEntryPlugin from 'webpack/lib/MultiEntryPlugin'
import { detachable } from './detach-plugin'
detachable(SingleEntryPlugin)
detachable(MultiEntryPlugin)
export default class DynamicEntryPlugin {
apply (compiler) {
compiler.entryNames = getInitialEntryNames(compiler)
compiler.addEntry = addEntry
compiler.removeEntry = removeEntry
compiler.hasEntry = hasEntry
compiler.plugin('emit', (compilation, callback) => {
compiler.cache = compilation.cache
callback()
})
}
}
function getInitialEntryNames (compiler) {
const entryNames = new Set()
const { entry } = compiler.options
if (typeof entry === 'string' || Array.isArray(entry)) {
entryNames.add('main')
} else if (typeof entry === 'object') {
Object.keys(entry).forEach((name) => {
entryNames.add(name)
})
}
return entryNames
}
function addEntry (entry, name = 'main') {
const { context } = this.options
const Plugin = Array.isArray(entry) ? MultiEntryPlugin : SingleEntryPlugin
this.apply(new Plugin(context, entry, name))
this.entryNames.add(name)
}
function removeEntry (name = 'main') {
for (const p of this.getDetachablePlugins()) {
if (!(p instanceof SingleEntryPlugin || p instanceof MultiEntryPlugin)) continue
if (p.name !== name) continue
if (this.cache) {
for (const id of Object.keys(this.cache)) {
const m = this.cache[id]
if (m.name === name) {
// cache of `MultiModule` is based on `name`,
// so delete it here for the case
// a new entry is added with the same name later
delete this.cache[id]
}
}
}
this.detach(p)
}
this.entryNames.delete(name)
}
function hasEntry (name = 'main') {
return this.entryNames.has(name)
}
import { resolve, relative, join, extname } from 'path'
const hotMiddlewareClientPath = join(__dirname, '..', '..', '..', 'client/webpack-hot-middleware-client')
const defaultPages = new Map()
for (const p of ['_error.js', '_document.js']) {
defaultPages.set(
join('bundles', 'pages', p),
join(__dirname, '..', '..', '..', 'pages', p)
)
}
import { resolve, join } from 'path'
export default class WatchPagesPlugin {
constructor (dir) {
this.dir = resolve(dir, 'pages')
this.prevFileDependencies = []
}
apply (compiler) {
......@@ -28,55 +17,12 @@ export default class WatchPagesPlugin {
compiler.plugin('emit', (compilation, callback) => {
// watch the pages directory
compilation.contextDependencies =
compilation.contextDependencies.concat([this.dir])
this.prevFileDependencies = compilation.fileDependencies
callback()
})
const isPageFile = this.isPageFile.bind(this)
const getEntryName = (f) => {
return join('bundles', relative(compiler.options.context, f))
}
compiler.plugin('watch-run', (watching, callback) => {
Object.keys(compiler.fileTimestamps)
.filter(isPageFile)
.filter((f) => this.prevFileDependencies.indexOf(f) < 0)
.forEach((f) => {
const name = getEntryName(f)
if (defaultPages.has(name)) {
compiler.removeEntry(name)
}
if (compiler.hasEntry(name)) return
const entries = [hotMiddlewareClientPath, f + '?entry']
compiler.addEntry(entries, name)
})
compiler.removedFiles
.filter(isPageFile)
.forEach((f) => {
const name = getEntryName(f)
compiler.removeEntry(name)
if (defaultPages.has(name)) {
compiler.addEntry([
hotMiddlewareClientPath,
defaultPages.get(name) + '?entry'
], name)
}
})
compilation.contextDependencies = [
...compilation.contextDependencies,
this.dir
]
callback()
})
}
isPageFile (f) {
return f.indexOf(this.dir) === 0 && extname(f) === '.js'
}
}
......@@ -9,8 +9,6 @@ import CaseSensitivePathPlugin from 'case-sensitive-paths-webpack-plugin'
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'
......@@ -19,37 +17,42 @@ const defaultPages = [
'_error.js',
'_document.js'
]
const nextPagesDir = join(__dirname, '..', '..', 'pages')
const nextNodeModulesDir = join(__dirname, '..', '..', '..', 'node_modules')
const interpolateNames = new Map(defaultPages.map((p) => {
return [join(nextPagesDir, p), `dist/pages/${p}`]
}))
export default async function createCompiler (dir, { dev = false, quiet = false } = {}) {
dir = resolve(dir)
const config = getConfig(dir)
const pages = await glob('pages/**/*.js', { cwd: dir })
const entry = {
'main.js': dev ? require.resolve('../../client/next-dev') : require.resolve('../../client/next')
}
const defaultEntries = dev
? [join(__dirname, '..', '..', 'client/webpack-hot-middleware-client')] : []
for (const p of pages) {
entry[join('bundles', p)] = defaultEntries.concat([`./${p}?entry`])
}
const mainJS = dev
? require.resolve('../../client/next-dev') : require.resolve('../../client/next')
let minChunks
const nextPagesDir = join(__dirname, '..', '..', 'pages')
const interpolateNames = new Map()
const entry = async () => {
const entries = { 'main.js': mainJS }
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'])
const pages = await glob('pages/**/*.js', { cwd: dir })
for (const p of pages) {
entries[join('bundles', p)] = [...defaultEntries, `./${p}?entry`]
}
interpolateNames.set(path, `dist/pages/${p}`)
}
const nextNodeModulesDir = join(__dirname, '..', '..', '..', 'node_modules')
const minChunks = pages.filter((p) => p !== documentPage).length
for (const p of defaultPages) {
const entryName = join('bundles', 'pages', p)
if (!entries[entryName]) {
entries[entryName] = [...defaultEntries, join(nextPagesDir, p) + '?entry']
}
}
// calculate minChunks of CommonsChunkPlugin for later use
minChunks = Math.max(2, pages.filter((p) => p !== documentPage).length)
return entries
}
const plugins = [
new webpack.LoaderOptionsPlugin({
......@@ -69,7 +72,11 @@ export default async function createCompiler (dir, { dev = false, quiet = false
new webpack.optimize.CommonsChunkPlugin({
name: 'commons',
filename: 'commons.js',
minChunks: Math.max(2, minChunks)
minChunks (module, count) {
// NOTE: it depends on the fact that the entry funtion is always called
// before applying CommonsChunkPlugin
return count >= minChunks
}
}),
new JsonPagesPlugin(),
new CaseSensitivePathPlugin()
......@@ -78,9 +85,7 @@ export default async function createCompiler (dir, { dev = false, quiet = false
if (dev) {
plugins.push(
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new DetachPlugin(),
new DynamicEntryPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new UnlinkFilePlugin(),
new WatchRemoveEventPlugin(),
new WatchPagesPlugin(dir)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment