javascripttypescriptwebpackecma

Webpack generates arrow function in ES5


I want to use TypeScript modules and bundle them via Webpack. Here are my config files:

webpack.config.js:

const path = require('path');

module.exports = () => {
    return {
        entry: './index.ts',
        output: {
            filename: 'bundle.js',
            path: path.resolve(__dirname, 'dist'),
        },
        module: {
            rules: [{
                test: /\.tsx?$/,
                use: 'ts-loader',
                exclude: /node_modules/,
            }],
        },
    };
};

tsconfig.json:

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es3"
  },
  "include": ["./**/*"],
  "exclude": ["node_modules/**/*", "webpack.config.js"]
}

Maybe I got something wrong from the documentation. The aim was to generate code in ES5 (or even earlier). But here is my bundled file:

(()=>{var n=function(n,o){console.warn(o)};n(0,0),n(0,1)})();

It has an arrow function, which was added in ES6. I am confused. How can I get rid of that?


EDIT:

Here's the code I try to compile:

const func = (foo, bar: number) => {
    console.warn(bar);
};

func(0, 0);
func(2, 1);

EDIT 2:

Also, I run the compilation process in production mode. (idk, maybe that's useful information)


Solution

  • Simply add target: ['web', 'es5'] to your webpack configuration. (In addition to changing the .tsconfig.) For the full list of accepted values, see the docs.

    You could also set target: 'es5', but in this case, there are some problems. At least in my case without specifying 'web' TerserWebpackPlugin refused to compress files in the production mode.