UNPKG

cybertron-utils

Version:
106 lines (93 loc) 3.48 kB
const CHUSocket = require( './CHUSocket' ); const getComponents = require( '../cli/getComponents' ); const createDevelopComponentAPI = require( './createDevelopComponentAPI' ); const getGroup = require( '../cli/getGroup' ); class CHUWebpackPlugin { constructor( options ) { this.client_list = {}; this.componentHash = {}; this.port = options.port; this.devServerPort = options.devServerPort; this.socket = new CHUSocket( this.port, '/develop_hot_update' ); // 建立连接 this.socket.io.on( 'connection', client => { console.log('客户端连接成功!'); // 客户端断开连接 client.on('disconnect', () => { console.log('客户端断开连接!'); this.client_list[client.id] && delete this.client_list[client.id]; }) // 将客户端id发送给客户端 client.emit( 'pre_register', client.id ); // 客户端收到id后回传,并记录 client.on( 'register', ( data ) => { this.register( client, data ) } ); // // 客户端发起请求 client.on( 'initDevelopComponent', this.initDevelopComponent.bind( this ) ); } ); } register ( client, data ) { const { id } = JSON.parse( data ); this.client_list[id] = { client, group: getGroup() }; } initDevelopComponent ( id ) { const { client } = this.client_list[id]; if ( !client ) return; const result = { group: getGroup(), list: createDevelopComponentAPI( getComponents( this.componentHash ), { ip: '0.0.0.0', port: this.devServerPort } ) } this.sendDevelopCompoentInfoToClient( id, 'server_initDevelopComponent', JSON.stringify( result ) ); } saveHash ( hash ) { this.componentHash = hash; // 发布消息 this.releaseComponentUpdateMessage(); } releaseComponentUpdateMessage() { const result = { group: getGroup(), list: createDevelopComponentAPI( getComponents( this.componentHash ), { ip: '0.0.0.0', port: this.devServerPort } ) } for ( let key in this.client_list ) { if ( this.client_list[key].client.connected ) { this.sendDevelopCompoentInfoToClient( key, 'server_initDevelopComponent', JSON.stringify( result ) ); } else { delete this.client_list[key]; } } } sendDevelopCompoentInfoToClient ( id, event, msg ) { const { client } = this.client_list[id]; if ( !client ) return; client.emit( event, msg ); } apply ( compiler ) { compiler.hooks.afterEmit.tap( 'CHU', ( compilation ) => { var stats = compilation.getStats().toJson( { hash: true, chunks: true, modules: true } ); const hash = {}; for ( let i = 0; i < stats.chunks.length; i++ ) { const item = stats.chunks[i]; hash[item.id] = { name: item.id, hash: item.hash, files: item.files } } this.saveHash( hash ); } ); } } module.exports = CHUWebpackPlugin;