Import .exports and es6 modules

React with babel. I have this confusion with import and module.exports. I assume that babel when converting ES6 code to ES5 will convert the import and export to the required and module.exports respectively.

If I export a function from one module and import a function into another module, the code will execute perfectly. But if I export a function using modules.exports and import using "import", an error is thrown at runtime, saying that it is not a function.

I have prepared an example.

// Tiger.js function Tiger() { function roar(terrian){ console.log('Hey i am in ' + terrian + ' and i am roaing'); }; return roar; } module.exports = Tiger; // animal.js import { Tiger } from './animals'; var animal = Tiger(); animal("jungle"); 

I used babel with preinstalled es2015 to recompile it. This gives me the following error:

Uncaught TypeError: (0, _animals.Tiger) is not a function

But if I remove module.exports = Tiger; And replace it with export { Tiger }; It works great.

What am I missing here?

EDIT: I use browserify as a bundler module.

+21
source share
3 answers

export { Tiger } will be equivalent to module.exports.Tiger = Tiger .

Conversely, module.exports = Tiger will be equivalent to export default Tiger .

So when you use module.exports = Tiger and then try to import { Tiger } from './animals' , you are actually querying Tiger.Tiger .

+26
source

If you want to import:

 module.exports = Tiger 

You can use the following construction:

 import * as Tiger from './animals' 

Then it will work.

Another option is to change the export as described by @Matt Molnar, but this is only possible if you are the author of the imported code.

+16
source

For me, I am trying to apply this to webpack.config.ts. Above does not work import * as X from "./X"; I get one more error.

Module.exports with es6 import for webpack.config.ts in typewritten text

enter image description here

 const getConfig = ( appDir: string, distDir: string, env: any, args: any ): webpack.Configuration => { const config: webpack.Configuration = { return config; }; }; module.exports = getConfig; 
0
source

Source: https://habr.com/ru/post/1238200/


All Articles