index.js 4.16 KB
Newer Older
1 2 3 4
const { join } = require('path');
const { writeFileSync, mkdirSync, existsSync } = require('fs');
const rimraf = require('rimraf');
const serveStatic = require('serve-static');
5
const { resolve } = require('path');
6
const { portfinder, chalk, delay, createDebug, chokidar, signale, glob } = require('@umijs/utils');
dengxiaofeng's avatar
dengxiaofeng committed
7 8
const argv = require('./argv');
const setup = require('./middlewares/frontendMiddleware');
邓晓峰's avatar
邓晓峰 committed
9
const pkg = require('../package.json');
10 11 12 13
const config = require('../config/config');
const mockMiddewares = require('./mock');
const emitter = require('./event');
const Server = require('./server');
14
const debug = createDebug('preset-build-in:proxy:createMiddleware');
15
// const proxyConfig = require('../config/proxy');
16 17
const loadDotEnv = require('./utils/loadDotEnv');
const { getSchema } = require('./openapi');
18 19 20
const cleanRequireCache = require('./utils/cleanRequireCache');


21
(async () => {
22
  const defaultPort = process.env.PORT || argv.port || (config && config.devServer && config.devServer.port);
23 24 25
  const port = await portfinder.getPortPromise({
    port: defaultPort ? parseInt(String(defaultPort), 10) : 8080,
  });
26
  const homename = process.env.HOST || (config && config.devServer && config.devServer.host) || '127.0.0.1';
27 28 29
  console.log(chalk.cyan('Starting the development server...'));
  // process.send && process.send({ type: 'UPDATE_PORT', port });
  const isHTTPS = process.env.HTTPS || (argv && argv.https);
dengxiaofeng's avatar
dengxiaofeng committed
30

31
  await delay(500);
32
  const absNodeModulesPath = `${process.cwd()}/node_modules`;
33
  const openAPIFilesPath = join(absNodeModulesPath, 'civ_open_api');
34

35 36 37 38 39 40
  const loadEnv = () => {
    const basePath = join(process.cwd(), '.env');
    const localPath = `${basePath}.local`;
    loadDotEnv(basePath);
    loadDotEnv(localPath);
  };
dengxiaofeng's avatar
dengxiaofeng committed
41

42
  loadEnv();
43

44 45 46 47 48 49 50 51
  // const absNodeModulesPath = cwd + '/node_modules';
  try {
    if (existsSync(openAPIFilesPath)) {
      rimraf.sync(openAPIFilesPath);
    }
    mkdirSync(join(openAPIFilesPath));
  } catch (error) {
    console.error(error);
dengxiaofeng's avatar
dengxiaofeng committed
52 53
  }

54 55 56 57 58 59
  const server = new Server({
    compress: true,
    https: !!isHTTPS,
    headers: {
      'access-control-allow-origin': '*',
    },
60
    port,
61 62 63 64 65 66 67 68
    beforeMiddlewares: [
      (config.mock || process.env.MOCK !== 'none') && mockMiddewares,
    ],
    afterMiddlewares: [serveStatic(openAPIFilesPath)],
    proxy: config.proxy,
    ...(config.devServer || {}),
  });

69

70 71 72 73 74 75 76 77 78
  setup(
    server.app,
    {
      outputPath: resolve(process.cwd(), pkg.name.toLocaleLowerCase()),
      publicPath: `/${pkg.name.toLocaleLowerCase()}`,
    },
    config,
    {
      port,
79 80
      homename,
    },
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
  // proxy config 热更新
  const ignore = [
    // ignore mock files under node_modules
    'node_modules/**'
  ];

  const cwd = process.cwd();
  const proxyWatcherPaths = [
    ...(glob.sync('config/proxy.js', {
      cwd,
      ignore,
    }) || []),
    ...(glob.sync('**/proxy.js', {
      cwd,
      ignore,
    }) || []),
    ...(glob.sync('.env', {
      cwd,
      ignore,
    }) || []),
    ...(glob.sync('.env.local', {
      cwd,
      ignore,
    }) || [])
  ];


  const watcher = chokidar.watch(proxyWatcherPaths, {
    ignoreInitial: true,
  });
  const errors = [];

  watcher.on('ready', () => debug('Initial scan complete. Ready for changes')).on('all', async (event, file) => {
116
    debug(`[${event}] ${file}, reload proxy config`);``
117
    errors.splice(0, errors.length);
118
    cleanRequireCache(Array.from(new Set(proxyWatcherPaths)));
119
    if (!errors.length) {
120 121
      const hotProxy = require('../config/proxy');
      server.setupProxy && server.setupProxy(hotProxy[process.env.NODE_ENV], true);
122 123 124 125 126 127 128 129 130
      signale.success(`Proxy config parse success`);
    }
  });

  process.once('SIGINT', async () => {
    await watcher.close();
  });


131
  emitter.on('onDevCompileDone', async () => {
dengxiaofeng's avatar
dengxiaofeng committed
132
    try {
133
      const openAPIConfig = config.openAPI;
134
      if (openAPIConfig && openAPIConfig.schemaPath) {
135 136 137 138 139 140
        const openAPIJson = await getSchema(openAPIConfig.schemaPath);
        writeFileSync(
          join(openAPIFilesPath, 'civ-plugins_openapi.json'),
          JSON.stringify(openAPIJson, null, 2),
        );
      }
141 142
    } catch (error) {
      console.error(error);
dengxiaofeng's avatar
dengxiaofeng committed
143
    }
144 145
  });

146

147 148 149 150 151
  await server.listen({
    port,
    homename,
  });
})();