Как запретить серверу Webpack Dev делать запросы XHR, когда приложение находится в работе? Его регистрация "[WDS] Отключено" - PullRequest
0 голосов
/ 28 февраля 2020

Когда я внедряю свое приложение в производство, я вижу некоторые ошибки в консоли, и мой частный IP-адрес становится доступным.

close @ index.js?http:/10.7.9.347:172
index.js?http:/10.0.0.125:172 [WDS] Disconnected!
close @ index.js?http:/10.7.9.347:172
10.7.9.347/sockjs-node/info?t=1582875821841:1 Failed to load resource: net::ERR_CONNECTION_TIMED_OUT
10.7.9.347/sockjs-node/info?t=1582875821843:1 Failed to load resource: net::ERR_CONNECTION_TIMED_OUT
10.7.9.347/sockjs-node/info?t=1582875843486:1 Failed to load resource: net::ERR_CONNECTION_TIMED_OUT
10.7.9.347/sockjs-node/info?t=1582875844587:1 Failed to load resource: net::ERR_CONNECTION_TIMED_OUT

Я пытался внести изменения в файл конфигурации webpack, но это не помогло ничем не помог.

Также обратите внимание, что я не использую реагирующие скрипты в этом проекте, я запускаю собственный скрипт сборки для генерации папки сборки.

Для лучшего понимания я копирую содержимое некоторых из моих файлов здесь:

build. js => скрипт для создания папки сборки

/*eslint-disable no-console */

// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'production';
process.env.NODE_ENV = 'production';

// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
  throw err;
});

// Ensure environment variables are read.
require('../config/env');

const path = require('path');
const fs = require('fs-extra');
const chalk = require('chalk');
const webpack = require('webpack');
const bfj = require('bfj');
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
const formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
const printHostingInstructions = require('react-dev-utils/printHostingInstructions');
const printBuildError = require('react-dev-utils/printBuildError');
const {
  measureFileSizesBeforeBuild,
  printFileSizesAfterBuild,
} = require('react-dev-utils/FileSizeReporter');
const { checkBrowsers } = require('react-dev-utils/browsersHelper');

const configFactory = require('../config/webpack.config');
const paths = require('../config/paths');

// These sizes are pretty large. We'll warn for bundles exceeding them.
const WARN_AFTER_BUNDLE_GZIP_SIZE = 512 * 1024;
const WARN_AFTER_CHUNK_GZIP_SIZE = 1024 * 1024;

const isInteractive = process.stdout.isTTY;

// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
  process.exit(1);
}

// Process CLI arguments
const argv = process.argv.slice(2);
const writeStatsJson = argv.indexOf('--stats') !== -1;

// We require that you explictly set browsers and do not fall back to
// browserslist defaults.

const config = configFactory('production');

// Create the production build and print the deployment instructions.
function build(previousFileSizes) {
  console.log(chalk.cyan('Creating an optimized production build...'));

  const compiler = webpack(config);
  return new Promise((resolve, reject) => {
    compiler.run((err, stats) => {
      if (err) {
        return reject(err);
      }
      const messages = formatWebpackMessages(
        stats.toJson({ all: false, warnings: true, errors: true }),
      );
      if (messages.errors.length) {
        // Only keep the first error. Others are often indicative
        // of the same problem, but confuse the reader with noise.
        if (messages.errors.length > 1) {
          messages.errors.length = 1;
        }
        return reject(new Error(messages.errors.join('\n\n')));
      }
      if (
        process.env.CI &&
        (typeof process.env.CI !== 'string' || process.env.CI.toLowerCase() !== 'false') &&
        messages.warnings.length
      ) {
        console.log(
          chalk.yellow(
            '\nTreating warnings as errors because process.env.CI = true.\n' +
              'Most CI servers set it automatically.\n',
          ),
        );
        return reject(new Error(messages.warnings.join('\n\n')));
      }

      const resolveArgs = {
        stats,
        previousFileSizes,
        warnings: messages.warnings,
      };
      if (writeStatsJson) {
        return bfj
          .write(`${paths.appBuild}/bundle-stats.json`, stats.toJson())
          .then(() => resolve(resolveArgs))
          .catch(error => reject(new Error(error)));
      }

      return resolve(resolveArgs);
    });
  });
}

function copyPublicFolder() {
  fs.copySync(paths.appAssets, paths.appBuild, {
    dereference: true,
    filter: file => ![paths.appHtml].includes(file),
  });
}

checkBrowsers(paths.appPath, isInteractive)
  .then(() => measureFileSizesBeforeBuild(paths.appBuild))
  .then(previousFileSizes => {
    // Remove all content but keep the directory so that
    // if you're in it, you don't end up in Trash
    fs.emptyDirSync(paths.appBuild);
    // Merge with the public folder
    copyPublicFolder();
    // Start the webpack build
    return build(previousFileSizes);
  })
  .then(
    ({ stats, previousFileSizes, warnings }) => {
      if (warnings.length) {
        console.log(chalk.yellow('Compiled with warnings.\n'));
        console.log(warnings.join('\n\n'));
        console.log(
          `\nSearch for the ${chalk.underline(
            chalk.yellow('keywords'),
          )} to learn more about each warning.`,
        );
        console.log(
          `To ignore, add ${chalk.cyan('// eslint-disable-next-line')} to the line before.\n`,
        );
      } else {
        console.log(chalk.green('Compiled successfully.\n'));
      }

      console.log('File sizes after gzip:\n');
      printFileSizesAfterBuild(
        stats,
        previousFileSizes,
        paths.appBuild,
        WARN_AFTER_BUNDLE_GZIP_SIZE,
        WARN_AFTER_CHUNK_GZIP_SIZE,
      );
      console.log();

      const appPackage = require(paths.packageJson);
      const { publicUrl } = paths;
      const { publicPath } = config.output;
      const buildFolder = path.relative(process.cwd(), paths.appBuild);
      printHostingInstructions(appPackage, publicUrl, publicPath, buildFolder);
    },
    err => {
      console.log(chalk.red('Failed to compile.\n'));
      printBuildError(err);
      process.exit(1);
    },
  )
  .catch(err => {
    if (err && err.message) {
      console.log(err.message);
    }
    process.exit(1);
  });

webpack.config. js

/*eslint-disable no-console */
const path = require('path');
const webpack = require('webpack');
const { format } = require('date-fns');

const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
const CircularDependencyPlugin = require('circular-dependency-plugin');
const GitRevPlugin = require('git-rev-webpack-plugin');
const HtmlPlugin = require('html-webpack-plugin');
const InlineChunkHtmlPlugin = require('react-dev-utils/InlineChunkHtmlPlugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const ModuleNotFoundPlugin = require('react-dev-utils/ModuleNotFoundPlugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
const WorkboxWebpackPlugin = require('workbox-webpack-plugin');

const getClientEnvironment = require('./env');
const paths = require('./paths');

const NPMPackage = require(paths.packageJson);
const gitRevPlugin = new GitRevPlugin();

const GITHASH = gitRevPlugin.hash() || '';

// Source maps are resource heavy and can cause out of memory issue for large source files.
const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';
// Some apps do not need the benefits of saving a web request, so not inlining the chunk
// makes for a smoother build process.
const shouldInlineRuntimeChunk = process.env.INLINE_RUNTIME_CHUNK !== 'false';

module.exports = webpackEnv => {
  const isProd = webpackEnv === 'production';
  const isDev = webpackEnv === 'development';

  // Webpack uses `publicPath` to determine where the app is being served from.
  // In development, we always serve from the root. This makes config easier.
  const { publicPath } = paths;
  // Some apps do not use client-side routing with pushState.
  // For these, "homepage" can be set to "." to enable relative asset paths.
  const shouldUseRelativeAssetPaths = publicPath === './';

  // `publicUrl` is just like `publicPath`, but we will provide it to our app
  // as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
  // Omit trailing slash as %PUBLIC_PATH%/xyz looks better than %PUBLIC_PATH%xyz.
  const publicUrl = publicPath.slice(0, -1);
  // Get environment variables to inject into our app.
  const env = getClientEnvironment(publicUrl);

  const optimizeCSSOptions = {
    // `inline: false` forces the sourcemap to be output into a
    // separate file
    inline: false,
    // `annotation: true` appends the sourceMappingURL to the end of
    // the css file, helping the browser find the sourcemap
    annotation: true,
  };
  const htmlPluginOptions = {
    githash: GITHASH,
    inject: true,
    template: paths.appHtml,
    title: NPMPackage.title,
  };

  if (isProd) {
    htmlPluginOptions.minify = {
      collapseWhitespace: true,
      keepClosingSlash: true,
      minifyCSS: true,
      minifyJS: true,
      minifyURLs: true,
      removeComments: true,
      removeEmptyAttributes: true,
      removeRedundantAttributes: true,
      removeStyleLinkTypeAttributes: true,
      useShortDoctype: true,
    };
  }

  const cssLoaders = [
    isDev && require.resolve('style-loader'),
    isProd && {
      loader: MiniCssExtractPlugin.loader,
      options: {
        ...(shouldUseRelativeAssetPaths ? { publicPath: '../../' } : undefined),
      },
    },
    {
      loader: 'css',
      options: {
        sourceMap: isProd,
      },
    },
    {
      loader: 'postcss',
      options: {
        // Necessary for external CSS imports to work
        // https://github.com/facebook/create-react-app/issues/2677
        ident: 'postcss',
        plugins: [
          require('postcss-flexbugs-fixes'),
          require('postcss-preset-env')({
            autoprefixer: {
              flexbox: 'no-2009',
            },
            stage: 3,
          }),
        ],
        sourceMap: isProd && shouldUseSourceMap,
      },
    },
  ].filter(Boolean);

  const sassLoaders = [
    ...cssLoaders,
    {
      loader: 'sass',
      options: {
        sourceMap: isProd,
      },
    },
  ];

  return {
    bail: isProd,
    context: paths.appSrc,
    mode: webpackEnv,
    devtool: isProd && shouldUseSourceMap ? 'source-map' : 'cheap-module-source-map',
    entry: {
      'scripts/modernizr': paths.appModernizr,
      'scripts/bundle': [
        // isProd && paths.appPolyfills,
        // isDev && 'react-dev-utils/webpackHotDevClient',
        isDev && 'react-error-overlay',
        paths.appIndexJs,
      ].filter(Boolean),
    },
    output: {
      chunkFilename: isProd ? 'scripts/js/[name].[git-hash].chunk.js' : '[name].chunk.js',
      filename: isProd ? '[name].[git-hash].js' : '[name].js',
      path: paths.appBuild,
      pathinfo: isDev,
      publicPath,
      // Point sourcemap entries to original disk location (format as URL on Windows)
      devtoolModuleFilenameTemplate: isProd
        ? info => path.relative(paths.appSrc, info.absoluteResourcePath).replace(/\\/g, '/')
        : info => path.resolve(info.absoluteResourcePath).replace(/\\/g, '/'),
    },
    resolve: {
      alias: {
        assets: paths.appAssets,
        modernizr$: paths.appModernizrrc,
        test: paths.test,
        'react-dom': '@hot-loader/react-dom',
      },
      modules: [paths.appSrc, paths.nodeModules],
      extensions: ['.js', '.jsx', '.json'],
    },
    resolveLoader: {
      moduleExtensions: ['-loader'],
    },
    module: {
      rules: [
        {
          oneOf: [
            {
              test: /\.(js|jsx|mjs)$/,
              loader: 'babel',
              options: {
                cacheDirectory: false,
              },
              include: paths.appSrc,
            },
            // "postcss" loader applies autoprefixer to our CSS.
            // "css" loader resolves paths in CSS and adds assets as dependencies.
            // "style" loader turns CSS into JS modules that inject <style> tags.
            // In production, we use MiniCSSExtractPlugin to extract that CSS
            // to a file, but in development "style" loader enables hot editing
            // of CSS.
            // By default we support CSS Modules with the extension .module.css
            {
              test: /\.css$/,
              use: cssLoaders,
              // Don't consider CSS imports dead code even if the
              // containing package claims to have no side effects.
              // Remove this when webpack adds a warning or an error for this.
              // See https://github.com/webpack/webpack/issues/6571
              sideEffects: true,
            },
            // Opt-in support for SASS (using .scss or .sass extensions).
            // By default we support SASS Modules with the
            // extensions .module.scss or .module.sass
            {
              test: /\.(scss|sass)$/,
              use: sassLoaders,
              // Don't consider CSS imports dead code even if the
              // containing package claims to have no side effects.
              // Remove this when webpack adds a warning or an error for this.
              // See https://github.com/webpack/webpack/issues/6571
              sideEffects: true,
            },
            {
              test: /\.(jpe?g|png|gif)$/i,
              use: [
                {
                  loader: 'file',
                  query: { name: 'static/[name].[ext]' },
                },
                {
                  loader: 'image-webpack',
                  query: {
                    optipng: {
                      optimizationLevel: 5,
                    },
                    pngquant: {
                      quality: '75-90',
                    },
                  },
                },
              ],
            },
            {
              test: /\.svg$/,
              use: [
                {
                  loader: '@svgr/webpack',
                  options: {
                    icon: true,
                  },
                },
                {
                  loader: 'file',
                  options: {
                    name: 'static/[name].[git-hash].[ext]',
                  },
                },
              ],
            },
            {
              test: /modernizrrc\.json$/,
              type: 'javascript/auto',
              use: ['expose?Modernizr', 'modernizr', 'json'],
            },
            {
              test: /\.md$/,
              use: ['html', 'markdown'],
            },
            // "file" loader makes sure those assets get served by WebpackDevServer.
            // When you `import` an asset, you get its (virtual) filename.
            // In production, they would get copied to the `build` folder.
            // This loader doesn't use a "test" so it will catch all modules
            // that fall through the other loaders.
            {
              loader: 'file',
              // Exclude `js` files to keep "css" loader working as it injects
              // its runtime that would otherwise be processed through "file" loader.
              // Also exclude `html` and `json` extensions so they get processed
              // by webpacks internal loaders.
              exclude: [/\.(js|jsx|mjs)$/, /\.html$/, /\.json$/],
              options: {
                name: 'static/[name].[git-hash].[ext]',
              },
            },
            // ** STOP ** Are you adding a new loader?
            // Make sure to add the new loader(s) before the "file" loader.
          ],
        },
      ],
    },
    optimization: {
      minimize: isProd,
      minimizer: [
        new TerserPlugin({
          terserOptions: {
            parse: {
              // we want uglify-js to parse ecma 8 code. However, we don't want it
              // to apply any minfication steps that turns valid ecma 5 code
              // into invalid ecma 5 code. This is why the 'compress' and 'output'
              // sections only apply transformations that are ecma 5 safe
              // https://github.com/facebook/create-react-app/pull/4234
              ecma: 8,
            },
            compress: {
              ecma: 5,
              warnings: false,
              // Disabled because of an issue with Uglify breaking seemingly valid code:
              // https://github.com/facebook/create-react-app/issues/2376
              // Pending further investigation:
              // https://github.com/mishoo/UglifyJS2/issues/2011
              comparisons: false,
              // Disabled because of an issue with Terser breaking valid code:
              // https://github.com/facebook/create-react-app/issues/5250
              // Pending futher investigation:
              // https://github.com/terser-js/terser/issues/120
              inline: 2,
            },
            mangle: {
              safari10: true,
              keep_fnames: true,
            },
            output: {
              ecma: 5,
              comments: false,
              // Turned on because emoji and regex is not minified properly using default
              // https://github.com/facebook/create-react-app/issues/2488
              ascii_only: true,
            },
          },
          // Use multi-process parallel running to improve the build speed
          // Default number of concurrent runs: os.cpus().length - 1
          parallel: true,
          // Enable file caching
          cache: true,
          sourceMap: shouldUseSourceMap,
        }),
        new OptimizeCSSAssetsPlugin({
          cssProcessorOptions: {
            parser: require('postcss-safe-parser'),
            map: shouldUseSourceMap ? optimizeCSSOptions : false,
          },
        }),
      ],
    },
    plugins: [
      new webpack.DefinePlugin({
        ...env.stringified,
        APP__BRANCH: JSON.stringify(gitRevPlugin.branch()),
        APP__BUILD_DATE: JSON.stringify(format(new Date(), 'dd/MM/yyyy')),
        APP__GITHASH: JSON.stringify(gitRevPlugin.hash()),
        APP__VERSION: JSON.stringify(NPMPackage.version),
      }),
      new ModuleNotFoundPlugin(paths.appPath),
      gitRevPlugin,
      new HtmlPlugin(htmlPluginOptions),
      new InterpolateHtmlPlugin(HtmlPlugin, env.raw),
      new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
      isProd &&
        shouldInlineRuntimeChunk &&
        new InlineChunkHtmlPlugin(HtmlPlugin, [/runtime~.+[.]js/]),
      isProd &&
        new MiniCssExtractPlugin({
          filename: 'css/bundle.[git-hash].css',
          chunkFilename: 'css/bundle.[git-hash].chunk.css',
        }),
      isProd &&
        new WorkboxWebpackPlugin.GenerateSW({
          clientsClaim: true,
          exclude: [/\.map$/, /asset-manifest\.json$/],
          importWorkboxFrom: 'cdn',
          navigateFallback: `${publicUrl}/index.html`,
          navigateFallbackBlacklist: [
            // Exclude URLs starting with /_, as they're likely an API call
            new RegExp('^/_'),
            // Exclude any URLs whose last part seems to be a file extension
            // as they're likely a resource and not a SPA route.
            // URLs containing a "?" character won't be blacklisted as they're likely
            // a route with query params (e.g. auth callbacks).
            new RegExp('/[^/?]+\\.[^/]+$'),
          ],
        }),
      isDev &&
        new CircularDependencyPlugin({
          exclude: /node_modules/,
          failOnError: true,
          cwd: process.cwd(),
        }),
      // Add module names to factory functions so they appear in browser profiler.
      isDev && new webpack.NamedModulesPlugin(),
      // This is necessary to emit hot updates (currently CSS only):
      isDev && new webpack.HotModuleReplacementPlugin(),
      // Watcher doesn't work well if you mistype casing in a path so we use
      // a plugin that prints an error when you attempt to do this.
      // See https://github.com/facebookincubator/create-react-app/issues/240
      isDev && new CaseSensitivePathsPlugin(),
      // If you require a missing module and then `npm install` it, you still have
      // to restart the development server for Webpack to discover it. This plugin
      // makes the discovery automatic so you don't have to restart.
      // See https://github.com/facebookincubator/create-react-app/issues/186
      isDev && new WatchMissingNodeModulesPlugin(paths.nodeModules),
    ].filter(Boolean),
    // Some libraries import Node modules but don't use them in the browser.
    // Tell Webpack to provide empty mocks for them so importing them works.
    node: {
      dgram: 'empty',
      fs: 'empty',
      net: 'empty',
      tls: 'empty',
      child_process: 'empty',
    },
    // Turn off performance processing because we utilize
    // our own hints via the FileSizeReporter
    performance: false,
  };
};

webpackDevServer. js

/*eslint-disable func-names, prefer-arrow-callback, no-console */
const path = require('path');
const errorOverlayMiddleware = require('react-dev-utils/errorOverlayMiddleware');
const evalSourceMapMiddleware = require('react-dev-utils/evalSourceMapMiddleware');
const noopServiceWorkerMiddleware = require('react-dev-utils/noopServiceWorkerMiddleware');

const paths = require('./paths');

const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
const host = process.env.HOST || '0.0.0.0';

module.exports = function(proxy, allowedHost) {
  // noinspection WebpackConfigHighlighting
  return {
    clientLogLevel: 'none',
    compress: true,
    contentBase: paths.appAssets,
    // disableHostCheck: !proxy || process.env.DANGEROUSLY_DISABLE_HOST_CHECK === 'true',
    disableHostCheck: true,
    historyApiFallback: {
      disableDotRule: true,
    },
    host,
    hot: true,
    https: protocol === 'https',
    noInfo: true,
    overlay: false,
    proxy,
    public: allowedHost,
    publicPath: '/',
    quiet: false,
    stats: { colors: true },
    watchOptions: {
      ignored: new RegExp(
        `^(?!${path
          .normalize(`${paths.appSrc}/`)
          .replace(/[\\]+/g, '\\\\')}).+[\\\\/]node_modules[\\\\/]`,
        'g',
      ),
    },
    watchContentBase: true,
    before(app, server) {
      // This lets us fetch source contents from webpack for the error overlay
      app.use(evalSourceMapMiddleware(server));
      // This lets us open files from the runtime error overlay.
      app.use(errorOverlayMiddleware());
      // This service worker file is effectively a 'no-op' that will reset any
      // previous service worker registered for the same host:port combination.
      // We do this in development to avoid hitting the production cache if
      // it used the same host and port.
      // https://github.com/facebook/create-react-app/issues/2272#issuecomment-302832432
      app.use(noopServiceWorkerMiddleware());
    },
  };
};

start. js

/*eslint-disable func-names, prefer-arrow-callback, no-console */

// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'development';
process.env.NODE_ENV = 'development';

// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
  throw err;
});

// Ensure environment variables are read.
require('../config/env');

const chalk = require('chalk');
const { differenceInSeconds } = require('date-fns');
const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const clearConsole = require('react-dev-utils/clearConsole');
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
const openBrowser = require('react-dev-utils/openBrowser');
const {
  choosePort,
  createCompiler,
  prepareProxy,
  prepareUrls,
} = require('react-dev-utils/WebpackDevServerUtils');

const paths = require('../config/paths');
const configFactory = require('../config/webpack.config');
const createDevServerConfig = require('../config/webpackDevServer');

const config = configFactory('development');

const isInteractive = process.stdout.isTTY;

// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
  process.exit(1);
}

// Tools like Cloud9 rely on this.
const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000;
const HOST = process.env.HOST || '0.0.0.0';

// We attempt to use the default port but if it is busy, we offer the user to
// run on a different port. `detect()` Promise resolves to the next free port.
choosePort(HOST, DEFAULT_PORT)
  .then(port => {
    if (port === null) {
      // We have not found a port.
      return;
    }
    const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
    const appName = require(paths.packageJson).name;
    const urls = prepareUrls(protocol, HOST, port);
    const compiler = createCompiler({ webpack, config, appName, urls });

    // Load proxy config
    const proxySetting = require(paths.packageJson).proxy;
    const proxyConfig = prepareProxy(proxySetting, paths.appAssets);
    // Serve webpack assets generated by the compiler over a web sever.
    const serverConfig = createDevServerConfig(proxyConfig, urls.lanUrlForConfig);

    let start;

    compiler.plugin('compile', function() {
      start = new Date();
    });

    compiler.plugin('emit', function(compilation, callback) {
      const now = new Date();
      console.log(
        chalk.yellow(`Duration: ${differenceInSeconds(now, start)}s - ${compilation.hash}`),
      );

      callback();
    });

    const devServer = new WebpackDevServer(compiler, serverConfig);
    // Launch WebpackDevServer.
    devServer.listen(port, HOST, err => {
      if (err) {
        console.log(err);
        return;
      }

      if (isInteractive) {
        clearConsole();
      }

      console.log(chalk.cyan('Starting the development server...'));
      openBrowser(urls.localUrlForBrowser);
    });

    ['SIGINT', 'SIGTERM'].forEach(function(sig) {
      process.on(sig, function() {
        devServer.close();
        process.exit();
      });
    });
  })
  .catch(err => {
    if (err && err.message) {
      console.log(err.message);
    }
    process.exit(1);
  });

развертывание. js

/*eslint-disable no-console */
const { exec } = require('child_process');
const chalk = require('chalk');
const publish = require('./publish');

function deploy() {
  const start = Date.now();
  console.log(chalk.blue('Bundling...'));

  return exec('npm run build', errBuild => {
    if (errBuild) {
      console.log(chalk.red(errBuild));
      process.exit(1);
    }

    console.log(`Bundled in ${(Date.now() - start) / 1000} s`);

    publish();
  });
}

module.exports = deploy;

publi sh. js

/*eslint-disable no-console */
const chalk = require('chalk');
const Rsync = require('rsync');

const paths = require('../config/paths');

function publish() {
  console.log(chalk.blue('Publishing...'));
  const rsync = new Rsync()
    .shell('ssh')
    .exclude('.DS_Store')
    .flags('az')
    .source(`${paths.appBuild}/`)
    .destination(
      'reactboilerplate@react-boilerplate.com:/home/reactboilerplate/public_html/redux-saga',
    );

  rsync.execute((error, code, cmd) => {
    if (error) {
      console.log(chalk.red('Something went wrong...', error, code, cmd));
      process.exit(1);
    }

    console.log(chalk.green('Published'));
  });
}

module.exports = publish;

Примечание: у меня есть изменил частный IP из соображений безопасности.

Если у кого-то есть какие-либо знания по этому поводу, пожалуйста, поделитесь

...