简体   繁体   中英

Reference error for _ (lodash) when declared as peerDependency

I have my custom lib which is published via npm. It declares peerDependency "lodash": "4.15.*"

As far as I understand, that means that whoever want to use my lib should provide lodash with specified version. So in my app in npm dependencies I have "lodash": "4.15.*" but when using component from my custom lib I receive following ReferenceError: _ is not defined . I have also added require('lodash'); to my app.js but it didn't help.

What else should I do in order to make this work?

Library is written in AngularJS 1.5 and TypeScript. I am trying to use it with plain AngularJS 1.5 application.

EDIT.

In my library I assume, that variable _ is global, so it isn't imported in any file that uses it.

Your assumption that _ is global is incorrect. If you are using the npm version of lodash, it is a commonjs module which will not globally export anything.

This means, that unless you are using some special plugin in browserify to export _ globally, or you are including lodash from a cdn using a script tag, _ will not be defined.

Assuming you are using typescript 2.0 and have installed the @types/lodash npm package, then the correct way to import lodash in every script that needs to use it is:

import * as _ from 'lodash';

This will transpile as:

var _ = require('lodash')

Which should be enough for node (or browserify when using it in web) to properly include and set _ to be usable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM