简体   繁体   English

Webpack 在 ES5 中生成箭头函数

[英]Webpack generates arrow function in ES5

I want to use TypeScript modules and bundle them via Webpack.我想使用 TypeScript 模块并通过 Webpack 捆绑它们。 Here are my config files:这是我的配置文件:

webpack.config.js: 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: 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).目的是在 ES5(甚至更早版本)中生成代码。 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.它有一个箭头函数,这是在 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:编辑2:

Also, I run the compilation process in production mode.另外,我在生产模式下运行编译过程。 (idk, maybe that's useful information) (idk,也许这是有用的信息)

The decision is simply adding target: ['web', 'es5'] to your webpack configuration.决定只是将target: ['web', 'es5']到您的 webpack 配置中。

You could also set target: 'es5' , but in this case, there are some problems.您也可以设置target: 'es5' ,但在这种情况下,存在一些问题。 At least in my case without specifying 'web' TerserWebpackPlugin refused to compress files in the production mode.至少在我没有指定“web”的情况下,TerserWebpackPlugin 拒绝在生产模式下压缩文件。

That's the problem I faced last week after upgrading the webpack to version 5.这就是我上周将 webpack 升级到版本 5 后面临的问题。

By default, it's bundling it as ES6.默认情况下,它将它捆绑为 ES6。 In your webpack configuration, configuring output.environment should resolve the problem.在您的 webpack 配置中,配置output.environment应该可以解决问题。

Edit: webpack only change it's internal usages with these configurations.编辑:webpack 仅使用这些配置更改其内部用法。

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

It does not compile the modules.它不编译模块。 For the module compilation, babel should be used.对于模块编译,应该使用 babel。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM