2016-05-05 79 views
0

我是webpack的新手,並且遇到了與webpack綁定socket.io-client的問題。有人可以告訴我我做錯了什麼嗎?如何將socket.io-client與webpack捆綁在一起?

我使用角2 RC.1

的package.json

...."dependencies": { 
"@angular/http": "2.0.0-rc.1", 
"@angular/common": "2.0.0-rc.1", 
"@angular/compiler": "2.0.0-rc.1", 
"@angular/core": "2.0.0-rc.1", 
"@angular/platform-browser": "2.0.0-rc.1", 
"@angular/platform-browser-dynamic": "2.0.0-rc.1", 
"@angular/platform-server": "2.0.0-rc.1", 
"@angular/router": "2.0.0-rc.1", 
"@angular/router-deprecated": "2.0.0-rc.1", 
"core-js": "^2.3.0", 
"rxjs": "5.0.0-beta.7", 
"zone.js": "~0.6.12", 
"socket.io": "^1.4.6" 
}.... 

typings.json

...."ambientDependencies": { 
"socket.io-client": "registry:dt/socket.io-client#1.4.4+20160317120654",.... 

socket.ts

import {Component} from '@angular/core'; 
require ('socket.io-client/socket.io'); 

@Component({ 
    selector: 'socket', 
    templateUrl: 'app/components/socket/socket.html', 
    styleUrls: ['app/components/socket/socket.css'], 
}) 
export class SocketTest { 
socket = null; 

constructor() { 
    this.socket = io('http://localhost:3001'); 
    .... 

錯誤:

./~/socket.io-client/socket.io.js 
Critical dependencies: 
1:475-482 This seems to be a pre-built javascript file. Though this is  possible, it's not recommended. Try to require the original source to get better  results. 
@ ./~/socket.io-client/socket.io.js 1:475-482 
browser_adapter.js:86 EXCEPTION: Error: Uncaught (in promise): EXCEPTION:  Error in :0:0 
ORIGINAL EXCEPTION: ReferenceError: io is not defined 
ORIGINAL STACKTRACE: 
ReferenceError: io is not defined.... 

回答

4

在你webpack.config.js,添加socket.js作爲外部庫,所以它不會擠滿了您的JavaScript的休息,

當然,實際上你需要合併這些設置與你的角。

在您的index.html
external:{ 
    ... 
    'socket.io-client':'io' 
} 

resolve: { 
    alias: { 
     ... 
     'socket.io-client': path.join(__dirname, 'node_modules', 'socket.io-client', 'socket.io.js') 
    } 
}, 
module: { 
    ... 
    noParse: [ /socket.io-client/ ] 
} 

然後,包括

<script src="socket.io.js"></script> 

並要求其爲:

import {Component} from '@angular/core'; 
require ('io'); 

@Component({ 
    selector: 'socket', 
    templateUrl: 'app/components/socket/socket.html', 
    styleUrls: ['app/components/socket/socket.css'], 
}) 

附:我自己並沒有嘗試過這些設置,我只是想至少讓你走上正確的軌道。

相關問題