W
W
Wayne12121212021-05-06 10:42:08
Node.js
Wayne1212121, 2021-05-06 10:42:08

Node+ts module-alias doesn't work with import but works with require?

Hello!
In node+ts, I need to use import instead of require to work well with interfaces.
Require does not throw errors on invalid values, unlike import.
The problem is that when importing + module-alias, an error is thrown, saying that the module was not found

. For example:

import { A } from '@/types/A.interface' // не работает
const { A } = require('A.interface') // видит модуль, но работает с ним некорректно


//Конфиг module-alias

const moduleAlias = require('module-alias');

const prefix = process.env.NODE_ENV ? '/dist/' : '/src/';

moduleAlias.addAliases({
    '@': `${__dirname}${ prefix }`,
});

moduleAlias();

export {};


Tell me what to do, I've already tried everything.
Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2021-05-06
@bingo347

Typescript only resolves paths from aliases, but does not translate them into real ones, leaving it up to the collectors.
Option 1: build project with webpack or rollup (or whatever you like)
https://www.npmjs.com/package/@rollup/plugin-alias
https://webpack.js.org/configuration/resolve/# reso...
Option 2: upload require/import to node (depending on what TS outputs) to understand your aliases
https://nodejs.org/dist/latest-v14.x/docs/api/ esm....
There is no hook for commonjs, you need to patch this: https://nodejs.org/dist/latest-v14.x/docs/api/modu...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question