简体   繁体   中英

Provide lodash with mixins globally via webpack.ProvidePlugin

I have some lodash mixins that I want to provide with webpack.ProvidePlugin, eg:

import * as _ from 'lodash';
export {_};
_.mixin({
  capitalize: function (input: string) {
  bla...
  }
})

I'm using Typescript with Webpack.

In webpack.config.js I have:

lodashPlugin = new webpack.ProvidePlugin({
  _: 'common/lodash_mixins'
})

When I try to use _.capitalize(string) , I get

TypeError: _.capitalize is not a function

When I log '_' I see that capitalize is in fact a function on that Object.

What am I missing here?

You are exporting _ as a named export, that you would require with import { _ } from 'common/lodash_mixins'; , but ProvidePlugin expects you to export a single object. You should be using a default export instead.

export default _;

See default export .

TypeError: .capitalize is not a function When I log ' ' I see that capitalize is in fact a function on that Object.

log _.capitalize you will find it is undefined. If you only log _ you get the opportunity to see a mutated version (dev tools will allow lazy evaluation). => if this is correct then it leads me to believe that you have a ordering issue somewhere in your code.

The solution I found to work for me is:

import * as lodashExtended from 'lodash';
module.exports = lodashExtended;
lodashExtended.mixin({
  capitalize: function (input: string) {
  bla...
  }
})

I would prefer a solution that uses es6 syntax but haven't found one as yet.

Thanks to @basarat for help in debugging this.

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