nodejs import is always undefined


nodejs import is always undefined



It's my first time using Babel transpiler to write ES6 to create a nodejs program.



I have the following directory structure:


/src/
/modules/
commands.js
index.js
/app/
.babelrc
package.json



in my /src/index.js I import my commands.js file, and export a const test:


/src/index.js


commands.js


const test


import { commands as commandsModule } from './modules/commands';
export const test = 'some test';



Then, inside my /src/modules/commands/js, I try to do the following:


/src/modules/commands/js


import { test }from '../index';
console.log(test);



Next, I use babel to transpile to es5 so I can run my program with node app/index.js using the following command:


node app/index.js


./node_modules/.bin/babel ./src --experimental --source-maps-inline -d ./app && node ./app/index



But this seems to always prints undefined!



What am I doing wrong, I really don't understand why my imported test variable is undefined.


test



This is my .babelrc:


.babelrc


{
"presets": ["env"]
}





You're sure, you don't create a circular dependency by importing index.js, which is importing command.js, which is importing index.js, which is ... ?
– Michael Hirschler
Jun 30 at 15:00


index.js


command.js


index.js





I see what you are saying. How would I avoid this problem? I import commands.js inside index.js because I want to run the code that is in the commands.js file, but I need the exported test variable from the index.js inside commands.js if that makes sense
– nbokmans
Jun 30 at 15:02


commands.js


index.js


commands.js


test


commands.js





Do not create circular dependencies. You have basically two options: 1) do not import the test variable from index.js in your commands.js, pass it as a parameter. I suppose you call some command from commands.js in your index.js -- you can do something like executeCommandXYZ(test). 2) extract the test variable into different module/file and import it from both index.js and commands.js. E. g. create constants.js, put test variable there a import it from both index.js and commands.js from this file.
– Lukáš Havrlant
Jun 30 at 15:49


executeCommandXYZ(test)









By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

How to input without newline? (Python)

C++ thread error: no type named ‘type’ MINGW

Analog for TagView in flutter