Babel has become the de-facto standard to compile ECMAScript 6 applications to a version of ECMAScript that can run in current browsers.
I recently updated an older project to Babel version 7. Read on for some advice how to update.
@babel
At first you will notice that the new package ecosystem now exists as a monorepo and all npm modules are namespaced behind the @babel organization handle.
babel-preset-env
The “env” preset has been out for a while and it replaces some of the earlier “year presets” that was recommeneded before. I’ve been using env
a while and it is very convenient. From the babel-preset-env website:
Without any configuration options, @babel/preset-env behaves exactly the same as @babel/preset-es2015, @babel/preset-es2016 and @babel/preset-es2017 together (or the deprecated babel-preset-latest).
Uninstall old dependencies
First up let’s remove some older packages:
npm uninstall -D babel babel-register babel-preset-env babel-polyfill babel-cli babel-core
Add new packages
Depending on what packages you need, now continue to install the new ones:
npm i -D @babel/core @babel/preset-env
My package.json
now looks like this:
"devDependencies": {
"@babel/core": "^7.0.0-beta.54",
"@babel/preset-env": "^7.0.0-beta.54",
...
}
Presets
With the packages updated, adjust the package.json
, .babelrc
or .babelrc.js
. I adjusted my .babelrc
like this:
{
"presets": [
["@babel/preset-env", {
"targets": {
"browsers": ["last 2 versions"]
}
}]
]
}
Tip
If you want to specify target browsers, simply use the "targets.browsers"
option like above. You can also use a .browserslistrc
config, which is also used by many tools.
Update an old Gulp task
I this project I have a workflow to process ES6+ code that is using Browserify and Babelify. Later on I might replace this with Webpack, but for now an update will work just fine. Let’s dive in.
Upgrade babelify:
npm i -D babelify@next
Upgrade uglify
npm i -D gulp-uglify-es
My gulp task now looks like this:
const isProduction = process.env.NODE_ENV === 'production'
gulp.task('js', () => {
return browserify({
entries: `${config.basePaths.scripts.base}app.js`,
debug: true
})
.transform('babelify', { presets: ['@babel/preset-env'] })
.bundle()
.on('error', err => {
console.log(err.message)
})
.pipe(plumber())
.pipe(source('app.js'))
.pipe(buffer())
.pipe(gulpif(isProduction, uglify()))
...
npm tips
-
Tip 1: You can run
npx npm-check -u
for an interactive list of all your dependencies and their upgrade status. It’s pretty rad. Read more about it -
Tip 2:
i
is short fornpm install
-D
is short for--save-dev
More reading
More detailed info about the migration