evont-software.com

Email: info@evont-software.com

SPFX 2019 Unexpected token - Uglify

Category:SPFX
Date:
Author: Mathias Osterkamp

Problem

If you are using some third party libraries on SPFX 2019 there can be a problem with your typescript language set. Everything works fine in development, but on production build you get an error message like this one:

SyntaxError: Unexpected token: name (xxxxxx) from Uglify plugin

The problem ist, that third party library uses ES6 code and UglifyJS ist not able to compile ES6.

Solution

UglifyJS does not support this compile, so we can go for TerserPlugin. (Source) In latest SPFX 1.12.1, Microsoft also don't use UglifyJS anymore, it is @Microsoft/Rush-Stack-Compiler-x-x.

First add this package to your devDependencies in package.json:

"terser-webpack-plugin-legacy": "1.2.3"

Second is to change your build configuration in gulpfile.js.

1const TerserPlugin = require('terser-webpack-plugin-legacy');
2
3...
4
5build.configureWebpack.mergeConfig({
6 additionalConfiguration: (generatedConfiguration) => {
7
8 // Replace the UglifyJS plugin with Terser, so that this will work with ES6
9 generatedConfiguration.plugins.forEach((plugin, i) => {
10 if (plugin.options && plugin.options.mangle) {
11 generatedConfiguration.plugins[i] = new TerserPlugin({
12 test: /\.(js|vue)(\?.*)?$/i
13 })
14 }
15 })
16
17 return generatedConfiguration;
18 }
19});
20build.initialize(require('gulp'));


For us everything worked fine afterwards.