2017-11-27 161 views
5

Czy ktoś może mi pomóc w tej sprawie 1 na 2?Bezwzględne lub względne "templateUrls" dla elementów kątowych

1) Projekt kątowy jako AoT w produkcji. Wymagało to zmiany mojego kodu źródłowego tak, aby szablony styleUrl i styleUrls były względne do pliku component.ts.

2) Karma kątowa jako JiT do testów jednostkowych. Wymagało to zmiany mojego kodu źródłowego, tak aby szablon templateUrl i styleUrls był absolutny, lub test jednostki wyrzuci 404 plik .html.

Chciałbym uniknąć zachowania względnej i bezwzględnej ścieżki w kodzie źródłowym.

Jakie są moje opcje? Jaka jest najlepsza praktyka?

(używam WebPACK z AOT i karmę, a nie kanciaste-CLI)

Dzięki !!

AKTUALIZACJA: zamierzamy również odkryć konwersję na kanciastą-cli, ale jest to ogromny projekt i jest to blokowanie dla nas, jeśli ktoś zna sztuczkę używaną przez kąt-cli, aby ją ściągnąć . lub nawet obejście, abyśmy mogli odzyskać nasze testy jednostkowe!

muszę wiedzieć trick aby uruchomić testy jednostka z AOT lub przynajmniej wzdłuż boku AOT (innymi słowy uruchomić AOT testów jednostkowych produkcji i JIT z jednym zestawem templateUrls)

dzięki jeszcze raz!

PS .. To działało bez AoT idealnie (z absolutnymi adresami URL), ale przejście na AoT (z adresami URL względem pliku komponentu) zablokowało nas.

AKTUALIZACJA 2: (w tym wszystkie moje pliki konfiguracyjne) jeśli muszę utworzyć inny plik konfiguracyjny, aby uruchomić testy z (co ma sens), ale chciałbym wiedzieć, co "magiczne", że test wymaga konfiguracji w celu uruchamiać komponenty JiT, ponieważ moje adresy URL są względne.

webpack.config.js

let webpack = require('webpack'); 
let path = require('path'); 
let aot = require('@ngtools/webpack'); 

module.exports = { 
    entry: { 
     main: './Angular/main' 
    }, 
    output: { 
     path: __dirname, 
     filename: './dist/smartcommand-[name].min.js', 
     // Lazy load modules by route & chunk 
     chunkFilename: './dist/smartcommand-[name].chunk.[hash].min.js' 
    }, 
    resolve: { 
     extensions: ['.ts', '.js'], 
     modules: [ 
      path.resolve('./'), 
      path.resolve('./node_modules') 
     ], 
     alias: { 
      'ng2-charts/charts/charts': 'node_modules/ng2-charts/bundles/ng2-charts.umd.min.js' 
      //'ng2-dragula': 'node_modules/ng2-dragula/bundles/ng2-dragula.umd.min.js' 
     } 
    }, 
    module: { 
     rules: [ 
      // Ahead of Time Compilation 
      { test: /\.ts$/, loader: '@ngtools/webpack', exclude: [/\.(spec)\.ts$/] }, 
      // AoT requires all files to be loaded 
      { test: /\.html$/, loader: 'html-loader' }, 
      { test: /\.css$/, loader: 'raw-loader' }, 
      { 
       test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/, 
       loader: 'file-loader', options: { name: '[path][name].[ext]' } 
      } 
     ] 
    }, 
    plugins: [ 
     new webpack.optimize.CommonsChunkPlugin({ name: 'main' }), 
     // Ahead of Time Plugin 
     new aot.AngularCompilerPlugin({ 
      tsConfigPath: path.resolve('./Angular/tsconfig.json'), 
      entryModule: path.resolve('./Angular/_app.module#SmartCommandModule') 
      // Use this setting to turn off AoT 
      //,skipCodeGeneration: true 
     }), 
     // Only load the necessary locales for moment 
     new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /en|es/) 
    ], 
    // Minimize webpack console output 
    stats: { assets: false, children: false } 
}; 

karma.config.js

/* Karma Configuration */ 
'use strict'; 
module.exports = function (config) { 
    let appBase = 'Angular/'; // transpiled app JS and map files 

    config.set({ 
     plugins: [ 
      'karma-jasmine', 
      'karma-jasmine-html-reporter', 
      //'karma-chrome-launcher', 
      'karma-firefox-launcher', 

      // preprocessors 
      'karma-webpack', 
      'karma-sourcemap-loader', // show proper (un-bundled) stack traces 
      'karma-coverage', // capture unit test code coverage 
      'karma-trx-reporter' // report coverage in VSTS 
     ], 

     // frameworks to use 
     // available frameworks: https://npmjs.org/browse/keyword/karma-adapter 
     frameworks: ['jasmine'], 

     // start these browsers 
     // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher 
     //browsers: ['Chrome'], 
     browsers: ['Firefox'], 

     // preprocess matching files before serving them to the browser 
     // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor 
     preprocessors: { 
      'karma-test-shim.js': ['webpack', 'coverage'] 
      // for debugging the tests 
      //'karma-test-shim.js': ['webpack', 'sourcemap'] 
     }, 

     // base path that will be used to resolve all patterns (eg. files, exclude) 
     basePath: '', 

     // list of files/patterns to load in the browser 
     files: [ 
      // polyfills 
      'node_modules/core-js/client/shim.js', 

      'Scripts/jquery-3.1.1.min.js', 
      'Scripts/jquery-ui-1.12.1.min.js', 

      'node_modules/moment/moment.js', 
      'node_modules/leaflet/dist/leaflet.js', 
      'node_modules/nipplejs/dist/nipplejs.js', 

      'node_modules/zone.js/dist/zone.js', 
      'node_modules/zone.js/dist/long-stack-trace-zone.js', 
      'node_modules/zone.js/dist/proxy.js', 
      'node_modules/zone.js/dist/sync-test.js', 
      'node_modules/zone.js/dist/jasmine-patch.js', 
      'node_modules/zone.js/dist/async-test.js', 
      'node_modules/zone.js/dist/fake-async-test.js', 

      // rxJS 
      { pattern: 'node_modules/rxjs/**/*.js', included: false, watched: false }, 
      { pattern: 'node_modules/rxjs/**/*.js.map', included: false, watched: false }, 

      // other dependencies 
      { pattern: 'node_modules/applicationinsights-js/**/*.js', included: false, watched: false }, 
      { pattern: 'node_modules/applicationinsights-js/**/*.js.map', included: false, watched: false }, 

      { pattern: 'node_modules/ng2-charts/**/*.js', included: false, watched: false }, 
      { pattern: 'node_modules/ng2-charts/**/*.js.map', included: false, watched: false }, 
      'node_modules/chart.js/dist/Chart.bundle.js', 

      { pattern: 'node_modules/primeng/**/*.js', included: false, watched: false }, 
      { pattern: 'node_modules/ngx-slick/**/*.js', included: false, watched: false }, 

      { pattern: 'node_modules/ng2-dragula/**/*.js', included: false, watched: false }, 
      { pattern: 'node_modules/ng2-dragula/**/*.js.map', included: false, watched: false }, 

      // our SmartCommand bundle 
      'dist/smartcommand-main.min.js', 

      // our Karma tests 
      { pattern: 'karma-test-shim.js', included: true, watched: true }, 

      // paths for debugging with source maps in dev tools 
      { pattern: appBase + '**/*.ts', included: false, watched: false }, 
      { pattern: appBase + '**/*.js.map', included: false, watched: false }, 

      // our assets (HTML & CSS) paths loaded via Angular's component compiler 
      { pattern: appBase + '**/*.html', included: false, watched: true }, 
      { pattern: appBase + '**/*.css', included: false, watched: true }, 
      { pattern: 'Content/*.css', included: true, watched: false }, 
      { pattern: 'Content/*.css.map', included: false, watched: false }, 
      { pattern: 'Content/Images/**/*', included: false, watched: false }, 
      { pattern: 'Content/images/**/*', included: false, watched: false } 
     ], 

     // proxied base paths for loading assets 
     proxies: { 
      // required for component assets fetched by Angular's compiler 
      '/Angular/': '/base/Angular/', 
      '/Content/': '/base/Content/' 
     }, 

     // test results reporter to use 
     // available reporters: https://npmjs.org/browse/keyword/karma-reporter 
     reporters: ['progress', 'kjhtml', 'coverage', 'trx'], 

     // karma code coverage 
     coverageReporter: { 
      // specify a common output directory 
      dir: 'coverage', 
      reporters: [ 
       // reporters not supporting the `file` property 
       { type: 'html', subdir: 'report-html' }, 
       { type: 'lcov', subdir: 'report-lcov' }, 
       // reporters supporting the `file` property, use `subdir` to directly 
       // output them in the `dir` directory 
       { type: 'cobertura', subdir: '.', file: 'cobertura.txt' }, 
       { type: 'lcovonly', subdir: '.', file: 'report-lcovonly.txt' }, 
       { type: 'teamcity', subdir: '.', file: 'teamcity.txt' }, 
       { type: 'text', subdir: '.', file: 'text.txt' }, 
       { type: 'text-summary', subdir: '.', file: 'text-summary.txt' } 
      ] 
     }, 

     // get code coverage in VSTS 
     trxReporter: { outputFile: 'test-results.trx', shortTestName: false }, 

     // web server port 
     port: 9876, 

     // enable/disable colors in the output (reporters and logs) 
     colors: true, 

     // level of logging 
     // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG 
     logLevel: config.LOG_INFO, 

     // enable/disable watching file and executing tests whenever any file changes 
     autoWatch: true, 

     // continuous integration mode 
     // if true, Karma captures browsers, runs the tests and exits 
     singleRun: false, 

     // concurrency level 
     // how many browsers should be started simultaneous 
     concurrency: Infinity, 

     client: { 
      captureConsole: false, // set to true if you need console output 
      builtPaths: [appBase], // add more spec base paths as needed 
      clearContext: false // leave Jasmine Spec Runner output visible in browser 
     }, 

     // workaround for disconnects 
     browserDisconnectTolerance: 5, 
     browserNoActivityTimeout: 50000 
    }); 
}; 

test karma Shim

// 'No stack trace' is usually best for app testing. 
Error.stackTraceLimit = 0; 
// Uncomment to get full stacktrace output. Sometimes helpful, usually not. 
//Error.stackTraceLimit = Infinity; 

// Import all .spec.js files in our Angular folder 
let appContext = require.context('./Angular', true, /\.spec\.js$/); 
appContext.keys().forEach(appContext); 

// Start the Test Environment 
let testing = require('@angular/core/testing'); 
let browser = require('@angular/platform-browser-dynamic/testing'); 
testing.TestBed.initTestEnvironment(browser.BrowserDynamicTestingModule, browser.platformBrowserDynamicTesting()); 
+5

Cóż, kanciasty-CLI używa WebPack też, i współpracuje z względnymi ścieżkami. Użyj eject w projekcie CLI i zobacz, jak to zrobili? Lub użyj CLI. –

+0

Szybko wypróbowałem sztuczkę ng eject i nie widziałem nic użytecznego w webpack.config.js. dobrze jest wiedzieć, że CLI działa. Dzięki!! ponownie skorzystałem z porady, aby ponownie wysunąć projekt CLI Z komponentami potomnymi. widzę, że zaczynają wszystkie adresy URL z "./", ale to nie pomagało. również wzięli swoje parametry, które przechodzą do AoTplugin, ale też nie pomagają. może jest tutaj, ale po prostu nie wiem, czego szukam – Jesse

+0

gdzieś w tym projekcie CLI musi być jakaś magia, którą mogę skopiować do mojego projektu na webpacka ... mam nadzieję .. w razie czego nie znajdę znasz jakieś odniesienia do konwersji z webpacka na cli? dzięki jeszcze raz! – Jesse

Odpowiedz

1

Oto problem widzę. W rzeczywistości używasz dwóch różnych konfiguracji Webpack. Oczywiście, jest twój webpack.config.js, który jest ustawiony dla AoT.

Jednak używasz innej, innej konfiguracji, gdy używasz Karmy. Wtyczka karma-webpack udostępnia instancję Webpack działającą w procesie Karma z własną konfiguracją. Jeśli sam nie napiszesz kodu w swoim karma.config.js, aby przeczytać webpack.config.js, Karma całkowicie zignoruje ten plik. Tak skutecznie, gdy korzystasz z Karmy, używasz innej konfiguracji Webpack. Problem polega na tym, że obecnie twoja konfiguracja jest pusta, co oznacza, że ​​Angular przetwarza "surowy" i ma wyniki, które uzyskujesz.

Musisz skonfigurować Webpack z ładowaczem, który przetworzy templateUrl i stylesUrls, aby je obsługiwał. W tym celu użyłbym angular2-template-loader.

Wygląda na to, że do czasu, gdy Karma zobaczy twoje pliki, wszystkie zostały przeniesione do JavaScript. Zwykle w plikach TypeScript używane jest angular2-template-loader, ale ponieważ wykonuje ono swoje zadanie za pomocą wyrażeń regularnych, działa również na plikach JavaScript.

będę oczekiwać dodanie konfiguracji WebPACK z angular2-template-loader do listy karma.config.js powinny działać, i dostosować do potrzeb specyficznych dla danego projektu:

webpack: { 
    module: { 
    loaders: [ 
     { 
     test: /\.js$/, 
     loaders: ['angular2-template-loader'], 
     // exclude: [...] You may want to exclude your test files here 
     // to save some build time. 
     }, 
     // etc. with raw-loader, html-loader and file-loader as needed.    
    ]}, 
    } 
+0

Dziękuję! Spróbuję tego tak szybko, jak będę mógł! – Jesse

+0

Jesteś mężczyzną !!! dodaje/base/przed wszystkimi ścieżkami (na co jestem pewien, że potrafię się zająć), ale reszta ścieżki jest poprawna w oparciu o komponent zamiast wszystkich znajdujących się w katalogu głównym lokacji !!! Dziękuję bardzo!! To jest dokładnie to, czego szukałem, utknąłem na tym przez tydzień! Kupiłbym ci drinka, gdybym mógł! – Jesse

Powiązane problemy