如何在 WebStorm 2016.1 中使用 ng2-file-uploader?
How to use ng2-file-uploader with WebStorm 2016.1?
我必须在我的应用程序中使用 ng2-file-uploader。
我已经按照这个 Github project 但是发生了这个错误。
PS : 我是 Angular2 开发的新手。
I am using the latest version of webstorm (2016.1) and Typescript 1.8.2
ERROR in ./~/ng2-file-upload/components/file-upload/file-uploader.ts
Module parse failed: C:\Users\...\Desktop\FrontEndSkilify\skilify-front\node_modules\tslintloader\index.js!C:\Users\...\Desktop\FrontEndSkilify\skilify-front\node_modules\ng2-file-upload\components\file-upload\file-uploader.ts Line 1: Unexpected token
You may need an appropriate loader to handle this file type.
| import {FileLikeObject} from './file-like-object';
| import {FileItem} from './file-item';
|
@ ./~/ng2-file-upload/ng2-file-upload.js 6:9-58
这是我的代码:
demo.ts :
import {Component, NgZone} from 'angular2/core';
import {Http} from "angular2/http";
import {UPLOAD_DIRECTIVES} from 'ng2-uploader/ng2-uploader';
import {NgFileSelect} from 'ng2-uploader/src/directives/ng-file-select';
let styles = require('./demo.css')
let template = require('./demo.html');
@Component({
selector: 'demo',
template: template,
styles: [styles],
providers: [],
directives: [UPLOAD_DIRECTIVES,NgFileSelect],
pipes: []
})
export class Demo {
file:File;
zone: NgZone;
options: Object = {
url: 'http://ng2-uploader.com:10050/upload'
};
basicProgress: number = 0;
basicResp: Object;
multipleProgress: number = 0;
multipleResp: any[] = [];
dropProgress: number = 0;
dropResp: any[] = [];
response : string;
constructor(public http: Http){
this.zone = new NgZone({ enableLongStackTrace: false });
}
handleBasicUpload(data): void {
this.basicResp = data;
this.zone.run(() => {
this.basicProgress = data.progress.percent;
});
/* return this.http.post(API + '/api/upload',JSON.stringify(name),{ headers: contentHeaders })
.subscribe(res => {console.log(res)},
error=>{this.response = error.text()}
);*/
}
}
我的demo.html:
<div class="columns">
<div class="column is-4">
<div class="message is-danger">
<div class="message-header">Basic Example</div>
<div class="message-body">
<div class="content">
<label class="tag btn is-danger">
<i class="fa fa-upload icon is-small"></i> Choose file
<input type="file" [ng-file-select]="options" (onUpload)="handleBasicUpload($event)">
</label>
<div class="progress">
<div class="progress-bar" [style.width]="basicProgress + '%'"></div>
<span class="percent">{{ basicProgress }}%</span>
</div>
</div>
</div>
</div>
</div>
<div class="message resp">
<div class="message-header">Response</div>
<div class="message-body">
<p>
{{ basicResp | json }}
</p>
</div>
</div>
</div>
我的webpack.js;
var sliceArgs = Function.prototype.call.bind(Array.prototype.slice);
var toString = Function.prototype.call.bind(Object.prototype.toString);
var path = require('path');
var webpack = require('webpack');
// Webpack Plugins
var CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin;
module.exports = {
devtool: 'source-map',
// devtool: 'eval',
//
entry: {
'vendor': [
// Polyfills
'es6-shim',
'es6-promise',
'reflect-metadata',
'zone.js/dist/zone-microtask',
'zone.js/dist/long-stack-trace-zone',
// Angular2
'angular2/platform/browser',
'angular2/platform/common_dom',
'angular2/core',
'angular2/router',
'angular2/http',
// RxJS
'rxjs',
// Other
'angular2-jwt'
],
'app': [
'./src/index'
]
},
// Config for our build files
output: {
path: root('build'),
filename: '[name].js',
// filename: '[name].[hash].js',
sourceMapFilename: '[name].js.map',
chunkFilename: '[id].chunk.js'
// publicPath: 'http://mycdn.com/'
},
resolve: {
root: __dirname,
extensions: [
'',
'.ts',
'.js',
'.json',
'.css',
'.html'
]
},
module: {
preLoaders: [ { test: /\.ts$/, loader: 'tslint-loader' } ],
loaders: [
// Support for .ts files.
{
test: /\.ts$/,
loader: 'ts-loader',
query: {
'ignoreDiagnostics': [
2403, // 2403 -> Subsequent variable declarations
2300, // 2300 Duplicate identifier
2374, // 2374 -> Duplicate number index signature
2375 // 2375 -> Duplicate string index signature
]
},
exclude: [ /\.spec\.ts$/, /\.e2e\.ts$/, /node_modules/ ]
},
// Support for *.json files.
{ test: /\.json$/, loader: 'json-loader' },
// Support for CSS as raw text
{ test: /\.css$/, loader: 'raw-loader' },
// support for .html as raw text
{ test: /\.html$/, loader: 'raw-loader' },
],
noParse: [
/zone\.js\/dist\/.+/,
/reflect-metadata/,
/es(6|7)-.+/,
]
},
plugins: [
new CommonsChunkPlugin({ name: 'vendor', filename: 'vendor.js', minChunks: Infinity }),
new CommonsChunkPlugin({ name: 'common', filename: 'common.js', minChunks: 2, chunks: ['app', 'vendor'] })
],
// Other module loader config
tslint: {
emitErrors: false,
failOnHint: false
},
// our Development Server configs
// our Webpack Development Server config
devServer: {
historyApiFallback: true,
publicPath: '/build'
}
};
function getBanner() {
return 'This is a sample that shows how to add authentication to an Angular 2 (ng2) app by @auth0';
}
function root(args) {
args = sliceArgs(arguments, 0);
return path.join.apply(path, [__dirname].concat(args));
}
function rootNode(args) {
args = sliceArgs(arguments, 0);
return root.apply(path, ['node_modules'].concat(args));
}
我的 NgFileSelect :
import {Directive, ElementRef, EventEmitter} from 'angular2/core';
import {Ng2Uploader} from '../services/ng2-uploader';
@Directive({
selector: '[ng-file-select]',
inputs: ['options: ng-file-select'],
outputs: ['onUpload'],
host: {'(change)': 'onFiles()'},
})
export class NgFileSelect {
uploader:Ng2Uploader;
options:any;
onUpload:EventEmitter<any> = new EventEmitter();
constructor(public el:ElementRef) {
this.uploader = new Ng2Uploader();
setTimeout(() => {
this.uploader.setOptions(this.options);
});
this.uploader._emitter.subscribe((data) => {
this.onUpload.emit(data);
});
}
onFiles():void {
let files = this.el.nativeElement.files;
if (files.length) {
this.uploader.addFilesToQueue(files);
}
}
}
您的项目不理解打字稿 (.ts) 文件 - 至少这是错误抱怨。
您是否为您的项目正确设置了打字稿?您可以使用您的 WebStorm IDE 激活它,只需进入设置 - 搜索打字稿并启用它。但是 IDE 打字稿支持的问题是,只有您积极处理的文件才会被编译。
那么你的构建脚本..呢?你使用 webpack 或 browserify 还是 system.js 来构建你的项目?我建议从一个不错的种子项目开始,它已经为您设置了所有这些,例如:https://github.com/AngularClass/angular2-webpack-starter
一个如何与 webpack 一起设置 typescript 工作流的例子:
http://www.jbrantly.com/typescript-and-webpack/
基本上:
- 为您的项目设置 webpack
- 为您的项目设置 typescript npm 模块和 tsconfig.json
- 为您的 webpack 配置包含 tsloader 部分
享受 运行可行的 typescript/ng2 项目 ;)
更新
现在提供了你的代码。我想知道你的 ts-loader 定义在这个查询中做了什么......我几乎不记得当你提供 "query" 参数时,它只会选择向上定义的内容.. 如果你删除它,他将拾取与 "test" 参数匹配的所有内容,除了它与排除正则表达式匹配。
我用的这个就简单多了:
{test: /\.ts$/, loader: 'ts-loader', exclude: [/\.(spec|e2e)\.ts$/]},
并挑选项目中所有不以 *.spec.ts 或 *.e2e.ts 结尾的 .ts 文件 - 尝试一次..如果错误仍然存在,我有运行 我自己对这段代码进行更深入的研究..
我必须在我的应用程序中使用 ng2-file-uploader。 我已经按照这个 Github project 但是发生了这个错误。
PS : 我是 Angular2 开发的新手。
I am using the latest version of webstorm (2016.1) and Typescript 1.8.2
ERROR in ./~/ng2-file-upload/components/file-upload/file-uploader.ts
Module parse failed: C:\Users\...\Desktop\FrontEndSkilify\skilify-front\node_modules\tslintloader\index.js!C:\Users\...\Desktop\FrontEndSkilify\skilify-front\node_modules\ng2-file-upload\components\file-upload\file-uploader.ts Line 1: Unexpected token
You may need an appropriate loader to handle this file type.
| import {FileLikeObject} from './file-like-object';
| import {FileItem} from './file-item';
|
@ ./~/ng2-file-upload/ng2-file-upload.js 6:9-58
这是我的代码:
demo.ts :
import {Component, NgZone} from 'angular2/core';
import {Http} from "angular2/http";
import {UPLOAD_DIRECTIVES} from 'ng2-uploader/ng2-uploader';
import {NgFileSelect} from 'ng2-uploader/src/directives/ng-file-select';
let styles = require('./demo.css')
let template = require('./demo.html');
@Component({
selector: 'demo',
template: template,
styles: [styles],
providers: [],
directives: [UPLOAD_DIRECTIVES,NgFileSelect],
pipes: []
})
export class Demo {
file:File;
zone: NgZone;
options: Object = {
url: 'http://ng2-uploader.com:10050/upload'
};
basicProgress: number = 0;
basicResp: Object;
multipleProgress: number = 0;
multipleResp: any[] = [];
dropProgress: number = 0;
dropResp: any[] = [];
response : string;
constructor(public http: Http){
this.zone = new NgZone({ enableLongStackTrace: false });
}
handleBasicUpload(data): void {
this.basicResp = data;
this.zone.run(() => {
this.basicProgress = data.progress.percent;
});
/* return this.http.post(API + '/api/upload',JSON.stringify(name),{ headers: contentHeaders })
.subscribe(res => {console.log(res)},
error=>{this.response = error.text()}
);*/
}
}
我的demo.html:
<div class="columns">
<div class="column is-4">
<div class="message is-danger">
<div class="message-header">Basic Example</div>
<div class="message-body">
<div class="content">
<label class="tag btn is-danger">
<i class="fa fa-upload icon is-small"></i> Choose file
<input type="file" [ng-file-select]="options" (onUpload)="handleBasicUpload($event)">
</label>
<div class="progress">
<div class="progress-bar" [style.width]="basicProgress + '%'"></div>
<span class="percent">{{ basicProgress }}%</span>
</div>
</div>
</div>
</div>
</div>
<div class="message resp">
<div class="message-header">Response</div>
<div class="message-body">
<p>
{{ basicResp | json }}
</p>
</div>
</div>
</div>
我的webpack.js;
var sliceArgs = Function.prototype.call.bind(Array.prototype.slice);
var toString = Function.prototype.call.bind(Object.prototype.toString);
var path = require('path');
var webpack = require('webpack');
// Webpack Plugins
var CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin;
module.exports = {
devtool: 'source-map',
// devtool: 'eval',
//
entry: {
'vendor': [
// Polyfills
'es6-shim',
'es6-promise',
'reflect-metadata',
'zone.js/dist/zone-microtask',
'zone.js/dist/long-stack-trace-zone',
// Angular2
'angular2/platform/browser',
'angular2/platform/common_dom',
'angular2/core',
'angular2/router',
'angular2/http',
// RxJS
'rxjs',
// Other
'angular2-jwt'
],
'app': [
'./src/index'
]
},
// Config for our build files
output: {
path: root('build'),
filename: '[name].js',
// filename: '[name].[hash].js',
sourceMapFilename: '[name].js.map',
chunkFilename: '[id].chunk.js'
// publicPath: 'http://mycdn.com/'
},
resolve: {
root: __dirname,
extensions: [
'',
'.ts',
'.js',
'.json',
'.css',
'.html'
]
},
module: {
preLoaders: [ { test: /\.ts$/, loader: 'tslint-loader' } ],
loaders: [
// Support for .ts files.
{
test: /\.ts$/,
loader: 'ts-loader',
query: {
'ignoreDiagnostics': [
2403, // 2403 -> Subsequent variable declarations
2300, // 2300 Duplicate identifier
2374, // 2374 -> Duplicate number index signature
2375 // 2375 -> Duplicate string index signature
]
},
exclude: [ /\.spec\.ts$/, /\.e2e\.ts$/, /node_modules/ ]
},
// Support for *.json files.
{ test: /\.json$/, loader: 'json-loader' },
// Support for CSS as raw text
{ test: /\.css$/, loader: 'raw-loader' },
// support for .html as raw text
{ test: /\.html$/, loader: 'raw-loader' },
],
noParse: [
/zone\.js\/dist\/.+/,
/reflect-metadata/,
/es(6|7)-.+/,
]
},
plugins: [
new CommonsChunkPlugin({ name: 'vendor', filename: 'vendor.js', minChunks: Infinity }),
new CommonsChunkPlugin({ name: 'common', filename: 'common.js', minChunks: 2, chunks: ['app', 'vendor'] })
],
// Other module loader config
tslint: {
emitErrors: false,
failOnHint: false
},
// our Development Server configs
// our Webpack Development Server config
devServer: {
historyApiFallback: true,
publicPath: '/build'
}
};
function getBanner() {
return 'This is a sample that shows how to add authentication to an Angular 2 (ng2) app by @auth0';
}
function root(args) {
args = sliceArgs(arguments, 0);
return path.join.apply(path, [__dirname].concat(args));
}
function rootNode(args) {
args = sliceArgs(arguments, 0);
return root.apply(path, ['node_modules'].concat(args));
}
我的 NgFileSelect :
import {Directive, ElementRef, EventEmitter} from 'angular2/core';
import {Ng2Uploader} from '../services/ng2-uploader';
@Directive({
selector: '[ng-file-select]',
inputs: ['options: ng-file-select'],
outputs: ['onUpload'],
host: {'(change)': 'onFiles()'},
})
export class NgFileSelect {
uploader:Ng2Uploader;
options:any;
onUpload:EventEmitter<any> = new EventEmitter();
constructor(public el:ElementRef) {
this.uploader = new Ng2Uploader();
setTimeout(() => {
this.uploader.setOptions(this.options);
});
this.uploader._emitter.subscribe((data) => {
this.onUpload.emit(data);
});
}
onFiles():void {
let files = this.el.nativeElement.files;
if (files.length) {
this.uploader.addFilesToQueue(files);
}
}
}
您的项目不理解打字稿 (.ts) 文件 - 至少这是错误抱怨。
您是否为您的项目正确设置了打字稿?您可以使用您的 WebStorm IDE 激活它,只需进入设置 - 搜索打字稿并启用它。但是 IDE 打字稿支持的问题是,只有您积极处理的文件才会被编译。
那么你的构建脚本..呢?你使用 webpack 或 browserify 还是 system.js 来构建你的项目?我建议从一个不错的种子项目开始,它已经为您设置了所有这些,例如:https://github.com/AngularClass/angular2-webpack-starter
一个如何与 webpack 一起设置 typescript 工作流的例子: http://www.jbrantly.com/typescript-and-webpack/
基本上:
- 为您的项目设置 webpack
- 为您的项目设置 typescript npm 模块和 tsconfig.json
- 为您的 webpack 配置包含 tsloader 部分
享受 运行可行的 typescript/ng2 项目 ;)
更新
现在提供了你的代码。我想知道你的 ts-loader 定义在这个查询中做了什么......我几乎不记得当你提供 "query" 参数时,它只会选择向上定义的内容.. 如果你删除它,他将拾取与 "test" 参数匹配的所有内容,除了它与排除正则表达式匹配。
我用的这个就简单多了:
{test: /\.ts$/, loader: 'ts-loader', exclude: [/\.(spec|e2e)\.ts$/]},
并挑选项目中所有不以 *.spec.ts 或 *.e2e.ts 结尾的 .ts 文件 - 尝试一次..如果错误仍然存在,我有运行 我自己对这段代码进行更深入的研究..