Introduction:
While packaging your SharePoint Framework (SPFx) solution using the production command:
You may encounter a frustrating error message like:
This usually indicates that UglifyJS, the default minifier in SPFx, stumbled upon ES6+ syntax (e.g., class, let, const) that it does not understand.
In this post, I will guide you through a clean and effective workaround using terser-webpack-plugin, a modern minifier that fully supports ES6+.
Why This Error Occurs:
- Root Cause: UglifyJS does not support modern JavaScript (ES6+).
- Impact: Webpack fails during the minification process, stopping the bundle process for production.
- Trigger: Usage of ES6+ syntax like class, const, etc., in your SPFx web part code.
Solution: Swap UglifyJS with Terser:
To resolve this, we will:
- Add Terser and Webpack merge dependencies.
- Update gulpfile.js to override the default SPFx Webpack configuration.
- Clean and rebuild your project.
Step-by-Step Fix:
Step 1: Install Compatible Dependencies:
Update your package.json to include:
Then run the following commands in your terminal:
Optional (if Babel is needed for ES6+ transpilation):
Step 2: Update gulpfile.js:
Modify your gulpfile.js as shown below:
This code replaces UglifyJS with Terser during the bundle phase.
Step 3: Clean & Rebuild the Project:
Run the following commands in sequence:
Your project should now build successfully, free of any “unexpected token” errors from UglifyJS.
Optional: Babel Setup (Only If Needed):
If your project uses newer JavaScript features not supported in your target environments, consider setting up Babel. However, for the UglifyJS error alone, swapping in Terser is typically enough.
Conclusion:
- If you are getting the "UglifyJs Unexpected Token" error while bundling your SPFx project, it is because the default minifier does not support modern JavaScript. By switching to it terser-webpack-plugin, you can fix the issue and bundle your project without errors. Just follow the steps to update your packages and gulpfile, and you will be good to go!
- If you run into any issues while implementing this solution, feel free to drop a comment. I will be happy to help.
No comments:
Post a Comment