【问题标题】:How to configure the package.json to install the local package first, and then try to install it from the registry or repository?如何配置package.json先安装本地包,然后再尝试从registry或repository安装?
【发布时间】:2019-09-05 21:42:25
【问题描述】:

有什么方法可以在package.json 中配置npm install 进程以尝试先从本地源安装新包,如果没有则尝试从其他地方安装?

是的,我知道这是syntax for versions,但我需要这样的东西:

"dependencies": {
    "ui-elements": "file:path/to/ui-elements || git+https://user@bitbucket.org/user/ui-elements.git"
}

之所以需要这样的行为,是因为我有一个包含一些 UI 元素的包,这些元素在不同的 React 应用程序中使用。这些 UI 元素正在积极开发中,这就是我需要它的本地副本的原因。最后,这些应用程序将部署在 AWS 云上,Docker 将尝试安装依赖项,如果本地不存在此包,我可以在一个配置文件中安装存储库中的依赖项。

我也知道npm link,但是在一堆目录中手动执行这个命令会很烦人,每次在新环境或本地机器上以特定方式运行npm link。这与便携性无关。 :)

谢谢。

【问题讨论】:

    标签: npm npm-install package.json


    【解决方案1】:

    我找到了一个非常适合我的需求的解决方案。我决定在安装完所有软件包后使用postinstall 挂钩来运行自定义脚本。然后我在package.json 中声明了一个自定义属性localDependencies

    这就是它在package.json 中的样子:

    "scripts": {
      "postinstall": "node install.js"
    },
    "localDependencies": {
      "ui-elements": "file:path/to/ui-elements"
    },
    "dependencies": {
      "ui-elements": "git+https://user@bitbucket.org/user/ui-elements.git"
    }
    

    至于文件install.js,我已经尝试了几种解决方案来完成它。首先,我尝试使用npm 包中的npm.commands.install(dependencies)。这个install() 方法工作正常,但问题出在这里,这个方法还使用package.json 中的localDependencies 中的依赖项覆盖了我的dependencies 列表。我试图找到一种将--no-save 参数传递给install 方法的方法,但它根本不起作用。总的来说,这个 API 没有在任何地方记录(或者我找不到它)。这就是为什么我决定使用child_process 中的exec 函数并直接运行npm 命令。

    install.js:

    const { exec } = require('child_process');
    
    const packageJson = require('./package.json');
    
    if (process.env.NODE_ENV !== 'production' && packageJson.localDependencies) {
      Object.values(packageJson.localDependencies).forEach((path) => {
        exec(`npm install ${path} --no-save`).stderr.pipe(process.stderr);
      });
    }
    

    嗯,我们到底有什么?

    对于生产,我们需要export NODE_ENV='production' 到全局变量,之后install.js 将被忽略,一切都会照常工作。

    对于本地开发,我们只需要localDependencies 的包的有效路径。在npm install 来自postinstall 的脚本之后,只需从本地存储重新安装新包。

    只有一个缺点,postinstall 将重写已经存在的下载包。

    【讨论】:

      猜你喜欢
      • 2013-02-25
      • 1970-01-01
      • 1970-01-01
      • 2014-08-18
      • 2020-01-24
      • 1970-01-01
      • 1970-01-01
      • 2021-12-25
      • 2015-07-01
      相关资源
      最近更新 更多