如何将ES6转换为ES5的第三方库?

我有一个webpack安装程序几乎可以正常工作,但是当我导入一些在ES6中编写的第三方库时,UglifyJS会发出一个错误。 这里是node-postgres一个例子:

 module.exports = { prepareValue: function prepareValueWrapper (value) { // this ensures that extra arguments do not get passed into prepareValue // by accident, eg: from calling values.map(utils.prepareValue) return prepareValue(value) }, normalizeQueryConfig, postgresMd5PasswordHash, md5 } 

这里是它应该在ES5中看起来如何:

 module.exports = { prepareValue: function prepareValueWrapper (value) { // this ensures that extra arguments do not get passed into prepareValue // by accident, eg: from calling values.map(utils.prepareValue) return prepareValue(value) }, normalizeQueryConfig: normalizeQueryConfig, postgresMd5PasswordHash: postgresMd5PasswordHash, md5: md5 } 

当原始代码被UglifyJS处理时,我看到这个错误:

来自UglifyJs的proxy.js中的错误

意外的令牌:punc(,)[proxy.js:382,22]

哪个指向上面的代码。

当我正在编译一个TypeScript项目时,我怀疑我需要通过Webpackstream中的一些转译器来处理第三方libs代码,以在捆绑之前将它们转换为ES5。

这是我的webpack.config.js

 const path = require('path'); const root = (dir) => { return path.resolve(__dirname, dir); }; module.exports = { entry: './src/main.ts', module: { rules: [ { test: /\.ts$/, use: 'ts-loader', exclude: /node_modules/ } ] }, resolve: { extensions: [".ts", ".js"], modules: [root('node_modules'), root('src')] }, output: { filename: 'proxy.js', path: path.resolve(__dirname, 'build') }, target: 'node' }; 

我该怎么做?

您可以使用uglify-es缩小您的ES6代码,或使用Babel和ES2015预设将代码转换为ES5。