Angular5+NGX_Restangular+Webpack-dev-server运行报错:_.isArray不是函数
_.isArray is not a function Error After ng eject in Angular 5 Hey there, let's work through this error together— I've run into similar issues with ejected Angular configs before, so let's break down what's going on and how to fix it.
The Scenario Recap
You're working with:
- Angular 5
- Dependencies:
ngx-restangular": "2.2.3","webpack": "4.5.0","webpack-dev-server": "3.1.3" ng serveruns perfectly, but after executingng eject, starting the app withnpm start(configured to runwebpack-dev-server --port=4200) throws a_.isArray is not a functionerror in Chrome's console.
Why This Happens
The core issue here is that ngx-restangular depends on Lodash for utility functions like isArray. When you use ng serve, Angular's default build setup automatically handles Lodash references behind the scenes. But when you eject to a custom webpack config, that automatic handling goes away—your webpack setup isn't making Lodash available globally, so ngx-restangular can't find the method it needs.
Step-by-Step Fixes
1. First, Confirm Lodash is Installed
Sometimes ejecting can mess up dependency references, so make sure Lodash is properly added to your project:
npm install lodash --save
2. Inject Lodash Globally with Webpack's ProvidePlugin
This tells webpack to automatically make Lodash available as the global _ variable, so every module (including ngx-restangular) can access it without explicit imports:
- Open your ejected
webpack.config.jsfile - At the top of the file, ensure you're importing webpack:
const webpack = require('webpack'); - Find the
pluginsarray in the config, and add this plugin to it:new webpack.ProvidePlugin({ _: 'lodash' })
3. Fallback: Import Lodash Directly in Polyfills
If the ProvidePlugin approach doesn't work, force Lodash to load early by adding this to your src/polyfills.ts file:
import * as _ from 'lodash'; // If you want to optimize with tree-shaking, you can import only needed methods: // import 'lodash/isArray'; // import 'lodash/...' // Add other Lodash methods ngx-restangular uses if needed
4. Double-Check Your Restangular Configuration
A misconfigured ngx-restangular setup can also trigger this error, so verify your AppModule setup is correct:
import { NgModule } from '@angular/core'; import { RestangularModule } from 'ngx-restangular'; // Your Restangular config factory (adjust to match your API setup) export function RestangularConfigFactory(RestangularProvider: any) { RestangularProvider.setBaseUrl('https://your-api-endpoint.com'); } @NgModule({ imports: [ RestangularModule.forRoot([RestangularConfigFactory]) ] }) export class AppModule { }
Test the Fix
After making these changes, run npm start again and check Chrome's console—this should resolve the _.isArray is not a function error and let your app load normally.
内容的提问来源于stack exchange,提问作者DeanB_Develop

