Cannot find module environment when running in server side with Angular Universal
Asked Answered
S

11

9

I have a simple Angular 4 app that I want to run in server side with Angular Universal (nodeJs server side rendering). I followed these steps to configure the Angular Universal with the angular-cli help and it's all good until I try to use the angular environment. When I try to access a property within the environment constant it works perfectly being rendered in client side (with ng serve) but in server side (ts-node src/server.ts) it throws the following error:

Error: Cannot find module 'environments/environment'
    at Function.Module._resolveFilename (module.js:470:15)
    at Function.Module._load (module.js:418:25)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (C:\Dev\code-carama\src\app\auth.service.ts:3:1)
    at Module._compile (module.js:571:32)
    at Module.m._compile (C:\Dev\code-carama\node_modules\ts-node\src\index.ts:385:23)
    at Module._extensions..js (module.js:580:10)
    at Object.require.extensions.(anonymous function) [as .ts] (C:\Dev\code-carama\node_modules\ts-node\src\index.ts:388:12)
    at Module.load (module.js:488:32)

npm ERR! Windows_NT 10.0.14393
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "start"
npm ERR! node v7.10.0
npm ERR! npm  v4.2.0
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: `ts-node src/server.ts`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] start script 'ts-node src/server.ts'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the code-carama package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     ts-node src/server.ts
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs code-carama
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls code-carama
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     C:\Users\dima\AppData\Roaming\npm-cache\_logs\2017-06-05T12_00_03_595Z-debug.log

This is my server.ts:

import 'reflect-metadata';
import 'zone.js/dist/zone-node';
import { platformServer, renderModuleFactory } from '@angular/platform-server';
import { enableProdMode } from '@angular/core';
import { AppServerModuleNgFactory } from '../dist/ngfactory/src/app/app.server.module.ngfactory';
import * as express from 'express';
import { readFileSync } from 'fs';
import { join } from 'path';

const PORT = 4000;

enableProdMode();

const app = express();

let template = readFileSync(join(__dirname, '..', 'dist', 'index.html')).toString();

app.engine('html', (_, options, callback) => {
  const opts = { document: template, url: options.req.url };

  //it serves html from the compiled angular app from the server
  renderModuleFactory(AppServerModuleNgFactory, opts)
    .then(html => callback(null, html));
});

app.set('view engine', 'html');
app.set('views', 'src')

app.get('*.*', express.static(join(__dirname, '..', 'dist')));

app.get('*', (req, res) => {
  res.render('index', { req });
});

app.listen(PORT, () => {
  console.log(`listening on http://localhost:${PORT}!`);
});

And the simple service trying to access environment variables is the auth.service.ts:

import { Injectable } from '@angular/core';
import { environment } from 'environments/environment';

@Injectable()
export class AuthService {

  private userManager = null;
  constructor() { 
    console.log('AuthService instantiated in environment ' + environment.envName); //this will fail in server-side rendering
  }
}

Any idea what's going with nodeJs (or angular universal) not to find that environment module?

Thanks

Singhalese answered 5/6, 2017 at 12:8 Comment(0)
P
11

In projects Angular6 change 'environments/environment' by 'src/environments/environment'

Pelias answered 9/6, 2018 at 15:23 Comment(1)
worked for me in Angular 7 (project migrated from Angular 6). I'm new to AngularLowther
S
9

Never mind, it seems the problem is that although for client side rendering the line:

import { environment } from 'environments/environment';

works well, for server side rendering the line must be:

import { environment } from '../environments/environment';

and by the way, I don't know why but by default for server-side rendering it will pick the PROD environment file.

on console: AuthService instantiated in environment prod

Singhalese answered 5/6, 2017 at 12:36 Comment(0)
V
6

try to execute this commande npm run env and then execute ng serve. It's work with me

Valeta answered 7/10, 2018 at 12:33 Comment(0)
E
1

app.module.ts

Add this line:

import { environment } from '../environments/environment';
Expressionism answered 27/7, 2020 at 1:28 Comment(0)
L
1

On Angular 15 the environment folder has been removed, but there is a solution released on version 15.1 to generate the folder:

ng generate environments

it will create src/environments/environment.ts and src/environments/environment.development.ts then inside your service or component import it as:

import { environment } from 'src/environments/environment';

and then you can use it like:

baseUrl: string = environment.baseUrl;
Lavery answered 3/8, 2023 at 7:57 Comment(0)
H
0

In your environment.ts add the following:

 export const environment = {
    production: false
 };
Halliard answered 4/2, 2022 at 20:56 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Earmuff
T
0

You just need to find the location of your environment.ts file.

With angular 14:

If you have your ts file here:

src\app\auth\reducers\index.ts

The answer is:

import { environment } from '../../../environments/environment';
Therapeutic answered 16/9, 2022 at 20:15 Comment(0)
P
0

Can you see environments folder in src folder?

And then, can you see environment.ts and environment.prod.ts on there?

If so, based on your depiction of the filesystem, you need to go back up one more level.

import { environment } from '../../environments/environment';
Pigmy answered 26/12, 2022 at 11:42 Comment(0)
S
0

First of all create environments directory. After that create environment.ts file with firebaseConfig (in my case). The key is call with double (../../) this line:

import { environment } from '../../src/environments/environment';
Skipjack answered 20/9, 2023 at 23:19 Comment(0)
S
-1

For me, some of build variants dev and prod were having some different const name

export const AppConfig {

instead of

export const environment {

Sulla answered 29/10, 2020 at 15:8 Comment(0)
B
-1

Check that you do not have it ignored in the .gitignore

Blanka answered 11/1, 2022 at 8:44 Comment(1)
What does .gitignore have to do with this?Dasheen

© 2022 - 2025 — McMap. All rights reserved.