11

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)

Green
  • 609
  • 1
  • 4
  • 25
Ivan Adanenko
  • 325
  • 1
  • 9

2 Answers2

7

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.

Yoskutik
  • 1,609
  • 2
  • 6
  • 25
1

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.

Tugay İlik
  • 2,658
  • 1
  • 10
  • 16
  • Thank you for the answer. The version of webpack is `5.3.2`. But adding `environment: 5` causes an error `Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.` – Ivan Adanenko Oct 31 '20 at 13:20
  • It's weird, I just tried, and yes, saw the same error. – Tugay İlik Oct 31 '20 at 13:36
  • Ok, I just realized the environment option only manages internal usage of webpack. It does not compile your modules. For doing it, you should use babel transformer plugin. This is how you configure only webpack itself., https://webpack.js.org/configuration/output/#outputenvironment – Tugay İlik Oct 31 '20 at 13:55
  • I have `ts-loader`. It can handle modules. Also just getting rid of arrow function is seems to be a crutch. Because not only arrow function were added in ES6 – Ivan Adanenko Oct 31 '20 at 19:15