【问题标题】:How to install node dependencies if they are not available Gulp + nodejs如果 Gulp + nodejs 不可用,如何安装节点依赖项
【发布时间】:2017-07-30 22:17:49
【问题描述】:

我正在使用 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"
}

【问题讨论】:

  • 你能添加更多的 gulp 依赖吗? gulp-install 声称让您“如果分别在 gulp 文件流中找到相关配置,则自动安装 npm、bower、tsd 和 pip 包/依赖项”。不过我从来没用过。

标签: javascript node.js gulp dependencies package.json


【解决方案1】:

您可以使用节点的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 并继续安装丢失的包。

【讨论】:

    【解决方案2】:

    所以,我通过使用 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' }
      })
    }) 
    

    【讨论】:

      猜你喜欢
      • 2018-09-11
      • 1970-01-01
      • 2021-07-30
      • 2015-06-02
      • 1970-01-01
      • 2016-01-05
      • 2015-05-26
      • 2023-01-12
      • 2014-11-27
      相关资源
      最近更新 更多