How to import something globally (only once) in a React Project

Viewed 310

In my React project, I heavily depend on lodash. Now in each file I have an import statement like this

import each from 'lodash/each';
import compact from 'lodash/compact';

Is there any way in React that I don't need to import these in every file ? Can I import them once in App.jsx (The root component) and they would be available for all React Components that are it's children ?

Or maybe make lodash object globally available throughout the project ?

1 Answers

This is not really recommended, but you could do this in your main file:

 import _ from 'lodash';
 window._ = _;

to make it available via global window object.

However, it would be better to configure your bundler or compiler setup to expose this as global variable.

Related