代码之家  ›  专栏  ›  技术社区  ›  Christian Ivicevic

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

  •  0
  • Christian Ivicevic  · 技术社区  · 7 年前

    我主要在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脚本提供的命令/变量。我想知道如何使这些呼叫在Windows和macOS上可移植。

    1 回复  |  直到 7 年前
        1
  •  0
  •   Christian Ivicevic    7 年前

    我的一个朋友建议使用 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;
    }