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



我之前没有使用grunt的经验,但我的任务是看看是否有办法将gruntfile.js文件修剪一下(它们很大(。当我选择它们时,我看到其中 30% 在每个文件中定义了相同的常量(这些是特定于我们环境的事物的路径(。

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

Gruntfile.js是一个常规的JavaScript文件;你可以像在任何其他JS文件中一样将变量从另一个文件导入到其中。从 MDN 文档中 https://developer.mozilla.org/en-US/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')

最新更新