20

What is the best way to import some modules in all of the files of the project, so I don't have to write stuff like:

import React from 'react';
import Reflux from 'reflux';
import reactMixin from 'react-mixin';

in almost every single file?

Victor Marchuk
  • 13,045
  • 12
  • 43
  • 67

2 Answers2

14

The other answer covers this, but not with valid ES6, so I'm adding my own. Make a central file to import your react components, in some central react.js file

export {default as React} from 'react';
export {default as Reflux} from 'reflux';
export {default as reactMixin} from 'react-mixin';

Then in the files where you need to use these three, you could do

import {React, Reflux, reactMixin} from './react';

to import all three into your component file.

loganfsmyth
  • 156,129
  • 30
  • 331
  • 251
  • Good solution. You have also the ability to import any of all (for example, you could, if you needed only that, `import {React, Reflux} from './react';`) – Ruby Racer Feb 10 '18 at 21:15
  • Will filesize increase if I import all this stuff everywhere that "doesn't need it"? Like just take everything that any file could use and import it to be safe. (`import axios from 'axios'` in a component that doesn't use requests) – Vael Victus Aug 16 '19 at 21:49
  • There is a reason why React starting from v17 doesn’t require react.js import in every file, but it requires hook imports separately. Yes, it affects bundle size. This is why imports from index that contains bunch of exports is not a good idea… (if it didn’t affect bundle size, react wouldn’t require other stuff to be imported as well). – C.L. Oct 22 '22 at 05:31
8

Create a "base" that declares common imports, then you can import that one file.

eXecute
  • 176
  • 7
  • 2
    @user860478: That file would be something like `import React from 'react'; import Reflux from 'reflux'; export {React, Reflux}` and you would use it everywhere as `import {React, Reflux} from 'path/to/base'`. – Felix Kling May 31 '15 at 20:48