Webpack generates arrow function in ES5

Viewed 2650

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)

2 Answers

The decision is simply adding target: ['web', 'es5'] to your webpack configuration.

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.

That's the problem I faced last week after upgrading the webpack to version 5.

By default, it's bundling it as ES6. In your webpack configuration, configuring output.environment should resolve the problem.

Edit: webpack only change it's internal usages with these configurations.

webpack.js.org/configuration/output/#outputenvironment

It does not compile the modules. For the module compilation, babel should be used.

Related