2016-12-21 02:01:56 +00:00
|
|
|
import { resolve, join, dirname } from 'path'
|
|
|
|
import { readFile, writeFile } from 'mz/fs'
|
|
|
|
import { transform } from 'babel-core'
|
|
|
|
import chokidar from 'chokidar'
|
|
|
|
import mkdirp from 'mkdirp-then'
|
2016-12-22 01:36:00 +00:00
|
|
|
import getConfig from '../../config'
|
2016-12-21 02:01:56 +00:00
|
|
|
|
|
|
|
export default babel
|
|
|
|
|
|
|
|
async function babel (dir, { dev = false } = {}) {
|
|
|
|
dir = resolve(dir)
|
2016-12-22 01:36:00 +00:00
|
|
|
const config = getConfig('../')
|
2016-12-21 02:01:56 +00:00
|
|
|
|
|
|
|
let src
|
|
|
|
try {
|
|
|
|
src = await readFile(join(dir, 'pages', '_document.js'), 'utf8')
|
|
|
|
} catch (err) {
|
|
|
|
if (err.code === 'ENOENT') {
|
|
|
|
src = await readFile(join(__dirname, '..', '..', '..', 'pages', '_document.js'), 'utf8')
|
|
|
|
} else {
|
|
|
|
throw err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-12-22 01:36:00 +00:00
|
|
|
let babelOptions = {
|
2016-12-21 02:01:56 +00:00
|
|
|
babelrc: false,
|
|
|
|
sourceMaps: dev ? 'inline' : false,
|
|
|
|
presets: [require.resolve('./preset')]
|
2016-12-22 01:36:00 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if (config.babel) {
|
|
|
|
console.log('> Using "babel" config function defined in next.config.js.')
|
|
|
|
babelOptions = await config.babel(babelOptions, { dev })
|
|
|
|
}
|
|
|
|
|
|
|
|
const { code } = transform(src, babelOptions)
|
2016-12-21 02:01:56 +00:00
|
|
|
|
|
|
|
const file = join(dir, '.next', 'dist', 'pages', '_document.js')
|
|
|
|
await mkdirp(dirname(file))
|
|
|
|
await writeFile(file, code)
|
|
|
|
}
|
|
|
|
|
|
|
|
export function watch (dir) {
|
|
|
|
return chokidar.watch('pages/_document.js', {
|
|
|
|
cwd: dir,
|
|
|
|
ignoreInitial: true
|
|
|
|
})
|
|
|
|
}
|