String literal expected. when importing in typescript
You're trying to Dynamically import a module. Unfortunately, this is impossible using the ES6 import/export mechanism which is not analyzed in runtime (nothing to do with TypeScript so far).
In order import your module dynamically and avoid the tsc error I'd suggest using the common.js require mechanism (which does allow dynamic import):
const your_module = require(`${process.cwd()}/server`);
Note that whenever your variable is not certained to be a string (unlike your template string example) I'd reccommend using the mentioned solution alongside Typescript type assertion. this should look like this:
const your_module = require(<string>process.env.myNodeModulePackageName);
Edit:
In ES2020 the import statement evolved to return a promise, supporting dynamic imports. So if you are willing to use the native import mechanism (rather then common.js) you should do as follows:
const your_module = await import (`${process.cwd()}/server`)
(note that your tsconfig.json
file should be configured to:
"target": "es2017"
"module": "esnext"
(will allow you to use top level await
as well)
In my case I did this which is illegal apparently:
import { two }, one from "./file";
While it should be this:
import one, { two } from "./file";
This is not legal syntax in ES6 modules or in TypeScript. Part of the ES6 module spec is that dependencies are always statically resolvable.