Nodejs需要来自外部文件夹模块

r1zk6ea1  于 2022-12-03  发布在  Node.js
关注(0)|答案(3)|浏览(128)

I'm developing microservice architecture on nodejs. I moved 'core' functionality to separate git repository, and each 'service' add that core as npm dependency.
In service I use core as

require('core/module1');

In that case nodejs takes 'core' from node_modules, it's ok for production but for development I want to take 'core' from the external folder not from node_modules.
My main idea - do changes in 'core' and immidiately get the result in 'service'.
I cannot use NODE_PATH for specify external 'core' folder, because I've used it now.
I found solution to use 'app-module-path' module for adding additional directories to the Node.js module search path.

if(isDevelopment()){
    require('app-module-path').addPath('path_to_core_folder');
}

It's working solution, but maybe you can suggest some more clear way?
My folders structure

- core
    module1

- service1
    -index.js
    -node_modules
      -core

Thanks.

bwntbbo3

bwntbbo31#

这两种方法都可以。如果您需要('modulename'),并且它存在于node_modules文件夹中,那么它将从那里加载。如果您希望它从另一个文件夹或主文件夹中加载,您需要执行require('./modulename”),它将在当前文件夹中查找它。或者您也可以执行require('./my_modules/modulename '),它将在子文件夹中工作。

8yparm6h

8yparm6h2#

我会看一下mockrequire模块,它允许您重定向模块加载的目录

o2g1uqev

o2g1uqev3#

npm链接是您问题的答案。您可以在'service1'的根目录(package.json所在的位置)中运行以下命令

npm link [../relative-path-to/library]

有关npm链接的更多详细信息,请参阅https://docs.npmjs.com/cli/v7/commands/npm-link

相关问题