node.js - Gulp 环境和预处理

标签 node.js gruntjs preprocessor gulp env

在 Grunt 中,我曾经使用一个名为 env 的插件。这将允许我在特定构建中定义一个环境。我有 3 个版本。一个是 DEV,它将使用单独拆分的所有文件。 PROD 会连接所有内容,而 RELEASE 会连接和丑化。我希望在 Gulp 中做同样的事情。我确实看到了 Gulp 的预处理器,但没有定义环境。

问题是。我能做什么?显然我不想一直定义所有的 JS 文件,我也不想要 3 个不同的 HTML 页面带有不同的脚本标签。

在我的 HTML 中我会有这样的东西:

<!-- @if NODE_ENV == 'DEVELOPMENT' -->
<script src="js/example1.js" type="text/javascript"></script>
<script src="js/example2.js" type="text/javascript"></script>
<script src="js/example3.js" type="text/javascript"></script>
<!-- @endif -->

<!-- @if NODE_ENV == 'PRODUCTION' -->
<script src="js/project.js" type="text/javascript"></script>
<!-- @endif -->

<!-- @if NODE_ENV == 'RELEASE' -->
<script src="js/project.min.js" type="text/javascript"></script>
<!-- @endif -->

我的 grunt 插件看起来像这样:

env: {
    dev: {
        NODE_ENV: 'DEVELOPMENT'
    },
    prod: {
        NODE_ENV: 'PRODUCTION'
    },
    release: {
        NODE_ENV: 'RELEASE'
    }
},
preprocess: {
    options: {
        context: {
            name: '<%= pkg.outputName %>',
            version: '<%= pkg.version %>',
            port: '<%= pkg.port %>'
        }
    },
    dev: {
        src: 'index.html',
        dest: '<%= pkg.outputFolder %>/index.html'
    },
    prod: {
        src: 'index.html',
        dest: '<%= pkg.outputFolder %>/index.html'
    },
    release: {
        src: 'index.html',
        dest: '<%= pkg.outputFolder %>/index.html'
    }
},

最佳答案

你可能应该使用 gulp-preprocess 并在 gulp 中做这样的事情

var preprocess = require('gulp-preprocess');
.pipe(preprocess({context: { NODE_ENV: 'PRODUCTION', RELEASE_TAG: '2.6.4', DEBUG: false}}))

在你的 html 中有这样的东西

<!-- @if NODE_ENV='DEVELOPMENT' -->
   <a href="test?v<!-- @echo RELEASE_TAG -->" />
<!-- @endif -->

关于node.js - Gulp 环境和预处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23119501/

相关文章:

javascript - JWT.decode 返回 null

ios - 为测试定义常量值,为调试定义另一个常量值

使用#if、#endif 的 Swift 错误

windows - Node.js 在 Windows 上安装模块

node.js - 如何在新的包名称规则后检查 npm 包名称的可用性?

gruntjs - grunt 任务完成后运行命令?

node.js - 错误 : Cannot find module 'time-grunt'

gruntjs - 由于 jit-grunt : Plugin for the "help" not found,grunt 失败

c# - #if DEBUG 与条件 ("DEBUG")

node.js - 如何在返回二进制数据的 node.js 中编写 Lambda 函数?