繁体   English   中英

有没有办法将常量导入Gruntfile.js文件?

[英]Is there a way to import constants into a Gruntfile.js file?

我以前没有使用grunt的经验,但是我的任务是查看是否有办法将gruntfile.js文件减少一些(它们很大)。 在挑选它们时,我发现其中有30%的人在每个文件中定义了相同的常量(这些是指向特定于我们环境的路径)。

我的第一个想法是,可以将大块文件移动到一个公共文件中,每个gruntfile.js可以从单个文件中导入所有这些路径,但是我一直无法找到一种在线完成该文件的方法。 外面有人有经验吗?

Gruntfile.js是常规的JavaScript文件; 您可以像导入其他任何JS文件一样,将变量从另一个文件导入该文件。 从MDN文档https://developer.mozilla.org/zh-CN/docs/web/javascript/reference/statements/export

在模块中,我们可以使用以下代码:

// module "my-module.js"
function cube(x) {
  return x * x * x;
}
const foo = Math.PI + Math.SQRT2;
var graph = {
    options:{
        color:'white',
        thickness:'2px'
    },
    draw: function(){
        console.log('From graph draw function');
    }
}
export { cube, foo, graph };

这样,在另一个脚本中,我们可以拥有:

import { cube, foo, graph } from 'my-module';
graph.options = {
    color:'blue',
    thickness:'3px'
}; 
graph.draw();
console.log(cube(3)); // 27
console.log(foo);    // 4.555806215962888

您可以在一个单独的模块或JSON文件中定义所有常量,并稍后使用require()

constants.js

module.exports = {
    constant1: 'abc',
    constant2: 1234
}

然后在您的gruntfile.js

const constants = require('./constants')
constants.constant1 === 'abc' // true

您还可以在JSON文件中定义常量

constants.json

{
    "constant1": "abc",
    "constant2": 1234,
}

require()一样, const constants = require('./constants')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM