3

In ES5 it is like this UserInfoModel = require(process.cwd() + '/server/models/Users');

How do I write the same in ES6?This does not work import { UserModel } from '/server/models/User';

I do not want to do this. Is there a better way? [The below works btw] import { UserModel } from '../../../server/models/User';

Barmar
  • 741,623
  • 53
  • 500
  • 612
suprita shankar
  • 1,554
  • 2
  • 16
  • 47

3 Answers3

4

After discussing with fellow mentors on other channels. The answer is - it is not possible. One of the optimizations ES6 made over ES5 is that imports had to be strictly statically analyzable. So it cannot depend on any variables.

Options to avoid ugly code

  1. Use this awesome plugin https://github.com/tleunen/babel-plugin-module-alias (this is what I ended up doing)

  2. Rearrange the files

  3. If you must have dynamic variables then use require :)

Thanks!

suprita shankar
  • 1,554
  • 2
  • 16
  • 47
0

Yes is better way! Your script and this child repository ( also extends your global app) are very encapsulate: you cap move script ( and child) to other directory without CHANGE ALL ROUTES, create npm package( and push to npm) run into other environement(prod server). It's not best pratice to concat string in require mostly without path.join or path.resolve

Jules Goullee
  • 571
  • 4
  • 11
0

Actually, it is possible to read cwd() and use it in an ES6 import.

It can be done like so:

const UserModel = await import(`file:///${process.cwd().replace(/\\/g, '/')}/server/models/Users`)

This is achieved by using a combination of dynamic imports and template literals, see:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import#importing_modules_with_a_non-literal_specifier

and:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals