javascript 从 grunt 模板访问进程/环境
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13989978/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Accessing the process / environment from a grunt template
提问by vitch
I have some code in a grunt.js file which is working with 0.3 but breaks on 0.4:
我在 grunt.js 文件中有一些代码,它使用 0.3 但在 0.4 上中断:
{
dest: '<%= process.env.DEST %>/index.html'
}
In 0.3 process is defined and so I can access variables defined in the environment inside the template when I am e.g. passing file paths to other plugins.
在 0.3 中定义了进程,因此当我将文件路径传递给其他插件时,我可以访问模板内环境中定义的变量。
Is there an alternative approach to this which will work in 0.4? Or a way to put a breakpoint in while the template is rendering so that I can see what variables are available?
有没有其他方法可以在 0.4 中工作?或者在模板渲染时放置断点以便我可以看到哪些变量可用?
回答by Sindre Sorhus
The default data is the config object. You can add the environment variable to the config object or just use it directly.
默认数据是配置对象。您可以将环境变量添加到配置对象或直接使用它。
grunt.initConfig({
destination: process.env.DEST,
task: {
target: {
dest: '<%= destination %>/index.html'
}
},
});
or
或者
grunt.initConfig({
task: {
target: {
dest: process.env.DEST + '/index.html'
}
},
});
回答by Aniket Thakur
That's a great straight forward answer by Sindre. Alternatively you can do (use the grunt-env plugin: https://npmjs.org/package/grunt-env)-
这是 Sindre 的一个很好的直接回答。或者你可以这样做(使用 grunt-env 插件:https: //npmjs.org/package/grunt-env)-
grunt.initConfig({
env : {
test : {
DEST : 'testDEST'
},
dev : {
DEST : 'devDEST'
},
qa : {
DEST : 'qaDEST'
},
prod : {
DEST : 'prodDEST'
}
}
});
grunt.registerTask('setenvs', 'Set environment variables', function() {
grunt.config('ENVS', process.env);
});
and then use
然后使用
{
dest: '<%= ENVS.DEST %>/index.html'
}
Your task would be -
你的任务是——
grunt.registerTask('default', [
'env:dev',
'setenvs'
'yourTask'
]);
Proposed alternative approach just so that you can use <%= ... %>
and you don't have to hardcode it in initConfig. Target for env you can take as input from user and pass it to env.
建议的替代方法只是为了您可以使用<%= ... %>
并且不必在 initConfig 中对其进行硬编码。您可以将 env 的目标作为用户的输入并将其传递给 env。