项目当dev
命令运行时能正常运行,打包后却报错UglifyJs Unexpected token: punc (,)
,
> node scripts/build.js
Creating an optimized production build...
Failed to compile.
Failed to minify the bundle. Error: static/js/main.js from UglifyJs
Unexpected token: punc (,) [static/js/main.js:11913,13]
at /Users/busyRobot/workSpace/B/A/scripts/build.js:120:23
at /Users/busyRobot/workSpace/B/A/node_modules/webpack/lib/Compiler.js:269:13
at Compiler.emitRecords (/Users/busyRobot/workSpace/B/A/node_modules/webpack/lib/Compiler.js:375:38)
at /Users/busyRobot/workSpace/B/A/node_modules/webpack/lib/Compiler.js:262:10
at /Users/busyRobot/workSpace/B/A/node_modules/webpack/lib/Compiler.js:368:12
at next (/Users/busyRobot/workSpace/B/A/node_modules/tapable/lib/Tapable.js:218:11)
at Compiler.<anonymous> (/Users/busyRobot/workSpace/B/A/node_modules/webpack/lib/performance/SizeLimitsPlugin.js:99:4)
at next (/Users/busyRobot/workSpace/B/A/node_modules/tapable/lib/Tapable.js:220:14)
at /Users/busyRobot/workSpace/B/A/node_modules/sw-precache-webpack-plugin/lib/index.js:98:18
Read more here: http://bit.ly/2tRViJ9
但是能顺利打出来,看一下原webpack.prod.conf.js
:
plugins: [
...
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
},
sourceMap: config.build.productionSourceMap,
parallel: true
}),
]
就是简单的使用了一个webpack内置压缩js的插件,报错信息为:“js文件app.xxx.js中14922行有,逗号问题
”。检查了这个文件确实是返回了一个含有逗号对象,但是看起来完全没有任何问题呀?
方法一: 注释压缩代码,这块代码
// Makes some environment variables available to the JS code, for example:
// if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
// It is absolutely essential that NODE_ENV was set to production here.
// Otherwise React will be compiled in the very slow development mode.
new webpack.DefinePlugin(env.stringified),
// Minify the code.
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
// Disabled because of an issue with Uglify breaking seemingly valid code:
// https://github.com/facebookincubator/create-react-app/issues/2376
// Pending further investigation:
// https://github.com/mishoo/UglifyJS2/issues/2011
comparisons: false,
},
mangle: {
safari10: true,
},
output: {
comments: false,
// Turned on because emoji and regex is not minified properly using default
// https://github.com/facebookincubator/create-react-app/issues/2488
ascii_only: true,
},
sourceMap: shouldUseSourceMap,
}),
因为是压缩相关的代码,我们可以推测,如果对代码不进行压缩,那么其实有不会影响打包;
于是,抱着忐忑的尝试性心态,注释了这段配置;
果然,打包成功,并且正常,当然打包后的包巨大(有1.4M);
继续寻找..........
网上说是babel转换的问题,有调整babelrc
配置,实测没用。难道是webpack版本太低了的原因?
方法二:
经过一番思考后对比其他项目打算换一个压缩插件uglifyjs-webpack-plugin
,而不使用webpack内置插件,结果就解决了!
"uglifyjs-webpack-plugin": "^1.1.1"
webpack.prod.conf.js:
const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
plugins: [
...
new UglifyJsPlugin({
uglifyOptions: {
compress: {
warnings: false,
drop_debugger: true,
drop_console: true
}
},
sourceMap: config.build.productionSourceMap,
parallel: true
}),
...
]
结论:
引用sorrycc大神的一句话: 业界有个潜在的约定,npm 包发布前需要先用 babel 转出一份 es5 的代码。