2017-12-27 12 views
0

RollupJS를 번들로 사용하고 CommonJS (플러그인을 통해) 또는 ES6 모듈을 읽을 수 있습니다. 그러나이 모듈은 UMD 형식으로 보이며, 많은 줄을 바꾸지 않고 편집 할 수있는 빠른 방법을 찾고 있습니다. 그래서 commonJS 또는 ES6 형식입니다.IIFE 모듈을 RollupJS에서 가져올 수있는 것으로 변환하십시오.

사람들은 무엇을 제안합니까? 나는 5,000 라인의 .js 파일의 상단과 하단을 보여준다. UPDATE


@module vrlinkjs **/ (function (mak) { mak.MessageKindEnum = { Any : -1, Other : 0, AttributeUpdate : 1, Interaction : 2, Connect : 3, ObjectDeletion : 4 }; /** Decodes AttributeUpdate messages into an EnvironmentalStateRepository object. @class EnvironmentalStateDecoder @constructor @augments StateDecoder @param {WebLVCConnection} webLVCConnection Connection to a WebLVC server **/ mak.EnvironmentalStateDecoder = function(webLVCConnection) { mak.StateDecoder.apply(this, arguments); }; mak.EnvironmentalStateDecoder.prototype = Object.create(mak.StateDecoder.prototype, { constructor : { value : mak.EnvironmentalStateDecoder }, /** Decodes a AttributeUpdate message into an EntityStateRepository object. @method decode @param {Object} attributeUpdate WebLVC AttributeUpdate message @param {EntityStateRepository} stateRep State repository to be updated **/ decode : { value : function(attributeUpdate, stateRep) { // if(this.webLVCConnection.timeStampType == mak.TimeStampType.TimeStampAbsolute && // attributeUpdate.TimeStampType == mak.TimeStampType.TimeStampAbsolute) { // } else { // stateRep.timeStampType = mak.TimeStampType.TimeStampRelative; // } stateRep.timeStampType = mak.TimeStampType.TimeStampRelative; var curTime = 0.0; // if (stateRep->timeStampType() == DtTimeStampAbsolute) // { // // Use timestamp as time of validity // curTime = pdu.guessTimeValid(myExConn->clock()->simTime()); // } // else // { // // Use receive time as time of validity // curTime = myExConn->clock()->simTime(); // } curTime = this.webLVCConnection.clock.simTime; if(attributeUpdate.ProcessIdentifier != undefined) { stateRep.entityIdentifier = attributeUpdate.EntityIdentifier; } if(attributeUpdate.Type != undefined) { stateRep.entityType = attributeUpdate.Type; } if(attributeUpdate.ObjectName != undefined) { stateRep.objectName = attributeUpdate.ObjectName; } if(attributeUpdate.GeometryRecords != undefined) { stateRep.GeometryRecords = attributeUpdate.GeometryRecords; } if(attributeUpdate.EnvObjData != undefined) { if(attributeUpdate.EnvObjData.VrfObjName != undefined) { stateRep.marking = attributeUpdate.EnvObjData.VrfObjName; } } } } }); ..... } (this.mak = this.mak || {})); 

I는 정말 좋아 (아래)에서 estus ES6 모듈 용액을 사용했다. 롤업 보딩 문제는 해결되었지만 여전히 런타임 오류가 있습니다.

하지만 조금 더 할 일이 있습니다. Chrome에서이 오류가 발생합니다. HTML main.html 파일에는 두 가지 변종이 있습니다. 하나는 번들을 사용하고 다른 하나는 내 es6 모듈을 가져옵니다. 롤업을 사용하지 않고 번들을 만들고 사용할 때도 오류가 발생합니다.

Uncaught TypeError: Cannot set property objectName of [object Object] which has only a getter 
    at mak$1.ReflectedEntity.mak$1.ReflectedObject [as constructor] (vrlink.mjs:818) 
    at new mak$1.ReflectedEntity (vrlink.mjs:903) 
    at mak$1.ReflectedEntityList.value (vrlink.mjs:1358) 
    at mak$1.WebLVCMessageCallbackManager.<anonymous> (vrlink.mjs:1155) 
    at mak$1.WebLVCMessageCallbackManager.processMessage (vrlink.mjs:1745) 
    at mak$1.WebLVCConnection.drainInput (vrlink.mjs:2139) 
    at SimLink.tick (SimLink.js:34) 

이것은 ES6 인생 모듈로 변환 할 때 가해자 보인다. 그것은 세터가 없다고 말합니다.

코드는 제 제작물이 아니지만 IIFE를 ES6으로 변환하는 데 큰 노력을 기울여서는 안된 것 같습니다. 기분을 상하게하는 조각은 다음과 같습니다

/** 
    Represents a connection to a WebLVC server. 
    clientName and port are required. webLVCVersion is optional (current version 
    supported by the WebLVC server will be in effect). serverLocation is optional 
    (websocket connection will be made to the host servering the javascript) 
    @class WebLVCConnection 
    @constructor 
    @param {String} clientName String representing name of the client federate 
    @param {Number} port Websocket port number 
    @param {Number} webLVCVersion WebLVC version number 
    @param {String} serverLocation Hostname of websocket server 
    **/ 
mak.WebLVCConnection = function (clientName, port, webLVCVersion, serverLocation, url) { 

    var self = this; 

    if (clientName == undefined) { 
     throw new Error("clientName not specified"); 
    } 
    if (!(typeof clientName == "string" && clientName.length > 0)) { 
     throw new Error("Invalid ClientName specified"); 
    } 
    if (port == undefined) { 
     throw new Error("Port not specified"); 
    } 
    if (url == undefined) { 
     url = "/ws"; 
    } 

    var websocket; 
    if (serverLocation == undefined) { 
     if (location.hostname) { 
      websocket = new WebSocket("ws://" + location.hostname + ":" + port + url); 
     } 
     else { 
      websocket = new WebSocket("ws://localhost:" + port + "/ws"); 
     } 
    } 
    else { 
     websocket = new WebSocket("ws://" + serverLocation + ":" + port + url); 
    } 

    /** 
    Websocket connected to a WebLVC server. 
    @property websocket 
    @type WebSocket 
    **/ 
    this.websocket = websocket; 

    /** 
    DIS/RPR-style identifier, used to generate new unique IDs for entities simulated 
    through this connection. Array of 3 numbers [site ID, host ID, entity number]. 
    @property currentId 
    @type Array 
    **/ 
    this.currentId = [1, 1, 0]; 

    /** 
    Manages registration and invoking of message callbacks. 
    @property webLVCMessageCallbackManager 
    @type WebLVCMessageCallbackManager 
    **/ 
    this.webLVCMessageCallbackManager = new mak.WebLVCMessageCallbackManager(); 

    /** 
    Simulation clock 
    @property clock 
    @type Clock 
    **/ 
    this.clock = new mak.Clock(); 

    /** 
    Indicates whether timestamping is relative or absolute 
    (mak.TimeStampType.TimeStampRelative or 
    mak.TimeStampType.TimeStampAbsolute). 
    @property {Number} timeStampType 
    **/ 
    this.timeStampType = mak.TimeStampType.TimeStampRelative; 

    /** 
    List of incoming messages. When messages are received, they are placed 
    in this queue. The drainInput() member function must be called regularly 
    to remove and process messages in this queue. 
    @property {Array} messageQueue 
    **/ 
    this.messageQueue = new Array(); 

    /** 
    Callback function invoked on receipt of a message. Calls 
    webLVCMessageCallbackManager.processMessage(). 
    @method processMessage 
    @private 
    **/ 
    this.processMessage = this.webLVCMessageCallbackManager.processMessage.bind(this.webLVCMessageCallbackManager); 

    /** 
    Callback function invoked when websocket connection is opened. Sends 
    the initial WebLVC connect message. 
    @method onopen 
    @private 
    **/ 
    this.websocket.onopen = function() { 
     var connectMessage = { 
      MessageKind: mak.MessageKindEnum.Connect, 
      ClientName: clientName 
     } 

     if (webLVCVersion != undefined) { 
      connectMessage.WebLVCVersion = webLVCVersion; 
     } 

     if (self.websocket.readyState == 1) { 
      self.websocket.send(JSON.stringify(connectMessage)); 
     } 
    }; 

    /** 
    Callback function invoked when a WebLVC message is received. Parses the 
    the JSON message data and passes the resulting object to processMessage. 
    @method onmessage 
    @event {Object} JSON message 
    @private 
    **/ 
    this.websocket.onmessage = function (event) { 
     //just in case 
     if (event.data == "ping") 
      return; 

     var message = JSON.parse(event.data); 
     if (message != null) { 
      self.messageQueue.push(message); 
     } else { 
      console.warn("onmessage - null message received"); 
     } 
    }; 

    /** 
    Callback function invoked when the websocket is closed. 
    @method onclose 
    @private 
    **/ 
    this.websocket.onclose = function() { 
     console.debug("In websocket.onclose"); 
    }; 

    /** 
    Callback function invoked when an error in the websocket is detected. 
    Sends warning to console. 
    @method onerror 
    @private 
    **/ 
    this.websocket.onerror = function() { 
     console.log("websocket onerror"); 
    }; 

    this.isOk = function() { 
     return this.websocket.readyState == 1; 
    } 
}; 

mak.WebLVCConnection.prototype = { 

    constructor: mak.WebLVCConnection, 

    /** 
    Set the DIS/RPR-style application ID. 
    @method set applicationId 
    @param {Array} applicationId Array of 2 integers [site ID, host ID]. 
    **/ 
    set applicationId(applicationId) { 
     this.currentId[0] = applicationId[0]; 
     this.currentId[1] = applicationId[1]; 
     this.currentId[2] = 0; 
    }, 

    /** 
    Returns next available DIS/RPR-style entity ID. 
    @method nextId 
    @return {Array} Array of 3 integers [site ID, host ID, entity number]. 
    **/ 
    get nextId() { 
     this.currentId[2]++; 
     return this.currentId; 
    }, 

    /** 
    Register callback function for a given kind of message. 
    @method addMessageCallback 
    @param {Number} messageKind WebLVC MessageKind 
    @param callback Function to be invoked 
    **/ 
    addMessageCallback: function (messageKind, callback) { 
     this.webLVCMessageCallbackManager.addMessageCallback(messageKind, callback); 
    }, 

    /** 
    De-register callback function for a given kind of message. 
    @method removeMessageCallback 
    @param messageKind WebLVC MessageKind 
    @param callback Function to be invoked 
    **/ 
    removeMessageCallback: function (messageKind, callback) { 
     this.webLVCMessageCallbackManager.removeMessageCallback(messageKind, callback); 
    }, 

    /** 
    Send a WebLVC message to the server. 
    @method send 
    @param {Object} message 
    **/ 
    send: function (message) { 
     try { 
      if (this.websocket.readyState == 1) { 
       this.websocket.send(JSON.stringify(message)); 
      } 
     } catch (exception) { 
      console.log("Error sending on websocket - exception: " + exception); 
     } 
    }, 

    /** 
    Send a time-stamped WebLVC message to the server. 
    @method sendStamped 
    @param {Object} message 
    **/ 
    sendStamped: function (message) { 
     // Timestamp is hex string 
     var timeStamp = this.currentTimeForStamping().toString(16); 
     //message.TimeStamp = ""; // timeStamp; 

     this.send(message); 
    }, 

    /** 
    Get the current simulation time for a time stamp. 
    @method currentTimeForStamping 
    @return {Number} Simulation time in seconds. 
    **/ 
    currentTimeForStamping: function() { 
     if (this.timeStampType == mak.TimeStampType.TimeStampAbsolute) { 
      return this.clock.simTime(); 
     } 
     else { 
      return this.clock.absRealTime(); 
     } 
    }, 

    /** 
    Iterate through message queue, calling processMessage() and then 
    removing each message. Should be called regularly from your 
    application. 
    @method drainInput 
    **/ 
    drainInput: function() { 
     var message; 

     while (this.messageQueue.length > 0) { 
      message = this.messageQueue.shift(); 
      this.processMessage(message); 
     } 
    }, 

    /** 
    Closes the websocket connection. Calls the destroy method on its 
    WebLVCMessageCallbackManager data member. 
    @method destroy 
    **/ 
    destroy: function() { 
     console.debug("In WebLVCConnection.destroy"); 
     this.webLVCMessageCallbackManager.destroy(); 
     this.websocket.close(); 
    } 
}; 
+0

을 @ estup IIFE 모듈을 ES6으로 변환하기위한 제목을 변경하는 것은 롤업이 실제로 v가 아니기 때문에 이 솔루션은 도움을 원하는 사람들에게 좀 더 일반적이 될 것입니다. –

+0

그게 효과가있을 것 같아요. – estus

답변

1

UMD : 당신이 가 무엇인지 궁금해하는 경우

mak.VrfBackendStateRepository = function (objectName) { 

/** 
Unique string identifying entity 
@property objectName 
@type String 
**/ 
this.objectName = objectName; //error generated on this line! 

, 그것은 인생의 코드에서이 기능에 의해 생성된다 mak.webLVConnection라는 객체이며, 모듈은 정의상 CommonJS입니다. 위의 코드는 단지 IIFE이며 mak global에 의존합니다.

인생의 래퍼 함수는 기본적으로 대체 또는 ES 모듈 수출 이름을 지정할 수 있습니다 :

const mak = {}; 

mak.MessageKindEnum = { ... }; 
... 

export default mak; 

또는 CommonJS 수출과 :

const mak = {}; 

mak.MessageKindEnum = { ... }; 
... 

module.exports = mak; 
+0

나는 이것을 정말로 좋아한다. 첫 번째 제안 (ES6 모듈)을 사용하여 번들 (롤업)을 만들지 않고도 사용할 수있었습니다. 필자는 모듈을 작성하여 번들로 또는 .mjs 파일 당 es6 임포트로 작동 할 수 있도록했습니다. 아직 IIFE -> ES6 converstion –

+0

을 차단하고있는 것에 대한 업데이트를 참조하십시오. 이것은 다른 문제입니다. 이것은 VrfBackendStateRepository를 사용하는 방법과'this.objectName'에'this'가 무엇을 기대하는지에 달려 있습니다. – estus

+0

나는 * this *가 무엇인지에 대한 설명과 그 생성에 책임이있는 함수를 제공했다. 나는 그것이 함수이기 때문에 es6가 엄격하다고 생각한다. 속성을 설정하지 못할 수도있다. 그 맞습니까? –

0

는 당신이 시도 않았다

(function (mak) { 
    ... 
}(module.exports)); 

// instead of 
// } (this.mak = this.mak || {})); 
+0

업데이트와 동일한 문제가 발생합니다. –

+0

내부 스크립트가 버그가있을 수 있습니까? – Hitmands

+0

아니요, 문제없이 IIFE를 사용했습니다. 스크립트 태그가있는 html에 포함 시키면 다음과 같습니다. -> –

관련 문제