加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

角度分量的绝对或相对“templateUrls”

发布时间:2020-12-17 18:10:57 所属栏目:安全 来源:网络整理
导读:有人可以帮我解决1 vs 2的这种情况吗? 1)角度项目作为AoT在生产中.这需要将我的源代码更改为具有相对于component.ts文件的templateUrl和styleUrls. 2)角度业力为单位测试的JiT.这需要将我的源代码更改为具有绝对的templateUrl和styleUrls,否则单元测试将抛
有人可以帮我解决1 vs 2的这种情况吗?

1)角度项目作为AoT在生产中.这需要将我的源代码更改为具有相对于component.ts文件的templateUrl和styleUrls.

2)角度业力为单位测试的JiT.这需要将我的源代码更改为具有绝对的templateUrl和styleUrls,否则单元测试将抛出404寻找.html文件.

我想避免在源代码中保持相对AND绝对路径.

我有什么选择?什么是最佳做法?

(我正在使用带有aot和Karma的WEBPACK,而不是angular-cli)

谢谢!!

更新:
我们也将探索转换为angular-cli,但这是一个巨大的项目,如果有人知道angular-cli用来解决这个问题的技巧,这对我们来说是一个阻碍.甚至是一个解决方案,所以我们可以让我们的单元测试回来!

我需要知道一个技巧来运行单元测试使用AoT或至少ALONG SIDE AoT(换句话说,使用一组templateUrls运行生产和jit单元测试)

再次感谢!

PS ..
这完全没有AoT(使用绝对URL),但切换到AoT(相对于组件文件的url)阻止了我们.

更新2 :(包括我所有的配置文件)
如果我必须创建另一个配置文件来运行测试(这是有道理的)但我想知道测试配置需要什么’魔术’才能运行JiT组件,现在我的网址都是相对的.

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',// other dependencies
            { pattern: 'node_modules/applicationinsights-js/**/*.js',{ pattern: 'node_modules/applicationinsights-js/**/*.js.map',{ pattern: 'node_modules/ng2-charts/**/*.js',{ pattern: 'node_modules/ng2-charts/**/*.js.map','node_modules/chart.js/dist/Chart.bundle.js',{ pattern: 'node_modules/primeng/**/*.js',{ pattern: 'node_modules/ngx-slick/**/*.js',{ pattern: 'node_modules/ng2-dragula/**/*.js',{ pattern: 'node_modules/ng2-dragula/**/*.js.map',// 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',{ pattern: appBase + '**/*.js.map',// our assets (HTML & CSS) paths loaded via Angular's component compiler
            { pattern: appBase + '**/*.html',{ pattern: appBase + '**/*.css',{ pattern: 'Content/*.css',{ pattern: 'Content/*.css.map',{ pattern: 'Content/Images/**/*',{ pattern: 'Content/images/**/*',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',file: 'report-lcovonly.txt' },{ type: 'teamcity',file: 'teamcity.txt' },{ type: 'text',file: 'text.txt' },{ type: 'text-summary',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
    });
};

业力测试垫片

// '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());

解决方法

这是我看到的问题.实际上,您正在使用两种不同的Webpack配置.显然,你的webpack.config.js是为AoT设置的.

但是,当您运行Karma时,您正在使用另一个不同的配置. karma-webpack插件提供了在Karma进程中运行的Webpack实例及其自己的配置.除非您自己在karma.config.js中编写代码来读取webpack.config.js,否则Karma将完全忽略该文件.如此有效,您运行的是不同的Webpack配置.问题是目前你的配置是空的,这意味着Angular正在处理templateUrl和styleUrls“raw”,你得到了你得到的结果.

您需要使用加载程序设置Webpack,该加载程序将处理templateUrl和stylesUrls以使Webpack处理它们.我会用angular2-template-loader这个.

看看你的配置,似乎当Karma看到你的文件时,它们都被转换为JavaScript.通常,angular2-template-loader用于TypeScript文件,但由于它使用正则表达式完成其工作,因此它也适用于JavaScript文件.

我希望在你的karma.config.js中添加带有angular2-template-loader的Webpack配置,并调整你的项目特定需求:

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.              
    ]},}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读