簡體   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