簡體   English   中英

如果不可用則如何安裝節點依賴Gulp + nodejs

[英]How to install node dependencies if they are not available Gulp + nodejs

我正在使用Gulp啟動Web應用程序。 我的gulpfile.js具有以下基本代碼:

var gulp = require('gulp'),
nodemon = require('gulp-nodemon');

gulp.task('default', function () {
  nodemon({
    script: 'server.js'
  , ext: 'js html'
  , env: { 'NODE_ENV': 'development' }
  })
})

使用Gulp,我要檢查依賴項,如果不可用,請安裝它們,然后運行'script.js'。 如何才能做到這一點?

我有以下package.json:

{
"name": "sample-project",
"version": "1.0.0",
"description": "Displays users and user details",
"main": "server.js",
"dependencies": {
"jquery"  : “>=1.5.1",
“bootstrap”: ">= 3.0.0”
}
"directories": {
"test": "test"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"author": "Arihant Jain",
"license": "ISC"
}

您可以使用節點的child_process這樣獨立於正在執行的任務來獨立運行npm install

var gulp = require('gulp');
var nodemon = require('gulp-nodemon');
var child_process = require('child_process');

gulp.task('default', function () {

    // Run npm install from the child process
    child_process.exe('npm install', function(err, stdout, stderr){

        // if everything goes well
        if(!err){

             // run nodemon
              nodemon({
                script: 'server.js'
              , ext: 'js html'
              , env: { 'NODE_ENV': 'development' }
              })

        }

    });
})

根據您的要求:

使用Gulp,我要檢查依賴項,如果不可用,請安裝它們。

這正是npm install所做的。 它檢查本地package.json並繼續安裝缺少的軟件包。

因此,我通過使用gulp-run解決了這一問題。 我實際上運行命令npm install

gulpfile看起來像這樣:

        var gulp = require('gulp'),
        nodemon = require('gulp-nodemon')
        run = require('gulp-run')
        runSequence = require('run-sequence')
        open = require('gulp-open');

gulp.task('default', function() {
  runSequence('dependencies',
              'start',
              'uri');
});


      gulp.task('dependencies', function() {
  return run('npm install').exec();
})

    gulp.task('uri', function(){
  gulp.src(__filename)
  .pipe(open({uri: 'http://localhost:3000/index.html'}));
});



    gulp.task('start', function () {
  nodemon({
    script: 'server.js'
  , ext: 'js html'
  , env: { 'NODE_ENV': 'development' }
  })
}) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM