2015-05-20 126 views
8

我有一個應用程序是一個網頁遊戲服務器,並說例如我有node_modules,我在目錄中使用./和我有一個適當的package.json這些。它發生在./public/目錄中。我有一個網站正在服務,它本身使用node_modules,並且它自己也有一個合適的package.json。npm如何安裝當前目錄以及包含package.json文件的子目錄?

我知道我可以通過瀏覽目錄來做到這一點。但是有沒有一種命令或方法可以使其自動化,以便其他開發人員可以更輕鬆地在系統中引導應用程序?

+0

你的意思是這樣https://www.exratione.com/2015/01/run-npm-install-on -all-subdirectories-containing-packages /? – Dhiraj

+0

我看到了,認爲這有點嚇人。我使用的所有東西都是跨平臺的,所以任何類型的操作系統開發人員都可以安裝我正在做的這件事。我不知道關於BASH的一件事,這是做這件事的唯一方法嗎?感謝您的幫助。 – Elemenofi

回答

13

假設你是在Linux/OSX,你可以嘗試這樣的事:

find ./apps/* -maxdepth 1 -name package.json -execdir npm install \;

參數:

./apps/* - 路徑進行搜索。我建議在這裏非常具體,以避免它在其他node_modules目錄中拾取package.json文件(請參閱下面的maxdepth)。

-maxdepth 1 - 只有穿越深度爲1(即當前目錄 - 不要進入子目錄)的搜索路徑

-name的package.json - 文件名以匹配搜索

-execdir npm install \; - 對於搜索中的每個結果,在保存該文件的目錄中運行npm install(在此例中爲package.json)。請注意,轉義分號的反斜槓必須在JSON文件中自行轉義。

在你的根的package.json將這個在安裝後鉤它將運行每次你的NPM安裝

"scripts": { 
    "postinstall": "find ./apps/* -name package.json -maxdepth 1 -execdir npm install \\;" 
} 
+0

我在'\'處收到'非法轉義序列'的錯誤;' – Pratik

+1

@Pratik嘗試'「postinstall」:「find ./apps/* -name package.json -maxdepth 1 -execdir npm install \\;」' – eddywashere

0

對於跨平臺支持(含Windows)中你可能試試我的解決方案 純Node.js的

運行它作爲 「預裝」 NPM腳本

const path = require('path') 
const fs = require('fs') 
const child_process = require('child_process') 

const root = process.cwd() 
npm_install_recursive(root) 

function npm_install_recursive(folder) 
{ 
    const has_package_json = fs.existsSync(path.join(folder, 'package.json')) 

    if (!has_package_json && path.basename(folder) !== 'code') 
    { 
     return 
    } 

    // Since this script is intended to be run as a "preinstall" command, 
    // skip the root folder, because it will be `npm install`ed in the end. 
    if (has_package_json) 
    { 
     if (folder === root) 
     { 
      console.log('===================================================================') 
      console.log(`Performing "npm install" inside root folder`) 
      console.log('===================================================================') 
     } 
     else 
     { 
      console.log('===================================================================') 
      console.log(`Performing "npm install" inside ${folder === root ? 'root folder' : './' + path.relative(root, folder)}`) 
      console.log('===================================================================') 
     } 

     npm_install(folder) 
    } 

    for (let subfolder of subfolders(folder)) 
    { 
     npm_install_recursive(subfolder) 
    } 
} 

function npm_install(where) 
{ 
    child_process.execSync('npm install', { cwd: where, env: process.env, stdio: 'inherit' }) 
} 

function subfolders(folder) 
{ 
    return fs.readdirSync(folder) 
     .filter(subfolder => fs.statSync(path.join(folder, subfolder)).isDirectory()) 
     .filter(subfolder => subfolder !== 'node_modules' && subfolder[0] !== '.') 
     .map(subfolder => path.join(folder, subfolder)) 
} 
相關問題