Angular Universal集成angular2-multiselect-dropdown报错:SyntaxError: Unexpected token import
SyntaxError: Unexpected token import with angular2-multiselect-dropdown in Angular Universal Hey there, I’ve dealt with this exact issue a few times when integrating third-party components into Angular Universal apps. That Unexpected token import error almost always means the angular2-multiselect-dropdown library is serving untranspiled ES6 code, which Node.js (running your server) can’t natively handle. Here’s how to fix it step by step:
1. Upgrade the library first
Older versions of this dropdown component weren’t optimized for server-side rendering. Start by upgrading to the latest stable version to rule out compatibility issues:
npm install angular2-multiselect-dropdown@latest --save
2. Configure Webpack to transpile the library
By default, Angular Universal’s Webpack config skips transpiling most node_modules packages. We need to explicitly tell it to process angular2-multiselect-dropdown:
- First, install the required Babel dependencies:
npm install @babel/core @babel/preset-env babel-loader --save-dev
- Open your
webpack.server.config.jsfile, and add this rule to themodule.rulesarray:
{ test: /\.js$/, include: [require.resolve('angular2-multiselect-dropdown')], loader: 'babel-loader', options: { presets: ['@babel/preset-env'] } }
This tells Webpack to use Babel to convert the library’s ES6 import statements into Node-compatible CommonJS require() calls.
3. Update your server.ts file
Sometimes, Universal needs global polyfills to handle browser-specific APIs that the dropdown might rely on. Add these lines at the top of your server.ts:
(global as any).WebSocket = require('ws'); (global as any).XMLHttpRequest = require('xhr2');
This ensures the server environment mimics browser APIs the component expects.
4. Adjust your Angular CLI config
Open angular.json and find the server build configuration. Add the dropdown library to externalDependencies to ensure it’s included in the server bundle properly:
"server": { "builder": "@angular-devkit/build-angular:server", "options": { "outputPath": "dist/server", "main": "server.ts", "tsConfig": "tsconfig.server.json", "externalDependencies": [ "angular2-multiselect-dropdown" ] }, // ... other existing configs }
5. Clean and rebuild from scratch
Cache issues can sometimes persist, so do a full reset to ensure no old code lingers:
rm -rf node_modules package-lock.json npm install npm run build:ssr npm run serve:ssr
If none of these work, double-check that your tsconfig.server.json has "module": "commonjs" set (which it should by default for Universal), and that you’re not importing the component in a way that bypasses the server bundle.
内容的提问来源于stack exchange,提问作者Ankita Gupta

