2017-02-13 5 views
0

Прежде всего - спасибо за помощь! Я создал веб-приложение, используя Angular 2, и я нахожусь в финальном процессе запуска в производство, но я испытываю ошибку в связке с Gulp. Кажется, что существует много документации вокруг конкретного Typeerror, который я испытываю, но ничего, что я видел, действительно соответствует моему варианту использования и позиции в этом процессе.Uncaught Typeerror в комплекте с кодом для углового 2 с помощью Gulp

В частности, сам сам процесс комплектации не возвращает никаких ошибок при выполнении следующей команды:

sudo gulp 

Однако при проверке, может ли код работать на моем локальном хосте, возвращается следующее сообщение об ошибке:

Uncaught TypeError: Cannot read property 'prototype' of undefined 

и файл, на который ссылается эта ошибка, - это app.min.js, который является выходным файлом моего полностью связанного кода.

После отладки проблемы дальше, из того, что я могу сказать, есть потенциальная некоторая отключаемость в том, как модули оцениваются, но я не могу показать большой корень причины проблемы или решение проблемы вопрос. Вот где я мог бы использовать помощь сообщества - выяснить, как решить проблему, когда «прототип» не может быть прочитан.

gulpfile.js:

const gulp = require('gulp'); 
const del = require('del'); 
const cleanCSS = require('gulp-clean-css'); 
const concat = require('gulp-concat'); 
const liveServer = require('gulp-live-server'); 
const plumber = require('gulp-plumber'); 
const runSequence = require('run-sequence'); 
const sass = require('gulp-sass'); 
const sourcemaps = require('gulp-sourcemaps'); 
const sysBuilder = require('systemjs-builder'); 
const tslint = require('gulp-tslint'); 
const tsc = require('gulp-typescript'); 
const uglify = require('gulp-uglify'); 
const tsconfig = require('tsconfig-glob'); 

const tscConfig = require('./tsconfig.json') 

// Development 

gulp.task("devmin", function() { 
    return gulp.src([ 
     'wwwroot/js/jquery.js', 
     'node_modules/core-js/client/shim.js', 
     'node_modules/zone.js/dist/zone.js', 
     'node_modules/reflect-metadata/Reflect.js', 
     'wwwroot/js/toastr.js', 
     'wwwroot/js/moment.js', 
     'wwwroot/js/typescript.js', 
    ]) 
    .pipe(concat('site.min.js')) 
    .pipe(uglify()) 
    .pipe(gulp.dest('wwwroot/js')); 
}); 

// Clean the distribution directory 

gulp.task('clean:dist', function() { 
    return del('wwwroot/dist/*'); 
}); 

// Clean the JavaScript distribution directory 

gulp.task('clean:dist:js', function() { 
    return del('wwwroot/dist/js/*'); 
}); 

// Clean the CSS Distribution directory 

gulp.task('clean:dist:css', function() { 
    return del('wwwroot/dist/css/*'); 
}); 

// Clean library directory 

gulp.task('clean:lib', function() { 
    return del('wwwroot/lib/**/*'); 
}); 

// Compile TypeScript to JS 

gulp.task('compile:ts', function() { 
    return gulp 
    .src(tscConfig.filesGlob) 
    .pipe(plumber({ 
     errorHandler: function (err) { 
     console.error('>>> [tsc] Typescript compilation failed'.bold.green); 
     this.emit('end'); 
     }})) 
    .pipe(sourcemaps.init()) 
    .pipe(tsc(tscConfig.compilerOptions)) 
    .pipe(sourcemaps.write('.')) 
    .pipe(gulp.dest('wwwroot/dist/app')); 
}); 

// Generate SystemJS-based builds 

gulp.task('bundle:js', function() { 
    var builder = new sysBuilder('wwwroot', 'wwwroot/systemjs.config.js'); 
     console.log("-----------------------------Start"); 
    return builder.buildStatic('app', 'wwwroot/dist/js/app.min.js') 
    .then(function() { 
     console.log("-----------------------------Deleting"); 
     return del(['wwwroot/dist/js/**/*', '!wwwroot/dist/js/app.min.js']); 
    }) 
    .catch(function(err) { 
     console.error('>>> [systemjs-builder] Bundling failed'.bold.green, err); 
    }); 
}); 

// Minify JS bundle 

gulp.task('minify:js', function() { 
    return gulp 
    .src('wwwroot/dist/js/app.min.js') 
    .pipe(uglify()) 
    .pipe(gulp.dest('wwwroot/dist/js')); 
}); 

gulp.task('compile:sass', function() { 
    // concat and minify global scss files 
    gulp 
     .src('wwwroot/css/global/*.scss') 
     .pipe(plumber({ 
      errorHandler: function (err) { 
       console.error('>>> [sass] Sass global style compilation failed'.bold.green); 
       this.emit('end'); 
      }})) 
     .pipe(sourcemaps.init()) 
     .pipe(sass({ errLogToConsole: true })) 
     .pipe(concat('styles.min.css')) 
     // .pipe(cleanCSS()) 
     .pipe(sourcemaps.write()) 
     .pipe(gulp.dest('wwwroot/dist/css/global')); 

    // minify component specific scss files 

    gulp 
     .src('wwwroot/css/*.scss') 
     .pipe(plumber({ 
      errorHandler: function (err) { 
       console.error('>>> [sass] Sass component style compilation failed'.bold.green); 
       this.emit('end'); 
      }})) 
     .pipe(sourcemaps.init()) 
     .pipe(sass({ errLogToConsole: true })) 
     // .pipe(cleanCSS()) 
     .pipe(sourcemaps.write()) 
     .pipe(gulp.dest('wwwroot/dist/css/component')); 
}); 

// Concat and minify CSS 

gulp.task('minify:css', function() { 
    // concat and minify global css files 
    gulp 
    .src('wwwroot/css/*.css') 
    .pipe(concat('styles.min.css')) 
    .pipe(cleanCSS()) 
    .pipe(gulp.dest('wwwroot/dist/css')); 

     // minify component css files 

    gulp 
    .src('wwwroot/css/component/*.css') 
    .pipe(cleanCSS()) 
    .pipe(gulp.dest('wwwroot/dist/css/component')); 
}); 

// Copy dependencies 

gulp.task('copy:libs', function() { 
    gulp.src([ 
     'node_modules/rxjs/**/*' 
    ]) 
    .pipe(gulp.dest('wwwroot/lib/js/rxjs')); 

    gulp.src([ 
     './node_modules/reflect-metadata/Reflect.js', 
     './node_modules/zone.js/dist/zone.js', 
     './node_modules/core-js/client/shim.js', 
     '.node_modules/systemjs/dist/system.src.js', 
     './node_modules/bootstrap/dist/js/bootstrap.js', 
     './node_modules/jquery/dist/jquery.js', 
     './node_modules/moment/moment.js', 
     './node_modules/es6-promise/dist/es6-promise.js', 
     './node_modules/typescript/lib/typescript.js', 
     './node_modules/systemjs/dist/system.src.js', 
     './node_modules/toastr/package/toastr.js' 
    ]) 
    .pipe(gulp.dest('wwwroot/lib/js')); 

    gulp.src([ 
     './node_modules/jquery/dist/jquery.min.js', 
     './node_modules/bootstrap/dist/js/bootstrap.min.js', 
     './node_modules/es6-promise/dist/es6-promise.min.js', 
     './node_modules/toastr/toastr.js', 
     './node_modules/moment/min/moment.min.js', 
     './node_modules/angular-in-memory-web-api/dist/index.js', 
     './wwwroot/systemjs.config.js' 
    ]) 

    .pipe(concat('vendors.min.js')) 
    .pipe(uglify()) 
    .pipe(gulp.dest('wwwroot/lib/js')); 

     // copy source maps 
    gulp.src([ 
     './node_modules/es6-shim/es6-shim.map', 
     './node_modules/reflect-metadata/Reflect.js.map', 
     './node_modules/systemjs/dist/system-polyfills.js.map' 
    ]).pipe(gulp.dest('wwwroot/lib/js')); 

    gulp.src([ 
     '.node_modules/bootstrap/dist/css/bootstrap.*', 
     './node_modules/bootstrap-toggle/css/bootstrap-toggle.css', 
     './node_modules/bootstrap/dist/css/bootstrap-theme.css', 
     './node_modules/bootstrap/dist/css/bootstrap-theme.css.map', 
     './node_modules/bootstrap-social/bootstrap-social.css', 
     './node_modules/font-awesome/css/font-awesome.css.map', 
     './node_modules/font-awesome/css/font-awesome.css', 
     './node_modules/glyphicons-halflings/css/glyphicons-halflings.css.map', 
     './node_modules/glyphicons-halflings/css/glyphicons-halflings.css', 
     './node_modules/toastr/package/toastr.css', 
     './node_modules/toastr/package/toastr.css', 
    ]).pipe(gulp.dest('wwwroot/lib/css')); 


    gulp.src([ 
     "./node_modules/font-awesome/fonts/FontAwesome.otf", 
     "./node_modules/font-awesome/fonts/fontawesome-webfont.eot", 
     "./node_modules/font-awesome/fonts/fontawesome-webfont.svg", 
     "./node_modules/font-awesome/fonts/fontawesome-webfont.ttf", 
     "./node_modules/font-awesome/fonts/fontawesome-webfont.woff", 
     "./node_modules/font-awesome/fonts/fontawesome-webfont.woff2", 
     "./node_modules/bootstrap/fonts/glyphicons-halflings-regular.eot", 
     "./node_modules/bootstrap/fonts/glyphicons-halflings-regular.svg", 
     "./node_modules/bootstrap/fonts/glyphicons-halflings-regular.ttf", 
     "./node_modules/bootstrap/fonts/glyphicons-halflings-regular.woff", 
     "./node_modules/bootstrap/fonts/glyphicons-halflings-regular.woff2" 
    ]).pipe(gulp.dest('wwwroot/dist/fonts')); 

    gulp.src(['./node_modules/angular-in-memory-web-api/**/*']).pipe(gulp.dest('wwwroot/lib/js/angular-in-memory-web-api')); 

    // handle all angular 

    return gulp.src(['node_modules/@angular/**/*']) 
     .pipe(gulp.dest('wwwroot/lib/js/@angular')); 
}); 

// Copy static assets 

gulp.task('copy:assets', function() { 
    return gulp.src(
     [ 
      '*.json', 
      '*.html', 
      '*.css', 
      '!*.ts', 
      '!*.scss' 
     ], 
      { base: '' }) 
      .pipe(gulp.dest('wwwroot/dist')) 
}); 

// Update the tsconfig files based on the glob pattern 

gulp.task('tsconfig-glob', function() { 
    return tsconfig({ 
     configPath: '.', 
     indent: 2 
    }); 
}); 

// Watch the source files for changes, then trigger recompilation 

gulp.task('watch:src', function() { 
    // gulp.watch('src/**/*.ts', ['scripts']); 
    // gulp.watch('src/**/*.scss', ['styles']); 
    gulp.watch('./**/*.ts', ['scripts']); 
    gulp.watch('./**/*.scss', ['styles']); 
}); 

gulp.task('test', ['compile:specs'], function() { 
    // gulp.watch('src/**/*.ts', ['compile:specs']); 
    gulp.watch('./**/*.ts', ['compile:specs']); 
}); 

gulp.task('lint', ['lint:sass']); 

// gulp.task('clean', ['clean:dist:js', 'clean:dist:css', 'clean:lib']); 

gulp.task('copy', function(callback) { 
// runSequence('clean:lib', 'copy:libs', callback); 
    runSequence('copy:libs', callback); 
}); 

gulp.task('scripts', function(callback) { 
    // runSequence(['clean:dist:js'], 'compile:ts', 'bundle:js', 'minify:js', callback); 
    runSequence('compile:ts', 'bundle:js', 'minify:js', callback); 
}); 

gulp.task('styles', function(callback) { 
// runSequence(['clean:dist:css'], ['compile:sass', 'minify:css'], callback); 
    runSequence(['compile:sass', 'minify:css'], callback); 
}); 

gulp.task('build', function(callback) { 
    runSequence('copy', 'scripts', 'styles', callback); 
}); 

gulp.task('buildnocopy', function(callback) { 
    runSequence('scripts', 'styles', callback); 
}); 

gulp.task('default', function(callback) { 
    runSequence('build', callback); 
}); 

systemjs.config.js:

// map tells the System loader where to look for things 
var map = { 
    'app': 'dist/app', 
    'rxjs': 'lib/js/rxjs', 
    '@angular': 'lib/js/@angular', 
    'zone.js': 'lib/js/zone.js', 
    'moment': 'lib/js/moment', 
    'angular-in-memory-web-api': 'lib/js/angular-in-memory-web-api', 
    'typescript': 'lib/js/typescript', 
}; 

// packages tells the System loader how to load when no filename and/or no extension 
var packages = { 
    'app': { main: 'main', defaultExtension: 'js' }, 
    'rxjs': { defaultExtension: 'js' }, 
    'zone.js': { main: 'zone', defaultExtension: 'js' }, 
    'symbol-observable': { main: 'index.js', defaultExtension: 'js' }, 
    'angular-localstorage': { defaultExtension: "js"}, 
    "angular-in-memory-web-api": { main: "index.js", defaultExtension: "js" }, 
    'moment': { defaultExtension: 'js' } 
}; 

var packageNames = [ 
    '@angular/common', 
    '@angular/compiler', 
    '@angular/core', 
    '@angular/forms', 
    '@angular/http', 
    '@angular/platform-browser', 
    '@angular/platform-browser-dynamic', 
    '@angular/router', 
    '@angular/testing', 
    '@angular/upgrade', 
]; 

// add package entries for angular packages in the form '@angular/common': { main: 'index.js', defaultExtension: 'js' } 
packageNames.forEach(function(pkgName) { 
    packages[pkgName] = { main: 'index.js', defaultExtension: 'js' }; 
}); 

System.config({  
    map: map, 
    packages: packages 
}); 

tsconfig.json:

{ 
    "compileOnSave": true, 
    "compilerOptions": { 
    "emitDecoratorMetadata": true, 
    "experimentalDecorators": true, 
    "removeComments": true, 
    "module": "system", 
    "moduleResolution": "node", 
    "rootDir": "wwwroot", 
    "outDir": "wwwroot/dist", 
    "sourceMap": true, 
    "target": "ES5", 
    "noImplicitAny": false, 
    "noEmitOnError": true, 
    "suppressImplicitAnyIndexErrors": true 
    }, 
    "exclude": [ 
    "wwwroot/node_modules", 
    "node_modules", 
    "typings", 
    "wwwroot/lib" 
    ], 
    "filesGlob": [ 
    "wwwroot/app/**/**/*.ts", 
    "typings/*.d.ts" 
    ] 
} 

Пожалуйста, дайте мне знать, если мне нужно предоставить больше документация. Благодаря!

+0

прототип не является функцией –

+0

Да, это правильно – durham989

ответ

0

Я знаю, что была точка, в которой была нарушена минификация/уклонение углового 2 с помощью gulp-uuglify.

Попробуйте удалить шаг uglify и посмотрите, поможет ли это вашему делу.

+0

Удивительно, спасибо за понимание! Поэтому я просто удалил часть uglification, и хотя это не устранило typeerror, что-то мне пришло в голову. Может ли это иметь какое-то отношение к тому факту, что некоторые из моих услуг являются расширением базовой службы, которую я использую? – durham989

+0

Хм ... теоретически это не должно быть проблемой, о которой я знаю ... но вы могли бы попытаться удалить ссылки на них и посмотреть, получится ли это. – chrispy

+0

Да, правда, на данный момент я просто пытаюсь уложить свой мозг, чтобы попробовать что-то, чего я еще не сделал. Я просто удалил расширения и ничего не изменил, но стоит сделать снимок! – durham989