如何将 socket.io-client 与 webpack 捆绑在一起? [英] How can I bundle socket.io-client with webpack?
问题描述
我是 webpack 的新手,在将 socket.io-client 与 webpack 捆绑在一起时遇到了问题.有人可以告诉我我做错了什么吗?
I am new to webpack and having issues bundling socket.io-client with webpack. Can someone please tell me what I am doing wrong?
我使用的是 Angular 2 RC.1
I am using Angular 2 RC.1
package.json
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
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....
推荐答案
在您的 webpack.config.js 中,将 socket.js 添加为外部库,这样它就不会与您的 javascript 的其余部分打包在一起,
In your webpack.config.js, add socket.js as an external library so it doesn't get packed with the rest of your javascript,
当然,您需要将这些设置与您的角度设置实际合并.
Of course, you need to actually merge these settings with your angular ones.
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/ ]
}
然后在你的 index.html 中,包含
Then in your index.html, include
<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'],
})
附言我自己没有尝试过这些设置,我只是想至少让你走上正轨.
P.S. I haven't tried these settings myself, I just wanted to at least put you on the right track.
这篇关于如何将 socket.io-client 与 webpack 捆绑在一起?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!