* invoked before build & runAfterBuild, do something different in each senario * * @param {string} env NODE_ENV * @param {boolean} isInBuild is in build process * @param {Object} options options * @param {string} options.config custom config file absolute path
(env, isInBuild, options = {})
| 27 | * @param {string} options.config custom config file absolute path |
| 28 | */ |
| 29 | async init(env, isInBuild, options = {}) { |
| 30 | this.env = env; |
| 31 | this.isProd = this.env === 'production'; |
| 32 | this.configReader = new ConfigReader(this.cwd, this.env, options.config); |
| 33 | |
| 34 | if (!process.env.NODE_ENV) { |
| 35 | process.env.NODE_ENV = env; |
| 36 | } |
| 37 | |
| 38 | /** |
| 39 | * in a build process, we need to read config by scan a directory, |
| 40 | * but for online server after build, we just read config.json directly |
| 41 | */ |
| 42 | if (isInBuild) { |
| 43 | // scan directory |
| 44 | this.config = await this.configReader.read(); |
| 45 | } |
| 46 | else { |
| 47 | // read config from config.json |
| 48 | this.config = await this.configReader.readConfigFile(); |
| 49 | } |
| 50 | |
| 51 | this.middlewareComposer = new MiddlewareComposer(this); |
| 52 | this.renderer = new Renderer(this); |
| 53 | this.builder = this.isProd |
| 54 | ? new ProdBuilder(this) : new DevBuilder(this); |
| 55 | |
| 56 | // expose Koa & express middleware factory function |
| 57 | this.koaMiddleware = this.middlewareComposer.koa |
| 58 | .bind(this.middlewareComposer); |
| 59 | this.expressMiddleware = this.middlewareComposer.express |
| 60 | .bind(this.middlewareComposer); |
| 61 | |
| 62 | // expose render function |
| 63 | this.render = this.renderer.render.bind(this.renderer); |
| 64 | |
| 65 | if (!this.isProd) { |
| 66 | // register rebuild listener |
| 67 | this.on('start-rebuild', async () => { |
| 68 | // read config again |
| 69 | let newConfig = await this.configReader.read(); |
| 70 | |
| 71 | // init builder again |
| 72 | this.builder.init(newConfig); |
| 73 | |
| 74 | // clean middlewares |
| 75 | this.middlewareComposer.reset(newConfig); |
| 76 | |
| 77 | // notify the server that it needs to restart |
| 78 | this.emit('rebuild'); |
| 79 | }); |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | /** |
| 84 | * build in dev & prod mode |
no test coverage detected