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/babel/index.js
Arunoda Susiripala ac2a71876d Add support for using .babelrc in the app root. (#493)
* Add support for using .babelrc in the app root.

* Update the README about the .babelrc usage.

* Fix a typo.

* Remove additional example usage.
2016-12-26 10:13:45 -08:00

48 lines
1.1 KiB
JavaScript

import { resolve, join, dirname } from 'path'
import { existsSync } from 'fs'
import { readFile, writeFile } from 'mz/fs'
import { transform } from 'babel-core'
import chokidar from 'chokidar'
import mkdirp from 'mkdirp-then'
export default babel
async function babel (dir, { dev = false } = {}) {
dir = resolve(dir)
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
}
}
let babelOptions = {
babelrc: true,
sourceMaps: dev ? 'inline' : false,
presets: []
}
const hasBabelRc = existsSync(join(dir, '.babelrc'))
if (!hasBabelRc) {
babelOptions.presets.push(require.resolve('./preset'))
}
const { code } = transform(src, babelOptions)
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
})
}