1
0
Fork 0
mirror of https://github.com/terribleplan/next.js.git synced 2024-01-19 02:48:18 +00:00

Eliminate context code based on process.browser (#5159)

* Allow deadCodeElemination when using process.browser

* Add process.browser test
This commit is contained in:
Henrik Wenz 2018-09-23 16:02:28 +02:00 committed by Tim Neutkens
parent 80a6160caf
commit 7ebcc5bec9
3 changed files with 35 additions and 0 deletions

View file

@ -274,6 +274,10 @@ export default async function getBaseWebpackConfig (dir: string, {dev = false, i
// required not to cache removed files
useHashIndex: false
}),
// Removes server/client code by minifier
new webpack.DefinePlugin({
'process.browser': JSON.stringify(!isServer)
}),
// This is used in client/dev-error-overlay/hot-dev-client.js to replace the dist directory
!isServer && dev && new webpack.DefinePlugin({
'process.env.__NEXT_DIST_DIR': JSON.stringify(distDir)

View file

@ -1,3 +1,12 @@
if (process.browser) {
global.__THIS_SHOULD_ONLY_BE_DEFINED_IN_BROWSER_CONTEXT__ = true
}
if (!process.browser) {
global.__THIS_SHOULD_ONLY_BE_DEFINED_IN_SERVER_CONTEXT__ = true
}
export default () => (
<div id='node-env'>{process.env.NODE_ENV}</div>
)

View file

@ -1,5 +1,11 @@
/* global describe, it, expect */
import webdriver from 'next-webdriver'
import { readFile } from 'fs'
import { promisify } from 'util'
import { join } from 'path'
const readFileAsync = promisify(readFile)
const readNextBuildFile = (relativePath) => readFileAsync(join(__dirname, '../.next', relativePath), 'utf8')
export default (context) => {
describe('process.env', () => {
@ -10,4 +16,20 @@ export default (context) => {
browser.close()
})
})
describe('process.browser', () => {
it('should eliminate server only code on the client', async () => {
const buildId = await readNextBuildFile('./BUILD_ID')
const clientCode = await readNextBuildFile(`./static/${buildId}/pages/process-env.js`)
expect(clientCode).toMatch(/__THIS_SHOULD_ONLY_BE_DEFINED_IN_BROWSER_CONTEXT__/)
expect(clientCode).not.toMatch(/__THIS_SHOULD_ONLY_BE_DEFINED_IN_SERVER_CONTEXT__/)
})
it('should eliminate client only code on the server', async () => {
const buildId = await readNextBuildFile('./BUILD_ID')
const serverCode = await readNextBuildFile(`./server/static/${buildId}/pages/process-env.js`)
expect(serverCode).not.toMatch(/__THIS_SHOULD_ONLY_BE_DEFINED_IN_BROWSER_CONTEXT__/)
expect(serverCode).toMatch(/__THIS_SHOULD_ONLY_BE_DEFINED_IN_SERVER_CONTEXT__/)
})
})
}