How to use import instead of ioc.use when use Env library?


#1

I want to use es6 import when using adonis libraries.

// this
const Route = use('Route')
// can be subsituted with
import Route from '@adonisjs/framework/src/Route/Manager'

// but this
const Env = use('Env')
// can not be subsituted with
import Env from '@adonisjs/framework/src/Env'

What did I do wrong?


#2

You cannot !

Please, read :


#3

In short

The use method resolves the dependency from IoC container

The import keyword and require resolves it from file system.

Though the dependency inside IoC Container will be file-system, but the IoC container, but they both are not same.

Understanding IoC container will take some of your time, so If interested, please read the docs http://dev.adonisjs.com/docs/4.0/ioc-container


#4

Hi @virk and @romain.lanz, sorry to bother you.
I know IoC Container is very powerful but it breaks the nature programming style of NodeJs, especially we lost IDE type hint cause we using use() function instead require() function.

I’m trying my best to find a way to keep my development joy during working with AdonisJs, so there is my solution and hope you could give me some advices :wink:

How to Use require() instead use()

  1. Create a jsconfig.json to make vscode could give us path autocompletion and type hint, just like to require other libraries.

    {
    "compilerOptions": {
      "baseUrl": ".",
      "paths": {
        "App/*": ["./app/*"]
       }
     }
    }
    
  2. Install module-alias package to make require() resolver happy :slight_smile: npm i --save module-alias

  3. Config module-alias in package.json.

    "_moduleAliases": {
      "App" : "./app"
    }
    
  4. Enable module-alias: Add require('module-alias/register') to the top of /server.js

  5. It works! Just try like this:

    const User = require('App/Models/User')
    const cat = await User.query().first()
    console.log(cat.toJSON())
    
  6. If you don’t want to change all of your use() to require(), just add const use = require to your /server.js. It works but I not sure if it is the right way to do.

Thanks for your patient

If you think it’s useful, please consider to use custom require resolver to rewrite IoC Container based on native require() function. I think it will make AdonisJs more elegant and also make us happier. :sunny: