gpt4 book ai didi

angular - Angular 分量的绝对或相对 "templateUrls"

转载 作者:太空狗 更新时间:2023-10-29 17:39:08 26 4
gpt4 key购买 nike

谁能帮我解决这个 1 对 2 的死胡同?

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

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

我想避免在源代码中维护相对路径和绝对路径。

我在这里有哪些选择?最佳做法是什么?

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

谢谢!!

更新:我们还将探索转换为 angular-cli,但这是一个巨大的项目,如果有人知道 angular-cli 用来实现这一目标的技巧,这对我们来说是一个障碍。甚至是解决方法,以便我们可以恢复单元测试!

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

再次感谢!

附言..这在没有 AoT 的情况下工作得很好(使用绝对 url),但是切换到 AoT(使用相对于组件文件的 url)已经阻止了我们。

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

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

karma 测试垫片

// '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 将完全忽略该文件。如此有效,当你运行 Karma 时,你正在运行不同的 Webpack 配置。问题是当前你的配置是空的,这意味着 Angular 正在处理 templateUrlstyleUrls “原始”,你得到你得到的结果。

您需要为 Webpack 设置一个加载程序,该加载程序将处理 templateUrlstylesUrls 让 Webpack 处理它们。我会用 angular2-template-loader为了这。

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

我希望将带有 angular2-template-loader 的 Webpack 配置添加到您的 karma.config.js 应该可以工作,并根据您项目的具体需求进行调整:

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

关于angular - Angular 分量的绝对或相对 "templateUrls",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47517360/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com