1

我有一个具有对等依赖关系的npm 包。我写了一个简短的安装后脚本,它会提示用户安装对等依赖项,但它不起作用。

正如您将从下面的输出中看到的那样,看起来 npm正在下载包,但它没有出现在项目的任何地方,package.json不在node_modules.

我正在运行 ubuntu 16.04 顺便说一句

这是我安装 npm 包时发生的情况:

➜  codeMentorTutorial npm i ../react-native-gradle-config

> react-native-gradle-config@2.0.0 postinstall /home/adam/apps/codeMentorTutorial/node_modules/react-native-gradle-config
> node lib/addScriptsToPackageJson && node lib/installPeerDependencies
...
This package has a peer dependency "replace", which is not installed in your project.
would u like to install it now? [Y/n]
installReplace
installReplace err, res null codeMentorTutorial@0.0.1 /home/adam/apps/codeMentorTutorial
└─┬ replace@0.3.0 
  ├── colors@0.5.1 
  ├─┬ minimatch@0.2.14 
  │ ├── lru-cache@2.7.3 
  │ └── sigmund@1.0.1 
  └─┬ nomnom@1.6.2 
    ├── colors@0.5.1 
    └── underscore@1.4.4 


closing rl!
closing rl!
codeMentorTutorial@0.0.1 /home/adam/apps/codeMentorTutorial
├── react-native-gradle-config@2.0.0 
└── UNMET PEER DEPENDENCY replace@*

npm WARN react-native-gradle-config@2.0.0 requires a peer of replace@* but none was installed.

这是脚本:

// this script install the peer dependency "replace" at the 
// consumer project of this package on postinstall
const fs = require('fs')
const path = require('path')
const readline = require('readline');
const packageJsonPath = path.resolve(getRootPath(), 'package.json')
const { exec } = require('child_process')

const package = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'))

if (doesReplaceExists()) {
  return
}

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

promptUser()
  .then(parseAnswer)
  .then(userAgrees => userAgrees && installReplace())
  .then(rlClose)
  .catch(console.error)
  .then(rlClose)

function promptUser () {
  return new Promise((resolve, reject) => {
    rl.question('This package has a peer dependency "replace", which is not installed in your project.\n' +
      'would u like to install it now? [Y/n]', resolve);    
  })
}

function parseAnswer (answer) {
  return answer.match(/^y(es)?$/i) || answer === ''
}

function installReplace () {
  console.log('installReplace')
  return new Promise((resolve, reject) => {
  // also tried without the cd command
    exec(`cd ${getRootPath()} && npm install --save-dev replace`, (err, res) => {
      console.log('installReplace err, res', err, res)
      if (err) {
        reject('error installing replace: ' + err)
        return
      }
      resolve()
    })
  })
}

function rlClose () {
  console.log('closing rl!')
  rl.close()
}

function doesReplaceExists () {
  return package.dependencies && package.dependencies.replace ||
    package.peerDependencies && package.peerDependencies.replace ||
    package.devDependencies && package.devDependencies.replace
}

function getRootPath () {
  return path.resolve(__dirname, '..', '..', '..')
}

我想在自己的 repo 上拥有这个 postinstall 脚本,以便其他 npm 作者可以轻松地将其复制到他们自己的项目中。

有任何想法吗?这甚至可能吗?

4

0 回答 0