Transpiling with Babel

In notebook:
FrontEndMasters Webpack Deep Dive
Created at:
2017-01-02
Updated:
2017-01-10
Tags:
JavaScript Webpack libraries
01.4-transpile branch

The Babel loader

You configure this in the ​module​ property of the config object where you can put your loaders.
  // ****   webpack.config.babel.js   ****

...

module.exports = env => {
  const {ifProd, ifNotProd} = getIfUtils(env)
  const config = webpackValidator({
    context: resolve('src'),
    entry: './bootstrap.js',
    output: {
      filename: 'bundle.js',
...
    },
    devtool: ifProd('source-map', 'eval'),
    // 1. ++++ add the module
    module: {
      // 2. ++++ add the loaders array
      loaders: [
        {test: /\.js$/, loaders: ['babel'], exclude: /node_modules/},
      ],
      // you could also say loaders:['babel-loader'] above
    },
  })
  if (env.debug) {
    console.log(config)
    debugger // eslint-disable-line
  }
  return config
}

Loaders

Loaders have a ​test​ property to know which files to apply to and the ​loaders​   array to set the loaders to use. 
Exclude files
Normally node modules authors should have already published transpiled code, so we can exclude the node_modules directory to save time. (see above snippet)

That's all to do transpiling with Babel! 

+ install some dependencies:
  //  **** package.json   ****

  "devDependencies": {
    // 1. ++++ install these
    "babel-core": "6.13.2",
    // need to use the babel loader in Webpack (above)
    "babel-loader": "6.2.4",
    "babel-preset-es2015": "6.13.2",
    "babel-preset-es2016": "6.11.3",
    "babel-preset-stage-2": "6.13.0",
    // 1. ++++ END
    "eslint": "3.2.2",
One more thing

Configure Babel with .babelrc

By default Babel will not do anything with the JavaScript files. You need to add a .babelrc file to tell it what you want to add
  // ****   .babelrc  ****

{
  "presets": ["es2015", "es2016", "stage-2"],
}

Add custom loader

  loaders: [
        {test: /\.js$/, loaders: ['babel', resolve('./foo/bar/my-loader.js')], exclude: /node_modules/},
      ],