2

In my project structure, I have some top level directories such as

components/
constants/
util/
test/, etc

I do the following when I have to import a module from util in components/App

import { formatDate } from '../../util/dateUtil'

This becomes cumbersome when modules are deeply nested. Is there a better way to do this? Something like:

import { formatDate } from '%BASE%/util/dateUtil'

Edit: I have used webpack as my module loader.

sanchit
  • 2,328
  • 2
  • 18
  • 22
  • https://stackoverflow.com/questions/10265798/determine-project-root-from-a-running-node-js-application – Stan Oct 24 '16 at 09:47
  • Would something like this not work? `const base = '/path/to/files/'; import { util } from base + '/util';` – evolutionxbox Oct 24 '16 at 09:52
  • 3
    This isn't so much a syntax question, the resolution of modules is up to the loader you are using. Are you using NodeJS, Webpack, Browserify, or similar? Each of those have their own solution to this problem – CodingIntrigue Oct 24 '16 at 09:52
  • @evolutionxbox Unfortunately not. Syntax must be a string literal & statically analyzable – CodingIntrigue Oct 24 '16 at 09:53
  • @CodingIntrigue - why doesn't string concatenation work? – evolutionxbox Oct 24 '16 at 09:54
  • I'm using Webpack. I'll try the solution mentioned by @evolutionxbox – sanchit Oct 24 '16 at 09:54
  • 1
    @CodingIntrigue is right. My solution won't work. Maybe [this question](http://stackoverflow.com/questions/30340005/importing-modules-using-es6-syntax-and-dynamic-path) will help – evolutionxbox Oct 24 '16 at 09:55
  • @evolutionxbox [The spec](http://www.ecma-international.org/ecma-262/6.0/#sec-imports) says a module specifier *must* be a string literal. I would imagine so that the JS engine can predetermine dependencies before runtime – CodingIntrigue Oct 24 '16 at 09:56
  • @CodingIntrigue So it isn't possible then? Any way around it – sanchit Oct 24 '16 at 10:02
  • 2
    @sanchit If you are using Webpack: http://stackoverflow.com/questions/27502608/resolving-require-paths-with-webpack - either one of the top two answers – CodingIntrigue Oct 24 '16 at 10:03

0 Answers0