Webpack 2 with angular 2 and asp.net mvc cshtml as template - asp.net-mvc

I've a project running with Angular 2 and webpack 2 but currently I load all my templates directly into the js file with no addional template loading from the server. That works great.
#Component({
selector: 'logmonitor',
styleUrls: [ './logmonitor.component.less' ],
templateUrl: './logmonitor.component.html'
}) ...
but I need to load only some Templates from a cshtml view and the views should only get loaded with an extra server request when I open these views.
I've created a simple cshtml view in my views folder an I can directly "show" it when typing the right controller/action into the url. That "works"
but I've tried to set this to get the Template loaded
#Component({
selector: 'testView',
templateUrl: 'Logviewer/TestLogview',
}) ...
but webpack will not compile the view it gives a error
Module not found: Error: Can't resolve './Logviewer/TestLogview' in 'C:\SourceControl\WebLogViewer\App\Views\LogViewer'
thats right the file is daved in
C:\SourceControl\WebLogViewer\Views\LogViewer
but I don't want that webpack tries to resolve this url, angular itself need to call this url when the view gets loaded. I've thought webpack will not try to load the cshtml file when I don't write the "./" in front of the file name, but thats not working. Is there a solution how I can prevent webpack from parsing all templateUrl ?
thats my current Loader for html files, but this should not parse the string because there is not .html at the end :-/
{
test: /\.html$/,
use: ['raw-loader'],
exclude: [helpers.root('App/index.html')]
},

You can find a working example in this repo.
https://github.com/timdows/webpages/tree/master/Angular2RazorViews
The key is lazy loading and
angular2-load-children-loader
in loading the ts template dependencies

Related

NestJs Swagger how to add custom favicon

I am trying to add a custom favicon to my NestJs documentation. However, I am a bit lost on how the path file gets resolved and not sure how to achieve this.
I am using nestjs/swagger module version 3.1.0 and trying to pass the path file like so when initializing the Swagger Module.
My main.ts file
SwaggerModule.setup('/v1/docs', app, document, {
customCss: CUSTOM_STYLE,
customSiteTitle: 'My API Documentation',
customfavIcon: './public/favicon.jpg'
});
Searched on the github issues and didn't find anything useful. And as you can see from the code I was able to modify the CSS styles, but I cannot figure out how to make the favicon custom.
Appreciate any help
I have added the custom favicon to my swagger docs using following:
The first thing you make sure is, in your main.ts, the app is initialized with the following:
const app: NestExpressApplication = await NestFactory.create(...)
To serve static content you must initialize your app with NestExpressApplication.
The next thing is to allow the Nest application to look for public content using the following in your main.ts after initialization:
app.useStaticAssets(join(__dirname, '..', 'public'));
Also, create a public directory in your root of the application and paste your favicon.jpg file in it.
Now its time to initialize the Swagger in main.ts
SwaggerModule.setup('/v1/docs', app, document, {
customCss: CUSTOM_STYLE,
customSiteTitle: 'My API Documentation',
customfavIcon: '../favicon.jpg'
});
You must give a relative path to the root of the application like ../favicon.jpg in case our main.ts is in src folder in root of the application.
Alternative solution, just host your favicon and reference it with external url
SwaggerModule.setup('api', app, getSwaggerDocument(app), {
...
customfavIcon:
'https://[your-bucket-url].com/.../anything.png',
});
To iterate on pravindot17's answer, now there's the #nestjs/serve-static package for hosting static files. Which avoid us from type-casting the Nest.js client and relying on our implicit assumption that we're running an Express-backed Nest.js server.
After installing the package, you hook it into your src/app.module.ts. This configuration expects that the root of your project has a /public/ folder where you store your static assets.
import { Module } from '#nestjs/common';
import { ServeStaticModule } from '#nestjs/serve-static';
import { join } from 'path';
#Module({
imports: [
// Host static files in ../public under the /static path.
ServeStaticModule.forRoot({
/**
* Config options are documented:
* https://github.com/nestjs/serve-static/blob/master/lib/interfaces/serve-static-options.interface.ts
*/
rootPath: join(__dirname, '..', '..', 'public'),
serveRoot: '/static',
}),
// ...
})
export class AppModule {}
Now my own preference is using an absolute path rather than relative, as it makes it independent from the path we picked to host our API documentation under.
SwaggerModule.setup('/v1/docs', app, document, {
customfavIcon: '/static/favicon.jpg'
});
One last note is that this configuration hosts static files from /static/*, this is done to prevent that API calls to non-existing endpoints show an error message to the end-user that the static file cannot be found.
Otherwise, all 404's on non-existing endpoints will look something like:
{"statusCode":404,"message":"ENOENT: no such file or directory, stat '/Users/me/my-project/public/index.html'"}

Rails 5.1 Angular templateUrl

Question
What do I need to do to get my Angular application to allow me to use the templateUrl property of the Component decorator? When you create a new Rails 5.1 application and use the flag --webpack=angular, it gives you a proof of concept Angular application, but as soon as I started creating more components, I began to recognize that I don't know how to refer to the correct path that the templates are being served. I'm not even sure if they are being served, to be honest.
What I've tried
Tried many different variations of the path, from just the file name all the way to the root of the application, one folder at a time.
Googling for someone else running into the same problem.
include the CommonModule in my imports in app.module.ts.
Background
I'm really used to using the Angular CLI and I don't remember ever having an issue using the templateUrl property. What is different about an Angular CLI project to what's given to you in a Rails 5.1 app in terms of configuration affecting templates? Would I be able to use Angular CLI in a Rails 5.1 app without having to change much of the Rails app itself?
Can be done. But this needs a different webpack loader setup and several minor tweaks.
But first: shopping!
$ yarn add \
html-loader \
awesome-typescript-loader \
angular2-template-loader \
#types/node \
--dev
With all required packages installed replace config/webpack/loaders/angular.js with this:
const {env} = require('../configuration.js');
isProd = env.NODE_ENV === 'production';
module.exports = {
test: /\.ts$/,
use: [
{
loader: 'awesome-typescript-loader',
options: { useCache: !isProd }
},
'angular2-template-loader'
]
};
angular2-template-loader scans your Component decorators for the templateUrl argument and replaces it with something like template: require('...')'. The require() call is the reason for installing #types/node by the way.
awesome-typescript-loader is a bit more optimized than the default ts-loader (which will probably work here as well, but I didn't test it).
So far so good. Next we need to tell webpack how to actually load HTML files. Add config/webpack/loaders/html.js with the following content:
module.exports = {
test: /\.html$/,
loader: 'html-loader',
};
Nothing obscure here. Moving on.
In your Javascript app add type informations for *.html files to app/javascript/hello_angular/html.d.ts:
declare module "*.html" {
const content: string
export default content
}
This tells the TypeScript compiler that require('template.html') returns a string.
Last but not least you have add .html to the recognized extensions in config/webpacker.yml:
default: &default
# ...
extensions:
# ...
- .html
# ...
Now you should be good to go:
import { Component } from '#angular/core';
#Component({
selector: 'hello-angular',
templateUrl: './template.html'
})
export class AppComponent {
name = 'Angular!';
}
Don't forget to restart bin/webpack-dev-server.
Theoretically you could do the same for styleUrls. But this is more tangled with rails/webpacker and you would loose some of it's features.

All angularJs templateUrl paths invalid

So I'm writing a small app and currently working on the angular js front end. The backend is written in RoR but thats besides the point. I have a dependency ui.router in my angular.module so I can move around pages.
Link to github branch if interested: linky link
Paths:
App
-Assets
-Javascripts
-app.js (where the routing lies)
-Templates
-dashboard.html (this is the template I want to render)
-Views
-Layouts
-Index.html.erb <- this is the index
Heres the problem:
angular.module('SwoleMetrics', [
'ui.router',
'templates'
])
.config(function ($stateProvider, $urlRouterProvider, $locationProvider) {
/**
* Routes and States
*/
$stateProvider
.state('dashboard', {
url: '/dashboard',
templateUrl: 'dashboard.html', <<--- RIGHT HERE
controller: 'DashboardCtrl'
});
// default fall back route
$urlRouterProvider.otherwise('/dashboard');
// enable HTML5 Mode for SEO
$locationProvider.html5Mode(true);
});
No matter what path I put into templateUrl, it never works. I have the same html file in basically every folder around app.js to see if it could read any of those but it always fails and just recursively inserts the parent div into the . Do any front end engineers know why?
The issue was the way the files were being served via rails. The sprockets gem was updated and no longer compatible with angular-ui-templates and broke everything. Downgraded to sprockets v. 2.x and it worked.
Its going to be relative to index.html. If index.html is under App then your path is going to be templateUrl: 'Templates/dashboard.html'.

In AngularDart, how should I reference my templates in templateUrl so they work for both Dartium and dart2js?

I currently have this directory layout:
project
web
app.html
main.dart
templates
app.html
alerts.html
menu.html
components
AppComponent.dart
AlertsComponent.dart
MenuComponent.dart
resources
css
bootstrap.css
My components look like:
#Component(
selector: 'app',
templateUrl: 'templates/app.html'
)
class AppComponent { ... }
My application's index.html (in another project) is served from /client, and project/web is served from /project. The above works in Dartium, but I get errors from pub build:
[Warning from _Serial on project|web/main.dart with input project|web/components/AppComponent.dart]:
line 3, column 1 of web/components/AppComponent.dart: Unable to find templates/app.html at project|templates/app.html
#Component(
^^^^^^^^^^^
and
[Warning from _Serial]:
Unable to find webatara|web/main.dart from html_files in pubspec.yaml.
and
[Warning from TemplateCacheGenerator]:
Can't find asset web/web/templates/app.html.
depending on what combination of paths I use in templateUrl and html_files (for Angular's transformer).
What, exactly, should go where and how should it be referenced in templateUrl and pubspec.yaml?
Update: I can get rid of my build errors by moving my templates to the lib directory and using templateUrl: 'packages/project/templates/app.html', but then Dartium tries to load that as /packages/project/templates/app.html, and not /project/packages/project/templates/app.html, which would be correct. I don't see any way to tell it what the base URL is.
but then Dartium tries to load that as
/packages/project/templates/app.html, and not
/project/packages/project/templates/app.html, which would be correct.
I don't see any way to tell it what the base URL is.
I believe you are using angulardart 1.1.1 or 1.1.2? We had the same issue in our project after switching from 1.1.0 to 1.1.2. This is weird behaviour that was added since version 1.1.1.
For some reason default package root in AngularDart now is '/packages/'. This causes generation of root-relative URLs. In your case it generates
/packages/project/templates/app.html
instead of
packages/project/templates/app.html
It's OK while you app is in the root of your domain. But in your case what you need to do is to add following to your initialization method in main.dart:
bind(ResourceResolverConfig, toValue: new ResourceResolverConfig
.resolveRelativeUrls(true, packageRoot: 'packages/'));
This will override angular's default packages root and will make it generate correct relative URLs.
Hope it helps.

AngularJS Template Url not working

I am trying to set a templateUrl on a route in AngularJS using an html file in a child directory of assets. It works fine locally.
The templates are stored at: #{RAILS_ROOT}/app/assets/templates
# Sets up routing
Blog.config(['$routeProvider', ($routeProvider) ->
# Route for '/post'
$routeProvider.when('/post', { templateUrl: './assets/mainIndex.html', controller: 'PostCtrl' } )
# Default
$routeProvider.otherwise({ templateUrl: './assets/mainIndex.html', controller: 'IndexCtrl' } )])
I've tried leveraging asset_path, but that doesn't seem to work at all.
try to remove the ./ before the assets
$routeProvider.when('/post', { templateUrl: 'assets/mainIndex.html', controller: 'PostCtrl' } )
We must both be working on the same AngularJS/Rails tutorial. I am stuck on the same part.
asset_path does work. Make sure your javascript.coffee file ends in .erb
My templates are at:
app/assets/templates
In my main.js.coffee.erb (DONT FORGET the .erb), I have the templateUrl defined as:
templateUrl: '<%= asset_path('mainIndex.html')%>'
This works locally. Unfortunately, it still isn't working in production (I'm using OpenShift.) The precompiled files are being generated at (public/assets.) However, the asset_path always resolves to
GET /assets/mainIndex.html
rather than something like:
GET assets/mainIndex-435fd76973a72d658af47da0fb824bcd.html
In the logs, I see all of the assets GETs referencing the precompiled files, but for some reason, this templateUrl isnt. That's my next problem to solve.

Resources