Javascript 有没有办法将常量导入Grunfile.js文件?
我以前没有使用grunt的经验,但我的任务是看看是否有办法将GrunFile.js文件稍微删减一点(它们非常庞大)。当我仔细阅读它们时,我发现其中有30%在每个文件中定义相同的常量(这些是特定于我们环境的路径)Javascript 有没有办法将常量导入Grunfile.js文件?,javascript,gruntjs,Javascript,Gruntjs,我以前没有使用grunt的经验,但我的任务是看看是否有办法将GrunFile.js文件稍微删减一点(它们非常庞大)。当我仔细阅读它们时,我发现其中有30%在每个文件中定义相同的常量(这些是特定于我们环境的路径) 我的第一个想法是,这一大块可以移动到一个公共文件中,每个gruntfile.js都可以从一个文件中导入所有这些路径,但我还没有找到一种在线方式。有没有人对此有经验?Gruntfile.js是一个常规的JavaScript文件;您可以像在任何其他JS文件中一样,将变量从另一个文件导入其中。
我的第一个想法是,这一大块可以移动到一个公共文件中,每个gruntfile.js都可以从一个文件中导入所有这些路径,但我还没有找到一种在线方式。有没有人对此有经验?Gruntfile.js是一个常规的JavaScript文件;您可以像在任何其他JS文件中一样,将变量从另一个文件导入其中。从MDN文档中: 在模块中,我们可以使用以下代码: 这样,在另一个脚本中,我们可以:
GrunFile.js是一个常规JavaScript文件;您可以像在任何其他JS文件中一样,将变量从另一个文件导入其中。从MDN文档中: 在模块中,我们可以使用以下代码: 这样,在另一个脚本中,我们可以:
您可以在单独的模块或JSON文件中定义所有常量,然后
require()
constants.js
:
module.exports = {
constant1: 'abc',
constant2: 1234
}
const constants = require('./constants')
constants.constant1 === 'abc' // true
然后在grunfile.js中:
module.exports = {
constant1: 'abc',
constant2: 1234
}
const constants = require('./constants')
constants.constant1 === 'abc' // true
您还可以在JSON文件中定义常量
constants.json
{
"constant1": "abc",
"constant2": 1234,
}
和require()
使用相同的方法,const constants=require('./constants')
您可以在单独的模块或JSON文件中定义所有常量,然后require()
使用它
constants.js
:
module.exports = {
constant1: 'abc',
constant2: 1234
}
const constants = require('./constants')
constants.constant1 === 'abc' // true
然后在grunfile.js中:
module.exports = {
constant1: 'abc',
constant2: 1234
}
const constants = require('./constants')
constants.constant1 === 'abc' // true
您还可以在JSON文件中定义常量
constants.json
{
"constant1": "abc",
"constant2": 1234,
}
和require()
使用相同的方法,const constants=require('./constants')