# All files / src/platformTools/web index.js

20.13% Statements 30/149
0% Branches 0/53
0% Functions 0/33
23.64% Lines 26/110

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    2052x
    2x
    2x
    2x
    2x
    2x
    2x
    2x

    2x
    2x
    2x
    2x

    2x

    2x

    2x

    2x

    2x

    2x

    2x

    2x

    2x

    2x

    2x

    2x

    2x

    2x

     /* eslint-disable import/no-cycle */
    import path from 'path';
    import fs from 'fs';
    import chalk from 'chalk';
    import open from 'react-dev-utils/openBrowser';
    import ip from 'ip';
    import { executeAsync } from '../../systemTools/exec';
    import {
        logTask,
        getAppFolder,
        isPlatformActive,
        getAppTemplateFolder,
        checkPortInUse,
        logInfo,
        resolveNodeModulePath,
        getConfigProp,
        logSuccess,
        waitForWebpack,
        logError,
        logWarning,
        getAppTitle
    } from '../../common';
    import { copyBuildsFolder, copyAssetsFolder } from '../../projectTools/projectParser';
    import { copyFileSync } from '../../systemTools/fileutils';
    import { getMergedPlugin } from '../../pluginTools';
    import { selectWebToolAndDeploy } from '../../deployTools/webTools';

    const isRunningOnWindows = process.platform === 'win32';

    const _generateWebpackConfigs = (c) => {
        const appFolder = getAppFolder(c, c.platform);
        const templateFolder = getAppTemplateFolder(c, c.platform);

        const { plugins } = c.buildConfig;
        let modulePaths = [];
        let moduleAliasesString = '';
        const moduleAliases = {};

        for (const key in plugins) {
            const plugin = getMergedPlugin(c, key, plugins);
            if (!plugin) {

            } else if (plugin.webpack) {
                if (plugin.webpack.modulePaths) {
                    if (plugin.webpack.modulePaths === true) {
                        modulePaths.push(`node_modules/${key}`);
                    } else {
                        modulePaths = modulePaths.concat(plugin.webpack.modulePaths);
                    }
                }
                if (plugin.webpack.moduleAliases) {
                    if (plugin.webpack.moduleAliases === true) {
                        moduleAliasesString += `'${key}': {
                      projectPath: 'node_modules/${key}'
                    },`;
                        moduleAliases[key] = { projectPath: `node_modules/${key}` };
                    } else {
                        for (const aKey in plugin.webpack.moduleAliases) {
                            if (typeof plugin.webpack.moduleAliases[aKey] === 'string') {
                                moduleAliasesString += `'${aKey}': '${plugin.webpack.moduleAliases[aKey]}',`;
                                moduleAliases[key] = plugin.webpack.moduleAliases[aKey];
                            } else {
                                moduleAliasesString += `'${aKey}': {projectPath: '${plugin.webpack.moduleAliases[aKey].projectPath}'},`;
                                if (plugin.webpack.moduleAliases[aKey].projectPath) {
                                    moduleAliases[key] = { projectPath: plugin.webpack.moduleAliases[aKey].projectPath };
                                }
                            }
                        }
                    }
                }
            }
        }

        const env = getConfigProp(c, c.platform, 'environment');
        const extendConfig = getConfigProp(c, c.platform, 'webpackConfig', {});
        const entryFile = getConfigProp(c, c.platform, 'entryFile', 'index.web');
        const title = getAppTitle(c, c.platform);
        const analyzer = getConfigProp(c, c.platform, 'analyzer') || c.program.analyzer;

        copyFileSync(
            path.join(templateFolder, '_privateConfig', env === 'production' ? 'webpack.config.js' : 'webpack.config.dev.js'),
            path.join(appFolder, 'webpack.config.js')
        );

        const obj = {
            modulePaths,
            moduleAliases,
            analyzer,
            entryFile,
            title,
            ...extendConfig
        };

        const extendJs = `
        module.exports = ${JSON.stringify(obj, null, 2)}`;

        fs.writeFileSync(path.join(appFolder, 'webpack.extend.js'), extendJs);
    };

    const buildWeb = (c, platform) => new Promise((resolve, reject) => {
        const { debug, debugIp, maxErrorLength } = c.program;
        logTask(`buildWeb:${platform}`);

        const appFolder = getAppFolder(c, platform);

        let debugVariables = '';

        if (debug) {
            logInfo(`Starting a remote debugger build with ip ${debugIp || ip.address()}. If this IP is not correct, you can always override it with --debugIp`);
            debugVariables += `DEBUG=true DEBUG_IP=${debugIp || ip.address()}`;
        }

        _generateWebpackConfigs(c);

        const wbp = resolveNodeModulePath(c, 'webpack/bin/webpack.js');

        executeAsync(c, `npx cross-env NODE_ENV=production ${debugVariables} node ${wbp} -p --config ./platformBuilds/${c.runtime.appId}_${platform}/webpack.config.js`)
            .then(() => {
                logSuccess(`Your Build is located in ${chalk.white(path.join(appFolder, 'public'))} .`);
                resolve();
            })
            .catch(e => reject(e));
    });

    const configureWebProject = (c, platform) => new Promise((resolve, reject) => {
        logTask(`configureWebProject:${platform}`);

        if (!isPlatformActive(c, platform, resolve)) return;

        copyBuildsFolder(c, platform)
            .then(() => configureProject(c, platform))
            .then(() => resolve())
            .catch(e => reject(e));
    });

    const configureProject = async (c, platform, appFolderName) => {
        logTask(`configureProject:${platform}`);

        await copyAssetsFolder(c, platform);
    };

    const runWeb = (c, platform, port) => new Promise((resolve, reject) => {
        logTask(`runWeb:${platform}:${port}`);

        const extendConfig = getConfigProp(c, c.platform, 'webpackConfig', {});
        let devServerHost = extendConfig.devServerHost || '0.0.0.0';

        if (isRunningOnWindows && devServerHost === '0.0.0.0') {
            devServerHost = '127.0.0.1';
        }

        checkPortInUse(c, platform, port)
            .then((isPortActive) => {
                if (!isPortActive) {
                    logInfo(
                        `Looks like your ${chalk.white(platform)} devServerHost ${chalk.white(devServerHost)} at port ${chalk.white(
                            port
                        )} is not running. Starting it up for you...`
                    );
                    _runWebBrowser(c, platform, devServerHost, port, 500)
                        .then(() => runWebDevServer(c, platform, port))
                        .then(() => resolve())
                        .catch(e => reject(e));
                } else {
                    logWarning(
                        `Looks like your ${chalk.white(platform)} devServerHost at port ${chalk.white(
                            port
                        )} is already running. ReNative Will use it!`
                    );
                    _runWebBrowser(c, platform, devServerHost, port)
                        .then(() => resolve())
                        .catch(e => reject(e));
                }
            })
            .catch(e => reject(e));
    });

    const _runWebBrowser = (c, platform, devServerHost, port, delay = 0) => new Promise((resolve, reject) => {
        waitForWebpack(c, port)
            .then(() => open(`http://${devServerHost}:${port}/`))
            .catch(logError);
        resolve();
    });

    const runWebDevServer = (c, platform, port) => new Promise((resolve, reject) => {
        logTask(`runWebDevServer:${platform}`);

        const appFolder = getAppFolder(c, platform);
        const wpPublic = path.join(appFolder, 'public');
        const wpConfig = path.join(appFolder, 'webpack.config.js');

        _generateWebpackConfigs(c);
        const command = `webpack-dev-server -d --devtool source-map --config ${wpConfig}  --inline --hot --colors --content-base ${wpPublic} --history-api-fallback --port ${port} --mode=development`;
        return executeAsync(c, command, { stdio: 'inherit', silent: true });
    });

    const deployWeb = (c, platform) => new Promise((resolve, reject) => {
        logTask(`deployWeb:${platform}`);
        selectWebToolAndDeploy(c, platform).then(resolve).catch(reject);
    });

    export { buildWeb, runWeb, configureWebProject, runWebDevServer, deployWeb };