简体   繁体   English

使用npm安装时重命名包

[英]rename package when installing with npm

Working on an existing nodejs project, one of packages is not in my control, for example, public-package . 在现有的nodejs项目上工作,其中一个包不在我的控制之下,例如public-package When I try to publish a new version, I have to deploy with a new package name, such as my-package . 当我尝试发布新版本时,我必须使用新的包名称进行部署,例如my-package

For example, 例如,

{
  ...
    "dependencies": {
    "public-package": "1.0.123",
    ...
  }
  ...
}

In source code, there are lot of lines, such as require('public-package') 在源代码中,有很多行,例如require('public-package')

So how can I use my package, rename it directly when npm install without changing the code from require('public-package') to require('my-package') ? 那么我如何使用我的包,在npm install时直接重命名,而不require('public-package')的代码更改为require('my-package')

Such as

{
  ...
    "dependencies": {
    "public-package": "my-package@1.0.10",   # <= how to make this work?
    ...
  }
  ...
}

Can I do anything to make it work as above code? 我可以做任何事情让它像上面的代码一样工作吗?

You could try to change the main entry in the package.json of public-package (located in node_modules/public-package/package.json ) 您可以尝试更改public-package的package.json中的main条目(位于node_modules/public-package/package.json

See Folders as Modules in the node docs for details of how the main entry works. 有关main条目如何工作的详细信息,请参阅节点文档中的“ 文件夹为模块” The technique is used to point require to a subfolder of a module, but in this case you could adapt it to fit your needs. 该技术被用来指向require一个模块的子文件夹,但在这种情况下,你能适应它来满足您的需求。

{ 
  "name" : "public-package",
  "main" : "./public-package.js"
}

Change it to 将其更改为

{ 
  "name" : "public-package",
  "main" : "/path/to/my-package.js"
}

Now each time you do a require('public-package') , it loads my-package without the need of changing the source code. 现在每次执行require('public-package') ,它都会加载my-package而无需更改源代码。

To change the entry automatically in node_modules/public-package/package.json , you could add a custom script to npm that does a search-and-replace in that file. 要在node_modules/public-package/package.json自动更改条目,您可以向npm添加一个自定义脚本 ,该脚本在该文件中执行搜索和替换。

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

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