0

Here is a JS module index.js using ES6 features (const, string interpolation, and arrow function):

const displayTime = () => {
    const now = new Date()
    alert(`It's ${now.toLocaleTimeString()}`)
}

displayTime()

It can be transpiled to ES5 by Babel:

> npm install @babel/cli @babel/preset-env --save-dev
> npx babel --presets=@babel/preset-env src/index.js
"use strict";

var displayTime = function displayTime() {
  var now = new Date();
  alert("It's ".concat(now.toLocaleTimeString()));
};

displayTime();

But when doing so through Webpack Babel Loader (in a fresh folder to avoid conflicts):

> npm install webpack-cli babel-loader @babel/preset-env --save-dev
> cat webpack.config.js
module.exports = {
    module: {
        rules: [
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['@babel/preset-env']
                    }
                }
            }
        ]
    }
}
> npx webpack
asset main.js 73 bytes [compared for emit] [minimized] (name: main)
./src/index.js 136 bytes [built] [code generated]

WARNING in configuration
The 'mode' option has not been set, webpack will fallback to 'production' for this value.
Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/configuration/mode/

webpack 5.64.1 compiled with 1 warning in 754 ms
> cat dist/main.js
(()=>{var t;t=new Date,alert("It's ".concat(t.toLocaleTimeString()))})();

No more const, no more string interpolation, but still arrow function!

To get rid of it I must complete the Webpack configuration with:

output: {
  environment: {
    arrowFunction: false
  }
}

To get:

!function(){var t;t=new Date,alert("It's ".concat(t.toLocaleTimeString()))}();

So it begs 2 questions:

  1. why the default behaviour is not the same?
  2. why configuring Webpack impacts the output? I thought Webpack was not concerned about transpiling but only bundling, or maybe the output/environment/arrowFunction is handled by Babel Loader...
Pragmateek
  • 13,174
  • 9
  • 74
  • 108
  • 1
    That wrapper arrow function is output by Webpack itself, it's not the arrow function from your original code, the minification step removed that one entirely. – loganfsmyth Nov 16 '21 at 00:15
  • Thanks for your answer and the dedup :) Indeed activating the cache of `babel-loader` with the `cache-directory` option I can see that it generates `var displayTime = function displayTime() {\n var now = new Date();\n alert(\"It's \".concat(now.toLocaleTimeString()));\n};\n\ndisplayTime();`, and the Webpack optimizer gets rid of the intermediate variable. – Pragmateek Nov 21 '21 at 20:26

0 Answers0