Webpack无法正确转换es6的问题

时间:2019-05-30 13:48:02

标签: javascript webpack

当我在目录中运行npm run build并将所有文件捆绑到bundle.js中时,我发现此错误:ERROR in ./bundle.js from UglifyJs \n Unexpected token name «key», expected punc «;» [./bundle.js:8141,13]

所以我去了bundle.js第8141行,发现了这一点:for (let key in val) {

问题就出在这里:let。 Uglify无法处理letconst

因此,我浏览了整个bundle.js文件,仅出现的真正时间就在那儿,几行下来,我特别知道该代码来自哪个包:npm install clone-deep

我使用的其他软件包都没有这个问题,它们在uglify运行之前都已从es6正确转换,并且我一直在自己的代码中使用let和const。这一个程序包仅引起我问题。

这是我的package.json

{
  "name": "jsx2",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "author": "",
  "license": "ISC",
  "dependencies": {
    "autobind-decorator": "^2.1.0",
    "axios": "^0.18.0",
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.4",
    "babel-plugin-transform-decorators-legacy": "^1.3.4",
    "babel-polyfill": "^6.26.0",
    "babel-preset-env": "^1.6.1",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "classnames": "^2.2.5",
    "clone-deep": "^4.0.1",
    "prop-types": "^15.6.0",
    "react": "^16.2.0",
    "react-dom": "^16.2.0",
    "react-toastify": "^4.5.2",
    "webpack": "^3.11.0"
  },
  "scripts": {
    "dev": "webpack -d --watch",
    "build": "webpack -p --config webpack.build.config.js"
  }
}

这是我的webpack.build.config.js

// https://www.codementor.io/tamizhvendan/beginner-guide-setup-reactjs-environment-npm-babel-6-webpack-du107r9zr

var webpack = require('webpack');
var path = require('path');

var BUILD_DIR = path.resolve(__dirname, 'out/');
var APP_DIR = path.resolve(__dirname, 'src/');

var config = {
    entry: ['babel-polyfill', APP_DIR + '/App.jsx'],
    output: {
        path: BUILD_DIR,
        filename: './bundle.js'
        //https://cloud.githubusercontent.com/assets/593571/20785959/290f7fbc-b7b4-11e6-9ad2-7dafd7803552.png
        //https://github.com/babel/babel-loader/issues/93
    },

    module : {
        loaders : [
            {
                test : /\.jsx?/,
                include : APP_DIR,
                loader : 'babel-loader',
                options: {
                    "presets" : ["env", "react"],
                    "plugins": ["transform-decorators-legacy"]
                }
            }
        ]
    },
    resolve: {
        extensions: ['.js', '.jsx'],
    }
};

module.exports = config;

-编辑

仅需确认,我确实进入了clone-deep index.js并将let更改为vars,并且一切正常,并且我没有出现任何错误。我真的不认为这是一种解决方案,因为...没有理由为什么这个软件包应该有此错误,而没有其他任何原因。但这绝对是问题的根源。

1 个答案:

答案 0 :(得分:1)

某些npm软件包没有es5版本。我们必须接受这一点或使用其他软件包。

如果要继续使用clone-deep,则必须将此软件包添加到include配置的babel-loader属性中:

...
{
    test : /\.jsx?/,
    include : [APP_DIR, path.resolve(__dirname, 'node_modules', 'clone-deep')],
    loader : 'babel-loader',
    options: {
        "presets" : ["env", "react"],
        "plugins": ["transform-decorators-legacy"]
    }
};
...

您可以在此issue

中阅读更多内容