无法让babel-loader为String.prototype.trimLeft()(又名trimStart)添加polyfill

时间:2019-02-16 18:54:09

标签: javascript node.js webpack babel-loader babel-polyfill

我将我的javascript与webpack / babel-loader捆绑在一起(使用@ babel / preset-env“ useBuiltIns:'usage'”设置),并且在编译过程中String.prototype.trimStart()polyfill无法得到添加。我尝试使用其替代名称“ trimLeft()”,但还是没有运气。这是错误还是我做错了什么?

我在Mac上使用Node,我将@ babel / polyfill作为项目依赖项,并将@ babel / core,@ babel / preset-env和babel-loader作为devDependencies(以及webpack)。我的babel配置位于我的webpack.config.js文件中。

我在调试模式下运行babel-loader,因此我可以看到将哪些polyfill添加到了哪些模块;据我所知,这只是trimLeft / trimStart问题。结果,在IE中运行我的应用会引发错误。

来自package.json:

"dependencies": {
    "@babel/polyfill": "^7.2.5"
},
"devDependencies": {
    "@babel/core": "^7.2.2",
    "@babel/preset-env": "^7.3.1",
    "babel-loader": "^8.0.5",
    "webpack": "^4.29.1",
    "webpack-cli": "^3.2.1"
}

从webpack.config.js(在module.exports.module.rules中):

use: {
    loader: 'babel-loader',
    options: {
        presets: [
            ['@babel/preset-env', {
                useBuiltIns: 'usage',
                debug: true,
                targets: {
                    browsers: ['IE >= 10']
                }
            }]
        ]
    }
}

在我使用String.prototype.trimLeft()的模块中(在默认的导出箭头功能内):

const messageInput = document.querySelector('#message-input');
const usernameInput = document.querySelector('#username-input');

messageInput.addEventListener('keydown', handleKeydown);
usernameInput.addEventListener('keydown', handleKeydown);

function handleKeydown(event) {
    if (event.key === 'enter') {
        const username = usernameInput.value.trim();
        const text = messageInput.value.trimLeft();

        // etc.
    }
}

在支持trimLeft()/ trimStart()的浏览器中,此代码可以正常工作。我还要补充一点,当我尝试更改babel设置以定位不支持trim()的浏览器时,trim()polyfill已在编译期间导入到此模块中。

0 个答案:

没有答案
相关问题