Sunday 19 March 2017

Why fromClause in import statement expects string literal?

In our previous node.js application(based on ES5), we struggled for having relative paths in require statements.

for eg: var conf = require('../../global/config');

The issue with the relative paths was bubbled up in code obfuscation. We had to spent considerable time in handling this issue.

With that experience, in our current node.js application(based on ES6), though I'm not sure whether we will obfuscate the code or not I don't want to use relative paths. Hence, I've created a const ROOTDIR in every file and assigned the project's absolute path to it. Then realized that import expects only static literals in it's fromClause. This makes life difficult by forcing to type(copy/paste) the full path for every import or go back using relative paths OR use require statement.

enter image description here

While I'm trying to understand the benefits of using import style, I need some help in understanding the following 3 points.

  1. What are the advantages of using import apart from similar coding style of java/.net?

  2. Why import is accepting only string literals? It seems it's by design, if so, why?

  3. If I want to import a module based on some condition, I'll have to go for require because I can't use import in if/else or switch statements. Is there any solution/hack for it?

Appreciate all the help.



via Ganesh Adapa

No comments:

Post a Comment