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:
- why the default behaviour is not the same?
- 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...