如何在JS中防止babel变换运算符'typeof' [英] How to prevent babel transform operator 'typeof' in JS

查看:294
本文介绍了如何在JS中防止babel变换运算符'typeof'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用ES6语法开发了一个JS SDK. SDK的文件大小约为8Kb.用babel编译后,SDK的大小约为20Kb.我发现babel使用助手" babel-runtime/helpers/typeof "转换了运算符typeof,这增加了我的SDK的大小.如果我在SDK中未使用typeof,则SDK的文件大小约为7Kb.

I develope a JS SDK with ES6 grammar. The file size of the SDK is about 8Kb. After compile it with babel, size of SDK is about 20Kb. I find that babel transforms operator typeof with a helper "babel-runtime/helpers/typeof", which increase my SDK's size. If I don't use typeof in my SDK, the file size of my SDK is about 7Kb.

_validateCallback(fnName, arg) {
    if (typeof arg !== 'function') {
        throw new TypeError(`[${fnName}]'s arguments[0] must be a function, but get a ${typeof arg}`);
    }
}

我的 .babelrc 的详细信息:

{
    "presets": [
        [
            "env",
            {
                "targets": {
                    "browsers": [
                        "last 2 versions",
                        "ie >= 9"
                    ]
                }
            }
        ],
        "stage-2"
    ],
    "plugins": [
        "transform-runtime"
    ]
}

package.json

{
    "babel-cli": "^6.26.0",
    "babel-core": "^6.26.3",
    "babel-loader": "^7.1.5",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-env": "^1.7.0",
    "babel-preset-stage-2": "^6.24.1",
    "webpack": "^4.37.0",
    "webpack-cli": "^3.3.6"
 }

我的 webpack.config.js

{
    mode: 'production',
    entry: './main.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'botapp-sdk.' + PACKAGE.version + '.js',
        library: 'BotApp', 
        libraryTarget: 'var', 
    },
    plugins: [

        new webpack.HashedModuleIdsPlugin(),
        new webpack.optimize.ModuleConcatenationPlugin(),
        new webpack.BannerPlugin(PACKAGE.name + ' - ' + PACKAGE.version),
    ],
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: 'babel-loader'
            }
        ]
    }
}

我需要防止babel转换'typeof',以便减小SDK的文件大小.

I need to prevent babel to transform 'typeof', so that I can reduce file size of my SDK.

有什么方法可以防止babel变换运算符typeof吗?

Is there any way to prevent babel transform operator typeof ?

推荐答案

我已经找到解决问题的方法:

I have been find a way to solve the question:

@@ -8,7 +8,10 @@
                         "last 2 versions",
                         "ie >= 9"
                     ]
-                }
+                },
+                "exclude": [
+                    "transform-es2015-typeof-symbol"
+                ]
             }
         ],
         "stage-2"

exclude的详细信息,请参见: https://babeljs.io/docs/en/babel-preset-env#exclude

The detail of exclude see: https://babeljs.io/docs/en/babel-preset-env#exclude

这篇关于如何在JS中防止babel变换运算符'typeof'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆