templateUrl does not work - node.js

I'm trying to make angular2-material app
It works when I template: ~ but If I use templateUrl: ~, <my-app> contains nothing even Loading... and a Network log Informed me the template successfully loaded 200 GET /app/mainLayout.html
Basically, I followed quick start guide of angular2 docs and these are what I did
installing angular2-materialize by npm
import "angular2-materialize" in main.ts
add System.config in index.html
index.html
<!-- 2. Configure SystemJS -->
<script src="systemjs.config.js"></script>
<script>
System.config({
defaultJSExtensions: true,
packages: {
"materialize-css": {
"main": "dist/js/materialize"
},
"materialize": {
"main": "dist/materialize-directive",
"defaultExtension": "js"
}
},
map: {
"materialize-css": "node-modules/materialize-css",
"materialize": "node_modules/angular2-materialize",
"angular2-materialize": "node_modules/angular2-materialize"
}
});
System.import('app').catch(function(err){ console.error(err); });
</script>
add MaterializeDirective in app.component.ts
app.component.ts
import { Component } from '#angular/core';
import { MaterializeDirective } from 'angular2-materialize';
#Component({
selector: 'my-app',
directives: [MaterializeDirective],
templateUrl: 'app/views/mainLayout.html',
styleUrls: ['/app/css/mainLayout.css']
})
export class AppComponent { }
This is my working dir
|
|-app
| |-css
| | |-mainLayout.css
| |-views
| | |-mainLayout.html
| |
| |-app.component.ts
| |-main.ts
|
|-node_modules
| |-(....)
|-typings
| |-globals
| | |-(...)
| |-index.d.ts
|-package.json
|-systemjs.config.js
|-tsconfig.json
|-typings.json
one more thing. I think --regardless of template: statement-- it seems some path are setted wrong. *.js files are loaded successfully but *.map files are not.
[1] 16.06.21 20:17:15 200 GET /node_modules/rxjs/Subject.js
[1] 16.06.21 20:17:15 404 GET /node_modules/systemjs/dist/Subject.js.map
like this

Try
#Component({
selector: 'my-app',
directives: [MaterializeDirective],
templateUrl: './app/views/mainLayout.html',
styleUrls: ['/app/css/mainLayout.css']
})
The key difference being './app/. This makes Angular look for the "mainLayout.html" in the current root /app/views/.

Although I don't know what happend, I resolved the problem somehow. Few more restarting npm and app/views/mainLayout.html were solution. but the angular2 still find .map in wrong path. Please let me know why it happen if there are someone who have a idea.

Related

Mirage/Pretender causes errors in Vitest

I'm working on migrating from Jest to Vitest (alongside CRA > Vite migration), and I think I've got everything working, except that using Mirage causes errors. Setting the vite config test environment between happy-dom and 'jsdom' both give different errors, though they appear to be related or similar or the same (just with happy-dom giving much more useful information!
My very simplified test:
import { describe, expect, it } from "vitest"
import { createServer } from "miragejs";
describe('tests', () => {
createServer({})
it('works', () => {
expect(true).toEqual(true)
})
})
happydom error
TypeError: Cannot read properties of undefined (reading 'prototype')
❯ interceptor node_modules/pretender/dist/pretender.js:1540:46
❯ new Pretender node_modules/pretender/dist/pretender.js:1638:32
❯ PretenderConfig._create node_modules/miragejs/dist/mirage-cjs.js:6398:14
❯ PretenderConfig.create node_modules/miragejs/dist/mirage-cjs.js:6259:27
❯ Server.config node_modules/miragejs/dist/mirage-cjs.js:6824:24
❯ new Server node_modules/miragejs/dist/mirage-cjs.js:6760:10
❯ Proxy.createServer node_modules/miragejs/dist/mirage-cjs.js:6725:10
❯ src/test.test.tsx:5:2
3|
4| describe('tests', () => {
5| createServer({})
| ^
6| it('works', () => {
7| expect(true).toEqual(true)
jsdom error
Error: Errors occurred while running tests. For more information, see serialized error.
❯ Object.runTests node_modules/vitest/dist/chunk-vite-node-externalize.6956d2d9.mjs:7048:17
❯ processTicksAndRejections node:internal/process/task_queues:96:5
❯ async file:/Users/jtuzman-superdraft/dev/superdraft-core-admin/NEW-vite-admin/node_modules/vitest/dist/chunk-vite-node-externalize.6956d2d9.mjs:10545:9
❯ Vitest.runFiles node_modules/vitest/dist/chunk-vite-node-externalize.6956d2d9.mjs:10558:12
❯ Vitest.start node_modules/vitest/dist/chunk-vite-node-externalize.6956d2d9.mjs:10479:5
❯ startVitest node_modules/vitest/dist/chunk-vite-node-externalize.6956d2d9.mjs:11204:5
❯ start node_modules/vitest/dist/cli.mjs:666:9
❯ CAC.run node_modules/vitest/dist/cli.mjs:662:3
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
Serialized Error: {
"errors": [
[Error: Internal error: Error constructor is not present on the given global object.],
],
}
vite.config.ts
/// <reference types="vitest" />
import { defineConfig } from 'vite';
import react from '#vitejs/plugin-react'
import svgrPlugin from 'vite-plugin-svgr';
import macrosPlugin from "vite-plugin-babel-macros"
import checker from 'vite-plugin-checker'
// https://vitejs.dev/config/
export default defineConfig({
test: {
globals: true,
environment: "jsdom", // or "happy-dom"
},
define: {
global: {},
},
esbuild: {
logOverride: { 'this-is-undefined-in-esm': 'silent' }
},
plugins: [
react(),
svgrPlugin({
svgrOptions: {
icon: true,
},
}),
macrosPlugin(),
checker({
typescript: true,
overlay: {
panelStyle: 'height: 100vh; max-height: unset;'
}
})
],
});
This GitHub issue appears to deal with the same question but doesn't appear to solve it.
Ran into the same thing. It's the global: {} statement. When I commented it out in my vite.config.ts file, my tests ran successfully. I haven't figured out another way to solve the global error yet that caused me to set that in the first place though.
happy-dom does not provide an implementation for XMLHttpRequest, which is used by pretenderjs. The most straightforward walk around is to put the following line at the very top of your test code, before the the vitest environment:
this.XMLHttpRequest = vi.fn()
//#vitest-environment happy-dom

Adding nguniversal/express-engine to Angular proj: "Cannot find BrowserModule import in /src/app/app.module.ts"

First question
Goal
I'm trying to add SSR to my Angular project with ng add #nguniversal/express-engine --clientProject [name] (so I can dynamically prerender meta tags)
Expected Result
I expected the command to execute successfully with all the scaffolding and necessary updates to my existing files, as demonstrated in this YouTube tutorial.
Actual Result
Instead, the console says this:
Installing packages for tooling via npm.
Installed packages for tooling via npm.
Cannot find BrowserModule import in /src/app/app.module.ts
But BrowserModule is imported in app.module.ts.
What I've Tried
Reinstalling package
I've tried uninstalling the package with npm uninstall #nguniversal/express-engineand re-running the ng add above, same issue.
Other posted questions about ng adding #nguniversal/express-server don't seem to apply here, as those guys actually got as far as creating some of the scaffolding and generating the new files - no files are created for me at all, but the module does get added to my node-modules folder.
Could it be an issue with simply reading the typescript in app.module.ts? The BrowserModule import is there, and in the imports array. This is the output for npm ls typescript:
+-- #angular-devkit/build-angular#0.901.8
| `-- #angular-devkit/build-optimizer#0.901.8
| `-- typescript#3.6.5
+-- #ng-toolkit/universal#1.1.21
| +-- #ng-toolkit/_utils#1.1.51
| | `-- #schematics/angular#7.3.10
| | `-- typescript#3.2.4
| `-- #schematics/angular#0.6.8
| `-- typescript#2.7.2
`-- typescript#3.8.3
Additional Info (for David)
app.module.ts
import { BrowserModule, Meta, Title } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { FooterComponent } from './footer/footer.component';
import { HomeComponent } from './home/home.component';
import { FontAwesomeModule } from '#fortawesome/angular-fontawesome';
import { SoftwareComponent } from './software/software.component';
import { MediaComponent } from './media/media.component';
import { ShopComponent } from './shop/shop.component';
import { FilmDetailsComponent } from './film-details/film-details.component';
import { ShareModalComponent } from './share-modal/share-modal.component';
import { ShareModule } from 'ngx-sharebuttons';
import { ShareButtonModule } from 'ngx-sharebuttons/button';
import { ShareIconsModule } from 'ngx-sharebuttons/icons';
#NgModule({
imports: [
ShareButtonModule,
ShareIconsModule // Optional if you want the default share icons
]
})
#NgModule({
declarations: [
AppComponent,
HeaderComponent,
FooterComponent,
HomeComponent,
SoftwareComponent,
MediaComponent,
ShopComponent,
FilmDetailsComponent,
ShareModalComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FontAwesomeModule,
ShareModule,
ShareButtonModule,
ShareIconsModule
],
providers: [Meta, Title],
bootstrap: [AppComponent]
})
export class AppModule { }
main.ts
import { enableProdMode } from '#angular/core';
import { platformBrowserDynamic } from '#angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
if (environment.production) {
enableProdMode();
}
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.error(err));
This error is caused by multiple NgModules in the app.module, as the first NgModule imports doesn't contain BrowserModule.
app would still work fine if you remove first NgModule since the modules in the imports are already imported in the second one

Angular 6 Bootstrap not found in ./src/.././src/app/app.browser.module.ts

I'm sorry for my bad english.
my fault is that when I want to seo the joints in the module.browser class bootstrap does not appear
app.browser.module.ts;
import { AppComponent } from './app.component';
import { AppModule } from './app.module';
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
#NgModule({
bootstrap: [
AppComponent
],
imports:[
BrowserModule.withServerTransition({appId: 'app-root'}),
AppModule,
]
})
export class AppBrowserModule {}
my bad eror
D:\çalışmalar\code\myWebSite>ng add #ng-toolkit/universal
Installing packages for tooling via npm.
INFO: Project property is set to 'myWebSite'.
ERROR: Bootstrap not found in ./src/.././src/app/app.browser.module.ts.
ERROR: If you think that this error shouldn't occur, please fill up bug report here: https://github.com/maciejtreder/ng-toolkit/issues/new
INFO: stacktrace has been sent to tracking system.
Nothing to be done.
help me please
After running once ng add #ng-toolkit/universal we got our initial files generated and retrieved this error.
For me this solution worked:
Delete app.browser.module.ts
In main.ts you need to insert AppModule (instead of AppBrowserModule) in the .bootstrapModule() function.
Now your main.ts looks like this:
import { AppBrowserModule } from '.././src/app/app.browser.module';
import { enableProdMode } from '#angular/core';
import { platformBrowserDynamic } from '#angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
if (environment.production) {
enableProdMode();
}
document.addEventListener('DOMContentLoaded', () => {
platformBrowserDynamic()
.bootstrapModule(AppModule)
.catch(err => console.log(err));
});
Add bootstrap: [AppComponent] to your app.module.ts #NgModule configuration
Run ng add #ng-toolkit/universal
This will run through successfully but ng-toolkit will leave an invalid line in app.module.ts .withServerTransition({appId:''}), which you can simply delete. Afterwards you can run ng run build:prod and deploy.
If this retrieved an error check if bootstrap: [AppComponent] exists in your app.module.ts and run ng run build:prod again.
You should check where you included Bootstrap.
ERROR: Bootstrap not found in ./src/.././src/app/app.browser.module.ts.
This error points that, it can not find the right path.

Import library into Angular2/WebPack project without NPM

I'm completely new to Angular2 and WebPack and am struggling with something probably very simple.
We're trying to incorporate yFiles for HTML into an Agular2/WebPack project. I've found and imported the types file on NPM at #types/yfiles. The rest of the library is only available from the vendor, not on NPM. This compiles correctly, but when I debug the project, the console reports the error:
EXCEPTION: Uncaught (in promise): Error: Error in ./HomeComponent class HomeComponent - inline template:0:0 caused by: yfiles is not defined
Error: Error in ./HomeComponent class HomeComponent - inline template:0:0 caused by: yfiles is not defined
It's not the HomeComponent so much as the DiagramComponent it references that's having the problem.
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'fs-diagram',
templateUrl: './diagram.component.html',
styleUrls: ['./diagram.component.scss']
})
export class DiagramComponent implements OnInit {
private canvas: yfiles.view.CanvasComponent;
constructor() {
this.canvas = new yfiles.view.CanvasComponent();
}
ngOnInit() { }
}
The folder structure looks like this:
> root
> .vscode
> node_modules
▼ src
> app
▼ lib
▼ yfiles
> impl
*.js
yfiles.css
> public
> style
main.ts
polyfill.ts
vendor.ts
npm-shrinkwrap.json
package.json
protractor.conf.js
tsconfig.json
tslint.json
typedoc.json
webpack.config.js
I get the feeling that the even though the #types/yfiles/index.d.ts file is present, it's looking for the *.js files at run time. Is that the problem, and if so, how do I import them into the project?
In order to have webpack include the yFiles modules in the bundle, they will indeed have to be imported in your Typescript file:
import yfiles = require("yfiles/view");
To make this work, webpack also needs to be told where the modules can be found - with webpack 2.x, this can be specified using the resolve.modules config in webpack.config.js:
module.exports = {
entry: "./src/index.ts",
output: {
filename: "dist/bundle.js"
},
resolve: {
extensions: [".ts", ".tsx", ".js"],
modules: ["./lib"] // the lib folder containing the yFiles modules
},
module: {
loaders: [
{ test: /\.tsx?$/, loader: "ts-loader" }
]
}
};

Using relative path for templateUrl in Angular2+Webpack

import {Component} from 'angular2/core';
#Component({
selector: 'app',
styleUrls: ['./app.component.less'],
templateUrl: './app.component.html'
})
export class AppComponent {
name:string = 'Demo'
}
When using the relative path for templateUrl and styleUrls, I get: error 404, file not found:
zone.js: 101 GET http://localhost/app.component.html 404 (Not Found)
code: https://github.com/Dreampie/angular2-demo
I think this is not good design,because under different circumstances may build directory is not the same, can I change it to relative current path?
raw-loader can resolve this,but html-loader,less-loader not work for template,styles,it only work in string,so why not suport them?
import {Component} from 'angular2/core';
#Component({
selector: 'app',
styles: [require('./app.component.less')],
template: require('./app.component.html')
})
export class AppComponent {
name:string = 'Demo'
}
get other error:
browser_adapter.js:77 EXCEPTION: Error during instantiation of Token Promise<ComponentRef>!.BrowserDomAdapter.logError
browser_adapter.js:77 ORIGINAL EXCEPTION: Expected 'styles' to be an array of strings.
Let me add some more information.
Why can't Angular calculate the HTML and CSS URLs from the component file's location?
Unfortunately, that location is not readily known. Angular apps can be loaded in many ways: from individual files, from SystemJS bundles, or from CommonJS bundles, to name a few. With this diversity of load strategies, it's not easy to tell at runtime where these files actually reside.
The only location Angular can be sure of is the URL of the index.html home page. So by default it resolves template and style paths relative to the URL of index.html. That's why we previously wrote our CSS file URLs with an app/ base path prefix.
Official Angular Docu
The ./ (single dot) notation works for ts paths only, it doesn't work with html or css paths.
These paths are relative to index.html, so according to your file structure, this should work
#Component({
selector: 'app',
styleUrls: ['app.component.less'],
templateUrl: 'app.component.html'
})
You need to try
#Component({
selector: 'app',
template: require('./app.component.html'),
styles: [
require('./app.component.less').toString()
or
String(require('./app.component.less'))
or
add css-to-string in your webpack conf ({test: /\.css$/, loaders: ['css-to-string', 'style', 'css']})
})
Set the moduleId property to module.id for module-relative loading, so that urls are relative to the component.
#Component({
moduleId: module.id,
selector: 'app',
styleUrls: ['app.component.less'],
templateUrl: 'app.component.html'
})
If you are using SystemJS for example, see my answer here: https://stackoverflow.com/a/40694657/986160
You can use model.id and convert it from your build path (that with the js) to the one with ts,css and html. That way you can use relative paths for your templates and styles in Angular 2 no problem
#Component({
moduleId: module.id.replace("/dist/", "/"),
...
});
I have noticed the same error in my case. The reason of
Expected 'styles' to be an array of strings
in my case was css-loader which was used for loading CSS files and piped to angular2-template-loader.
What I understood from debugging that css-loader has some "smart" detection of changes in CSS files and if nothing were changed CSS file just wasn't exported as a string by webpack module.
As it was just hello word app my solution was very simple: replace css-loader by raw-loader. It is my version of loaders:
loaders: [
{
include: [srcPath],
test: /\.js$/,
loader: 'babel',
query: {
presets: ['es2015']
}
},
{
include: [srcPath],
test: /\.js$/,
loader: 'angular2-template-loader',
query: {
keepUrl: true
}
},
{
include: [srcPath],
test: /\.(html|css)$/,
loader: 'raw',
query: {
minimize: true
}
}
]
WebPack2 do not require this moduleId anymore

Resources