When this line is executed:
import stats from `./${process.env.STATS}`
the error below is reported:
Parsing error: Unexpected token `
The module can be loaded successfully with the expression:
const stats = require(`./${process.env.STATS}`);
The import
statement seems to require a regular string as it works with the statement:
import stats from './statsdir'
where './statsdir'
is the value of process.env.STATS
.
Why does the error occur?
Template literals provide an easy way to interpolate variables and expressions into strings. The method is called string interpolation.
When you use regular template literals, your input is passed to a default function that concatenates it into a single string. An interesting thing is that you can change it by preceding the template literal with your function name that acts as a tag.
A template literal is a new kind of string literal that can span multiple lines and interpolate expressions (include their results). For example: const firstName = 'Jane' ; console . log ( `Hello ${ firstName } !
Why does the error occur?
It seems you found the answer yourself:
The
import
statement seems to require a regular string
Exactly. import
needs a string literal. It import location cannot be dynamic.
Related: ES6 variable import name in node.js?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With