简体   繁体   English

节点找不到在 tsconfig 和 package.json 中定义的模块别名

[英]Node unable to find module alias defined in tsconfig and package.json

I'm trying to run a typescript project in production mode.我正在尝试在生产模式下运行 typescript 项目。 The code is here on Github代码在 Github 上

  • Running npm run start:dev is running the server up on http://localhost:3000/运行npm run start:devhttp://localhost:3000/上运行服务器
  • Running npm run build is generating the dist folder运行npm run build正在生成dist文件夹

The package.json has the definition of @server defined using module alias : package.json具有使用模块别名定义的@server定义:

"_moduleAliases": {
  "@server": "dist/Server"
}

The @server is defined under compilerOptions.paths.@server in tsconfig.json too! @server也在tsconfig.jsoncompilerOptions.paths.@server下定义!

The index.ts imports app from @server ; index.ts@server导入app

import app from '@server';

When I run npm start - it does nothing当我运行npm start - 它什么也不做

So I tried node dist/index.js --env=production and it throws the following error:所以我尝试了node dist/index.js --env=production并抛出以下错误:

Error: Cannot find module '@server'

Why is the node not detecting this module alias ?为什么节点没有检测到这个模块别名

As stated on the module-alias README , it changes the default behavior of require .正如module-alias README中所述,它改变了require的默认行为。 So, to use it, you have to add require('module-alias/register') to the beginning of your code before you import anything.因此,要使用它,您必须在导入任何内容之前将require('module-alias/register')添加到代码的开头。 I would suggest adding it to LoadEnv.ts .我建议将其添加到LoadEnv.ts

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM