I have a WebGL project where every micro optimization matters. For readibility I use .forEach, .map, .filter and for of loops but I would like to transpile them to simple (reversed) length based for loops in my production code due to performance reasons. Could you please advise how to achieve that using Webpack? I am curious about best practices in this topic.
As it turned out, there are two Babel plugins available that do the job quite well.
@babel/plugin-transform-for-of transpiles for of loops to index based loops
babel-plugin-loop-optimizer transpiles .forEach, .every, .find, .map, .filter statements to index based for loops
In my configuration, I use Webpack and ts-loader to transpile TypeScript. To use these Babel plugins while keeping the ts-loader I chain the two loaders, thus Babel plugins will optimize the js code that comes out of ts-loader.
webpack.config.js:
{
test: /\.tsx?$/,
use: [
{ // babel-loader runs second and receives output of ts-loader
loader: 'babel-loader'
},
{ // ts-loader runs first
loader: 'ts-loader',
options: {
// ts-loader options
},
},
],
},
.babelrc:
{
"presets": [],
"plugins": [
"@babel/plugin-transform-for-of",
"babel-plugin-loop-optimizer"
]
}
Unfortunately, the second plugin is unmaintained and neither of them transpiles to reversed index based loops. One could publish a plugin that solves all of this in one place.