export function webpackDevServerTask()

in packages/just-scripts/src/tasks/webpackDevServerTask.ts [50:96]


export function webpackDevServerTask(options: WebpackDevServerTaskOptions = {}): TaskFunction {
  const configPath =
    options && options.config
      ? resolveCwd(path.join('.', options.config))
      : findWebpackConfig('webpack.serve.config.js', 'webpack.config.js');

  // for webpack-cli < 4, use webpack-dev-server directly, for webpack-cli >= 4, use "webpack serve"
  const webpackCliPath = resolve('webpack-cli/package.json');

  if (!webpackCliPath) {
    throw new Error('Missing webpack-cli package. Please install webpack-cli as a devDependency.');
  }

  const webpackCliVersion = JSON.parse(fs.readFileSync(webpackCliPath, 'utf-8')).version;

  const useWebpackServe = semver.gte(webpackCliVersion, '4.0.0');

  const devServerCmd = useWebpackServe
    ? // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
      [resolve('webpack/bin/webpack.js')!, 'serve']
    : // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
      [resolve('webpack-dev-server/bin/webpack-dev-server.js')!];

  return function webpackDevServer() {
    let args = [...(options.nodeArgs || []), ...devServerCmd];

    if (configPath && fs.existsSync(configPath)) {
      args = [...args, '--config', configPath];
      options.env = { ...options.env, ...(configPath.endsWith('.ts') && getTsNodeEnv(options.tsconfig, options.transpileOnly)) };
    }

    if (options.open) {
      args.push('--open');
    }

    if (options.mode) {
      args = [...args, '--mode', options.mode];
    }

    if (options.webpackCliArgs) {
      args = [...args, ...options.webpackCliArgs];
    }

    logger.info(process.execPath, encodeArgs(args).join(' '));
    return spawn(process.execPath, args, { stdio: 'inherit', env: options.env });
  };
}