How to use a template literal in an import statement?

When this line is completed:

import stats from `./${process.env.STATS}` 

the error is reported below:

Analysis error: Unexpected token `

A module can be successfully loaded using the expression:

 const stats = require(`./${process.env.STATS}`); 

The import statement seems to require a regular line, since it works with the operator:

 import stats from './statsdir' 

where './statsdir' is the value of process.env.STATS .

Why does an error occur?

+5
source share
1 answer

Why does an error occur?

It seems you found the answer yourself:

The import statement seems to require a regular line

That's right. import needs a string literal. This import location cannot be dynamic.

Related: Import name of ES6 variable in node.js?

+7
source

All Articles