Angular 9 universal why only half app is translated with ngx-translate? - node.js

I have angular 9 pwa universal web app which after npm run build:ssr works with node dist/app/server/server.js. I translated all text , but after build I see only half translated and another half like : common.next , common.back.
Here is what i have :
app.module :
export function createTranslateLoader(http: HttpClient) {
return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}
imports: [
...
TransferHttpCacheModule,
HttpClientModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: (createTranslateLoader),
deps: [HttpClient]
}
}),
...
]
app.server.module :
import { NgModule } from '#angular/core';
import { ServerModule, ServerTransferStateModule } from '#angular/platform-server';
import { BrowserModule } from '#angular/platform-browser';
import { AppModule } from './app.module';
import { AppComponent } from './app.component';
#NgModule({
imports: [
AppModule,
ServerModule,
ServerTransferStateModule,
BrowserModule.withServerTransition({ appId: 'autorent' }),
],
bootstrap: [AppComponent],
})
export class AppServerModule { }
app.browser.module :
import { NgModule } from '#angular/core';
import { BrowserModule, BrowserTransferStateModule } from '#angular/platform-browser';
import { AppModule } from './app.module';
import { AppComponent } from './app.component';
import { ServiceWorkerModule } from '#angular/service-worker';
import { environment } from '../environments/environment';
import { BrowserAnimationsModule } from '#angular/platform-browser/animations';
#NgModule({
imports: [
AppModule,
BrowserModule.withServerTransition({ appId: 'autorent' }),
BrowserTransferStateModule,
ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production }),
BrowserAnimationsModule
],
bootstrap: [AppComponent],
})
export class AppBrowserModule { }
If you need another info, which I doubt, just write in comments and I will provide.
How to make that ngx-translate would work fully + won't be loaded on page load, It should lode on server I think, because when I open app for the first time, i see how text changes (half of it)

As you use separate translation files and load them after the code (TranslateHttpLoader(http, './assets/i18n/', '.json');) this json file is cached by the browser. As you're not using content hashes there, it is likely that a newer version of you code is getting older translation files from the browser cache. (You can verify this with the chrome dev tools, there is a disable cache checkbox)
You have several options there:
Delete your browser cache and tell your users to do the same after every redeploy
Configure the web server to serve the translation file with a very short cache lifetime
Use some kind of content-hashing where the requested resource is different after a redeploy so that the browser cache does not hit if the file has changed. (for example, modify your build process so that the filename ends like .json?67d383 where the last part is replaced at build time with the git commit hash of the code that was build)
compile the translation into the javascript bundle
I have used options 1, 3 and 4 and recommend the last (for applications with little different locales). The javascript bundle cannot display anything meaningful without the translations, so it might as well include them.
You can directly include the json files for all the languages into the typescript file and use them as a constant. Switch as needed, as any loading of translations will be immediate (no http call) and the translations will always be accurate. Content hashing should be configured for the javascript bundle already (by default).
If you have many languages, I'd rather move towards approach 3 for bundle size.

Related

Strict mode code may not include a with statement

I got an error Strict mode code may not include a with statement in Angular 12 with universal when building the server bundle.
I removed this line export { renderModule, renderModuleFactory } from '#angular/platform-server'; as suggested here and here but the issue occures only when I add ServerModule to imports array
#NgModule({
imports: [/*AppModule,*/ ServerModule],
// bootstrap: [AppComponent],
})
export class AppServerModule {}
// export { renderModule, renderModuleFactory } from '#angular/platform-server';
when removing ServerModule the build executed successfully

Angular NPM package using after publishing

I build an npm package as a test to see how it works. So far it worked, I could build it (--prod) and publish it to a registry. Just one question, if I want to use it in a different project I can include the Module of my npm package which is published and it will be shown in my project.
My Module consists of a few components (ts and HTML) how do I do that if I only want to use one component? So install everything but only use one of them through the selector? For example Angular packages like routing you can do something like this
"" this is what I want to do too.
My module.ts of npm package
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { RouterModule } from '#angular/router';
import { ShowTitleComponent } from './show-title/show-title.component';
import { MypageComponent } from './mypage/mypage.component';
import { MyCounterComponent } from './my-counter/my-counter.component';
import { MyTitleComponent } from './my-title/my-title.component';
#NgModule({
imports: [
CommonModule,
RouterModule.forChild([
{path: '', pathMatch: 'full', component: MypageComponent}
]),
],
declarations: [ShowTitleComponent, MypageComponent, MyCounterComponent, MyTitleComponent]
})
export class MyuiModule {}
And say I want to install everything but only use ShowtitleComponent, how do I do this? If I import my module in new project everything is shown.

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.

unexpected token import when use localize-router in Angular 4 Universal app

I try to build Angular 4 app with server rendering side and language route path. All this base on Angular CLI in 1.5.0-rc1 version.
Everything work OK but I can't solve a problem with language in route.
I have two idea - one to make it like a parameter :lang in URL, but everywhere people advice me to use localize-router plugin. It look very good, but my npm run server can't start properly. In console I get an error:
/home/xxx/Projects/private/angular4-cli-seed/node_modules/localize-router/src/localize-router.config.js:1
(function (exports, require, module, __filename, __dirname) { import { Inject, OpaqueToken } from '#angular/core';
Here is my app-routing.module.ts:
import {NgModule, PLATFORM_ID, Inject, OpaqueToken} from '#angular/core';
import 'zone.js';
import 'reflect-metadata';
import { Routes, RouterModule } from '#angular/router';
import {AboutComponent} from './about/about.component';
import {HomeComponent} from './home/home.component';
import {LocalizeParser, LocalizeRouterModule, LocalizeRouterSettings, ManualParserLoader} from 'localize-router';
import {HttpClientModule, HttpClient} from '#angular/common/http';
import {TranslateService} from '#ngx-translate/core';
import { Observable } from 'rxjs/Observable';
import { Location } from '#angular/common';
const routes: Routes = [
{
path: '',
component: HomeComponent
},
{
path: 'about',
component: AboutComponent
}
];
export function localizeFactory(translate: TranslateService, location: Location, settings: LocalizeRouterSettings): LocalizeParser {
const browserLocalizeLoader = new ManualParserLoader(translate, location, settings, ['en', 'pl'], 'pl');
return browserLocalizeLoader;
}
#NgModule({
imports: [
RouterModule.forRoot(routes),
LocalizeRouterModule.forRoot(routes, {
parser: {
provide: LocalizeParser,
useFactory: (localizeFactory),
deps: [TranslateService, Location, LocalizeRouterSettings, HttpClient]
}
}),
],
exports: [RouterModule]
})
export class AppRoutingModule {
private static TranslateService: any;
}
Do you have any tips how can I solve it? I found some tips for Webpack (to use exclude list), but I want to use CLI because I don't know Webpack too well.
This problem is connected with library type - it's not a commonjs type, but ES6. More about this problem you can read here on GitHub.
To solve it you can contact the author of library what you want to use in Angular 4 Universal (with Angular CLI). They should recompile it in a proper way.
Another solution (more quick to realize) give me a #sjogren on GitHub. You can use babel.js to recompile library during a building process. To do this you should run:
npm install babel-cli --save
npm install babel-preset-env --save
npm install babel-preset-es2015 --save
and add this code in package.json:
"babel": {
"presets": [
"es2015"
]
},
Finally in package.json you should add to your scripts prestart script with code to recompile the library. In my example:
"scripts": {
"prestart": "node node_modules/babel-cli/bin/babel.js node_modules/localize-router --out-dir node_modules/localize-router --presets es2015"
"start": "......"
}
This worked fine for me, and I don't have an Unexpected Token Import error.

Resources