Tips for integrating ng2-file-uploader with WebStorm version 2016.1

I am implementing the ng2-file-uploader in my application. I have referred to this Github project but encountered an error.

Note: I am new to Angular2 development.

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

Below is my code :

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()}

         );*/

    }

}

my 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>

my 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));
}

My 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.eplouader._emitter.subscribe((data) => {
this.onUpload.emit(data);
});
}

onFiles():void {
let files = this.el.nativeElement.files;
if (files.length) {
this.uploader.addFilesToQueue(files);
}
}

}

Answer №1

It seems like your project is having trouble understanding typescript (.ts) files.

If you haven't already, make sure to set up typescript correctly for your project. You can do this in WebStorm IDE by going into settings and enabling typescript. However, keep in mind that the IDE's typescript support only compiles files that you are actively working on.

Also, check your build script. Are you using webpack, browserify, or system.js to build your project? Starting with a seed project that has everything set up for you can be helpful. For example, you can find a good starting point at https://github.com/AngularClass/angular2-webpack-starter

For an example of setting up typescript workflow with webpack, you can refer to

Here's a basic outline:

  • Set up webpack for your project
  • Add typescript npm module and tsconfig.json
  • Include the tsloader part in your webpack config

Enjoy working on your runnable typescript/ng2 project! ;)

Update

After looking at your provided code, it seems like the query in your ts-loader definition might be causing issues. Removing the query parameter should make it pick up all .ts files except those ending with *.spec.ts or *.e2e.ts. Here's a simpler version I am using:

{test: /\.ts$/, loader: 'ts-loader', exclude: [/\.(spec|e2e)\.ts$/]},

Try this out and if the error persists, feel free to reach out for further investigation.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Advanced type generics in Typescript

I've hit a roadblock in my attempt to ensure type safety for a function that should take an object and return a number. Despite numerous efforts, I haven't been successful. To give you a simple example (the actual application involves more comple ...

I am encountering a TypeScript error with URLSearchParams. The object cannot be successfully converted to a string using the toString() method

During the development of my react app with postgres, express, node, and typescript, I ran into an issue while working on the backend code. The problem arises when trying to utilize URLSearchParams. index.js import express from 'express'; import ...

Can social login be used to add Firebase users to the user database?

When a user logs in through a social provider like Facebook, does Firebase automatically include them in the Firebase Authentication/User database? In simpler terms, if Christine signs in with Facebook, will Firebase save her Email address, first name, et ...

Material UI Error TS1128: Expected declaration or statement for ButtonUnstyledProps

While working on my application that utilizes Material UI, I encountered an issue. I keep receiving a Typescript error and haven't been able to find a solution for it. TypeScript error in C:/.../node_modules/@mui/base/ButtonUnstyled/index.d.ts(3,1): D ...

Facebook is failing to detect meta tags for Angular Universal

I am facing an issue where the meta tags are not showing up on my article pages for Facebook sharing, despite using Angular Universal with Server-side rendering. Although Google Indexing is working fine and the meta tags are visible in the page source, the ...

Adding the "unsafe" keyword before the URL in the href attribute ensures that potentially harmful URLs are

When attempting to launch an app, everything goes smoothly with a static URL. However, when using a dynamic href tag in *ngFor, the URL is modified by adding an unsafe keyword which causes it to fail. Currently operating on Angular 6, I am retrieving an I ...

Encountering an error in Angular where the property 'nativeElement' is undefined when using @ViewChild

I have a div in my code named #map that will be displayed after a certain condition is met in a for loop. <div *ngFor="let message of fullMessagesArr"> <div *ngIf="message.replyMap"> <div #gmap style="width:100px;height:400px"></d ...

Concealing the BottomNavigation bar in Nativescript

Currently using Nativescript 7+ and seeking to implement a feature where the TabStrip can be hidden on certain pages post navigation. Below is the relevant section of my .html code. <BottomNavigation id="bottomNav"> <TabStrip> ...

Guide on creating a Meteor Bootstrap WhatsApp clone

I'm currently going through the step-by-step guide for Whatsapp on the following website: After entering this command: meteor npm install angular@^1.5.8 --save I encountered the following message: no matches found: angular@^1.5.8 Does this mean t ...

Angular4 Datatable Integration with Firebase

Issue encountered with Datatable, Angular 4, and Firebase I suspect the problem lies in the usage of | async as it is not generating a valid JSON object. HTML Markup <tr *ngFor="let item of items | async; let i = index"> <th scope="row">{ ...

What is the best way to focus on a particular version of TypeScript?

After upgrading my Angular 2 project to RC1 and the router to v3 alpha3, I encountered the following errors: node_modules/@angular/router/directives/router_outlet.d.ts(10,14): error TS1005: '=' expected. It appears to be a TypeScript version is ...

What is the best way to dynamically adjust the width of multiple divisions in Angular?

I am currently working on an angular project to create a sorting visualizer. My goal is to generate a visual representation of an array consisting of random numbers displayed as bars using divisions. Each bar's width will correspond to the value of th ...

A guide on structuring connected properties in Typescript

I possess a collection of interrelated attributes: A = B * C B = A / C C = A / B A, B, and C are all intrinsic to my model, implying the existence of a function that takes an incomplete model lacking one attribute and generates a complete model with a ...

Combine identical arrays of object keys into one unified array

https://i.sstatic.net/A2r5c.png I am striving for this particular output [ productId:106290, productserialno:[{ "12121", "212121" }] ] ...

Deploying a Typescript node application using pm2 for process management

When it comes to deploying a node app written in typescript using pm2, the process can be a bit tricky. The source code is typically stored on a git repository, with the remote machine having an ssh connection to git. The standard workflow for deployment ...

Angular Material Datatables - Issue with Paginating Data from Firestore

Data has been retrieved from Firestore and transformed into an Observable array with the InvoiceItem type. The data loads correctly onto the datatable, but there seems to be an issue initializing the paginator with the array's length. This could poss ...

Utilize an embedded Angular project to access a property file within a Spring Boot application

Currently, I am working on a project where Angular 6 is embedded within a Spring Boot application. Everything is running smoothly so far and the index.html file for my Angular app is located in the resources folder of the Spring Boot application. I am no ...

Angular's ng serve is experiencing issues with mark-compacts near the heap limit, leading to an unsuccessful allocation

Encountering an issue while running ng serve in my Angular project. However, ng build --prod seems to be working fine. <--- Last few GCs ---> [4916:00000276B1C57010] 588109 ms: Scavenge (reduce) 8180.7 (8204.3) -> 8180.6 (8205.1) MB, 3 ...

Error in Angular 7 Reactive Forms: "No value accessor available for form control without a specified name attribute"

I'm encountering issues with some form fields while using reactive forms in Angular. Any insights on why this might be happening would be greatly appreciated. Just started working with Angular and Material 7, if that's relevant. An interesting ...

What is the reason behind TypeScript classifying the argument type from the function as 'never'?

Presented here is the combined type of two signatures for the filter function and the function itself. type Filter = { (arr: string[], f: (item: string) => boolean): string[] (arr: number[], f: (item: number) => boolean): number[] } let filter: ...