运行 gulp 通过环境变量提供的选项在 Windows 上不起作用

Running gulp with options supplied via environment variables does not work on Windows

我主要在 macOS 上编程,因此我的 package.json 看起来像这样:

[...]
"scripts": {
    "build": "NODE_TARGET=electron NODE_CONFIGURATION=development gulp",
    "watch": "NODE_TARGET=electron NODE_CONFIGURATION=development gulp watch",
    "build:web": "NODE_TARGET=web NODE_CONFIGURATION=development gulp",
    "watch:web": "NODE_TARGET=web NODE_CONFIGURATION=development gulp watch",
    "release": "NODE_TARGET=electron NODE_CONFIGURATION=production gulp",
    "release:web": "NODE_TARGET=web NODE_CONFIGURATION=production gulp",
    "clean": "gulp clean",
    "start": "electron ."
}
[...]

起初我尝试通过命令行参数以 gulp --web 的形式提供这些参数,但我没有找到任何正确解析这些参数的库。因此我在调用之前使用环境变量并像这样访问 gulpfile.babel.js 中的环境变量:

const targetPlatform = {
    isElectron: process.env.NODE_TARGET === "electron",
    isWeb: process.env.NODE_TARGET === "web"
};

不幸的是,我没有考虑到 Windows 并不能真正处理 npm 脚本提供的 commands/variables。我想知道如何在 Windows 和 macOS 之间移植这些调用。

我的一个朋友建议使用cross-env,这基本上解决了我遇到的问题。

在使用那个包之前,我只是用下面的代码解析了 process.argv 数组:

const commandLineArguments = (argumentList => {
    let parsedArguments = {}, index, option, thisOption, currentOption;
    for (index = 0; index < argumentList.length; index++) {
        thisOption = argumentList[index].trim();
        option = thisOption.replace(/^\-+/, '');
        if (option === thisOption) {
            if (currentOption) {
                parsedArguments[currentOption] = option;
            }
            currentOption = null;
        } else {
            currentOption = option;
            parsedArguments[currentOption] = true;
        }
    }
    return parsedArguments;
})(process.argv);

使用像 gulp --target electron --configuration development 这样的调用,我可以像这样访问这些参数:

const targetPlatform = {
    isElectron: commandLineArguments.target === "electron",
    isWeb: commandLineArguments.target === "web"
};
// Default setting if no option was supplied
if (!targetPlatform.isElectron && !targetPlatform.isWeb) {
    targetPlatform.isElectron = true;
}