【问题标题】:npm/gulp/nodejs : Different files for productionnpm/gulp/nodejs : 用于生产的不同文件
【发布时间】:2015-11-16 10:56:02
【问题描述】:

我有一个 gulp 脚本可以连接和缩小我的 JavaScript。

使用gulp-html-replace 插件,我可以用index.html 中的连接文件替换我所有的JS 依赖项。

我最终得到一个开发版本 (/dev/index.html),包含所有单个 JS 文件(更易于调试)和一个生产版本,所有 JS 连接 (/prod/index.html)。

现在我在 config.js 文件中有一个配置标志(在 NodeJS 中),我执行以下操作:

res.render(((config.build === 'prod') ? './prod' : './dev') + 'myPage')

但我对这个解决方案并不满意,因为它添加了很多代码,而且很容易忘记编写这段代码。

  • 有更好的解决方案吗?
  • 此解决方案是否发生在 Gulp 中 (例如,gulp prodgulp dev
  • 还是发生在 Node 中(例如通过设置虚拟目录)

我是这个 npm/gulp/node 工作流的新手,不知道什么属于哪里

【问题讨论】:

    标签: node.js npm gulp


    【解决方案1】:

    我喜欢这样做的方式是为index.html 维护两个单独的版本。 index-development.html 用于开发环境,index-production.html 用于生产环境。

    index-development.html 包括所有脚本和 css(非缩小和连接)和 index-production.html 作为缩小和连接脚本和 css 链接。

    我从 gulp 脚本构造index.html

    默认情况下会部署index-development.html。 如果我为 gulp 脚本指定参数p,它将部署index-production.html

    无需更新要在您的express router 中提供的文件的文件路径。

    先做

    npm install yargs

    在 gulp 中,我包括

    var argv = require('yargs').argv;

    检查参数p (gulp -p) 是否通过

    传递给 gulp(用于生产的 p)

    var isProduction = argv.p;

    然后,

    if(isProduction){
        taskSequence = ['combineControllers','combineServices','productionsIndex','startServer'];
    } else{
        taskSequence = ['developmentIndex','startServer'];
    }
    
    
    gulp.task('default', taskSequence);
    gulp.task('startServer', function(){
        exec('npm start', function (err, stdout, stderr) {
        console.log(stdout);
        console.log(stderr);
        cb(err);
      });
    });
    gulp.task('productionsIndex', function(done) {
        return gulp.src('./www/index-productions.html')
               .pipe(concat('index.html'))
               .pipe(gulp.dest('./public/'));
    });
    
    gulp.task('developmentIndex', function(done) {
        return gulp.src('./www/index-development.html')
               .pipe(concat('index.html'))
               .pipe(gulp.dest('./public/'));
    });
    

    这样,您的 index.html 文件将动态构建,而无需更改 express 中的代码,您可以像这样提供它

    res.render('index');

    如果您想在任何地方使用myPage.html,只需将上面代码中的index.htmlindex 替换为myPage.htmlmyPage

    编辑:

    要在开发环境中启动您的应用程序,只需运行gulp

    要在生产环境中启动您的应用程序,只需运行gulp -p

    简单!

    【讨论】:

      【解决方案2】:

      在您的应用初始化过程中,您可以设置视图的路径。

      app.set('views', process.cwd() + ((config.build === 'prod') ? '/prod' : '/dev'));
      

      现在你可以像这样调用渲染函数了:

      res.render('myPage');
      

      【讨论】:

        猜你喜欢
        • 2016-06-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-17
        • 2015-11-18
        • 2017-04-12
        • 1970-01-01
        • 2019-06-29
        相关资源
        最近更新 更多