Search code examples
javascriptwebpackbabel-loader

babel-loader is not interpolating in transpiled file


I'm learning webpack, and have a simple javascript that uses a bit of ES6.

function sayHello(){
  let tool = 'webpack';
  alert('Hello I am ${tool}, welcome to ES6');
}

/*module.exports = sayHello;*/

// use ES6 modules
export { sayHello };

I've configured a babel-loader like so

 module: {
    rules: [
      {
        test: /\.m?js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env']
          }
        }
      }
    ]
  }

If I check the transpiled file I see that it converted the let to var, but I was expecting that it will interpolate the '${tool}' to something like '.concat(tool,...').

What am I missing?


Solution

  • @babel/preset-env will only use transformations for specific targets. That means only a couple of transformations are applied if the environment targeted is fairly new or a lot of transformations are applied if the targeted environment is old.

    You can check the default by using:

    npx browserlist
    

    Which should give you the list of browsers @babel/preset-env is targeting.

    That being said though. What you have there does not require a transformation. You are probably thinking on template literals:

    alert(`Hello I am ${tool}, welcome to ES6`);
    

    Notice the character ` is different from '.

    Which I believe should be transformed on default installations as of writing of this post. Since IE11 does not have support for template literals and it's on the browsers list.