Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use a template literal in an import statement? [duplicate]

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?

like image 629
gnerkus Avatar asked Apr 30 '16 12:04

gnerkus


People also ask

What is the use of template literals?

Template literals provide an easy way to interpolate variables and expressions into strings. The method is called string interpolation.

Can you concatenate template literals?

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.

Which of the following is an example of template literal?

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 } !


1 Answers

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?

like image 126
Felix Kling Avatar answered Sep 28 '22 19:09

Felix Kling