Uncaught in promise error cannot find module

I'm trying to lazy load Angular 2 modules with the router, and I'm having this error: error_handler.js:50 EXCEPTION: Uncaught (in promise): Error: Cannot find module 'app/home/home.module' I tr...

I’m trying to lazy load Angular 2 modules with the router, and I’m having this error:

error_handler.js:50 EXCEPTION: Uncaught (in promise): Error: Cannot find module ‘app/home/home.module’

I tried all the answers that seems to be working for the others, like this one which seems to be a solution for everybody facing this issue, but doesn’t work with me Lazy loading in Angular2 RC7 and angular-cli webpack

here is my code:app.module

import { MediatorService } from './home/mediator.service';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';


import appRoutes from "./app.routes";


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    appRoutes
  ],
  providers: [MediatorService],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.routes

import { RouterModule } from '@angular/router';

const routes = [
 {path : '', loadChildren: './home/home.module#HomeModule'},
 {path: 'devis', loadChildren: './forms/forms.module#FormsModule'}
];

export default RouterModule.forRoot(routes);

home.module

import {NgModule} from "@angular/core";
import {CommonModule} from "@angular/common";
import homeRoutes from "./home.routes";

@NgModule({
  imports:[CommonModule, homeRoutes],
  declarations: [HomeComponent]
})
export default class HomeModule{}

home.routes

import {RouterModule} from "@angular/router";
import {HomeComponent} from "./home.component";
const routes = [
  {path: '', component: HomeComponent}
];

export default RouterModule.forChild(routes);

Package.json

{
  "name": "insurance",
  "version": "0.0.0",
  "license": "MIT",
  "angular-cli": {},
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "lint": "tslint "src/**/*.ts"",
    "test": "ng test",
    "pree2e": "webdriver-manager update --standalone false --gecko false",
    "e2e": "protractor"
  },
  "private": true,
  "dependencies": {
    "@angular/common": "^2.3.1",
    "@angular/compiler": "^2.3.1",
    "@angular/core": "^2.3.1",
    "@angular/forms": "^2.3.1",
    "@angular/http": "^2.3.1",
    "@angular/platform-browser": "^2.3.1",
    "@angular/platform-browser-dynamic": "^2.3.1",
    "@angular/router": "^3.3.1",
    "bootstrap": "^4.0.0-alpha.5",
    "core-js": "^2.4.1",
    "font-awesome": "^4.7.0",
    "rxjs": "^5.0.1",
    "ts-helpers": "^1.1.1",
    "zone.js": "^0.7.2"
   },
  "devDependencies": {
    "@angular/compiler-cli": "^2.3.1",
    "@types/jasmine": "2.5.38",
    "@types/jquery": "^2.0.34",
    "@types/node": "^6.0.42",
    "angular-cli": "1.0.0-beta.24",
    "codelyzer": "~2.0.0-beta.1",
    "jasmine-core": "2.5.2",
    "jasmine-spec-reporter": "2.5.0",
    "karma": "1.2.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-cli": "^1.0.1",
    "karma-jasmine": "^1.0.2",
    "karma-remap-istanbul": "^0.2.1",
    "protractor": "~4.0.13",
    "ts-node": "1.2.1",
    "tslint": "^4.0.2",
    "typescript": "~2.0.3"
  }
}

UPDATE

I managed to make it work on plunker

https://plnkr.co/edit/uLxmxDIeCdDzxbFjYQS7?p=preview

but still nothing on my machine !!!!

UPDATE

I installed a new virtual machine ubuntu 16.04
and I have the same problem! Could it be because of the versions of the modules, I mean those on package.json? How can I find out the versions used in plunker because it worked on there.

There’s CSS methodologies to help use write such as SMACSS or Atomic, one we’re going to look at today is Block Element Module


Ash Grennan


Oct 28, 2019



2 min read

This is a quick post on an error I encountered whilst opting into the Ivy compiler (which should be here Nov 2019).

Once you get through the initial errors, you may see the below in your console log:

core.js:6014 ERROR Error: Uncaught (in promise): Error: Cannot find module 'src/app/modules/module/your-module.module'
Error: Cannot find module 'src/app/modules/module/your-module.module'
    at $_lazy_route_resource lazy namespace object:5
    at ZoneDelegate.invoke (zone-evergreen.js:365)
    at Object.onInvoke (core.js:39707)
    at ZoneDelegate.invoke (zone-evergreen.js:364)
    at Zone.run (zone-evergreen.js:124)
    at zone-evergreen.js:851
    at ZoneDelegate.invokeTask (zone-evergreen.js:400)
    at Object.onInvokeTask (core.js:39688)
    at ZoneDelegate.invokeTask (zone-evergreen.js:399)
    at Zone.runTask (zone-evergreen.js:168)
    at resolvePromise (zone-evergreen.js:793)
    at resolvePromise (zone-evergreen.js:752)
    at zone-evergreen.js:854
    at ZoneDelegate.invokeTask (zone-evergreen.js:400)
    at Object.onInvokeTask (core.js:39688)
    at ZoneDelegate.invokeTask (zone-evergreen.js:399)
    at Zone.runTask (zone-evergreen.js:168)
    at drainMicroTaskQueue (zone-evergreen.js:570)
    at ZoneTask.invokeTask [as invoke] (zone-evergreen.js:485)
    at invokeTask (zone-evergreen.js:1596)

You’re getting this error due to Angular 8 introduced a new recommended module loading method, previously the default method of lazy loading modules was to specify a string path to a module:

{path: '/admin', loadChildren: './admin/admin.module#AdminModule'}

This was something built into the Angular toolchain, and performed some wizardry to parse and load the module from the loadChildren attribute.

Since Angular 8, the method of importing modules has changed to the industry recognised / standard, dynamic import. So your import should now be changed to:

loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule)

Depending upon your IDE choice, you’ll likely also get Intellisense too:

Ash Grennan

Ash Grennan
Snr Software Engineer

Deliver value first, empower teams to make technical decisions. Snr Engineer @ Moonpig, hold a BSc & MSc in software engineering & certified AWS Solutions Architect (LinkedIn). A fan of Serverless computing, distributed systems, and anything published by serverless.com 🧡

Related

  • Micro Multi Tenanted Value Resolver Library 📚
  • Image Mutation Pipeline — Reshaping and Overlay Images
  • Broadcast data strategy with .NET Core, SignalR & Angular
  • EF Core – Seed Data Strategy
  • Fixing MSBuild CS103, CS012 Compiler Errors

Содержание

  1. Search
  2. Related
  3. ERROR < Error: Uncaught (in promise): Error: Cannot find module «./. /.module.ngfactory». #1862
  4. Comments
  5. Version info
  6. How to reproduce these conditions
  7. Debug output
  8. Expected behavior
  9. Actual behavior
  10. Runtime Error Uncaught (in promise): Error: Cannot find module «./pages/login» #6139
  11. Comments
  12. APP.Module
  13. app.component
  14. Uncaught (in promise) Error: Cannot find module ‘../node_modules/string_decoder/index.js’ #17125
  15. Comments
  16. Prerequisites
  17. Description
  18. Steps to Reproduce
  19. Versions
  20. Additional Information
  21. App-shell + ssr + lazy loading throw error Cannot find module #12921
  22. Comments
  23. Bug Report or Feature Request (mark with an x )
  24. Command (mark with an x )
  25. Versions
  26. Repro steps
  27. The log given by the failure
  28. Desired functionality
  29. Mention any other details that might be useful

Search

There’s CSS methodologies to help use write such as SMACSS or Atomic, one we’re going to look at today is Block Element Module

This is a quick post on an error I encountered whilst opting into the Ivy compiler (which should be here Nov 2019).

Once you get through the initial errors, you may see the below in your console log:

You’re getting this error due to Angular 8 introduced a new recommended module loading method, previously the default method of lazy loading modules was to specify a string path to a module:

This was something built into the Angular toolchain, and performed some wizardry to parse and load the module from the loadChildren attribute.

Since Angular 8, the method of importing modules has changed to the industry recognised / standard, dynamic import. So your import should now be changed to:

loadChildren: () => import(‘./admin/admin.module’).then(m => m.AdminModule)

Depending upon your IDE choice, you’ll likely also get Intellisense too:

Ash Grennan
Snr Software Engineer

Deliver value first, empower teams to make technical decisions. Snr Engineer @ Moonpig, hold a BSc & MSc in software engineering & certified AWS Solutions Architect (LinkedIn). A fan of Serverless computing, distributed systems, and anything published by serverless.com 🧡

Copyright 2021 Ash Grennan | Information provided is published and reviewed according to the latest literature and is for general information purpose only

Published with Wowchemy — the free, open source website builder that empowers creators.

Источник

ERROR < Error: Uncaught (in promise): Error: Cannot find module «./. /.module.ngfactory». #1862

Version info

Angular: 6.0

Firebase: 5.4.2

AngularFire: 5.0.0-rc.7

Other (e.g. Ionic/Cordova, Node, browser, operating system):
«rxjs»: «^6.3.2»,
«rxjs-compat»: «^6.3.2»,
«sweetalert2»: «^7.26.28»,
«zone.js»: «^0.8.26»

devDependencies:
«typescript»: «^2.9.2»,
«webpack-cli»: «^3.1.0»,
«ws»: «^6.0.0»,
«xmlhttprequest»: «^1.8.0»

How to reproduce these conditions

Failing test unit, Plunkr, or JSFiddle demonstrating the problem

I followed the steps of Server-side Rendering with Universal published in your documentation:
https://github.com/angular/angularfire2/blob/master/docs/server-side-rendering.md
I achieved to compile the whole application without errors but when I was running the application I got the following error:

Steps to set up and reproduce

I created a repository for you so that you can reproduce this error that I commented to you before:
https://github.com/IngAjVillalon/Angular-Universal-6-Server-Side-Render
You can execute:
npm install
later
npm run build: ssr && npm run serve: ssr.
and the application will run fine, but when using the application the error appears.

Sample data and security rules

Debug output

** Errors in the JavaScript console **

** Output from firebase.database().enableLogging(true); **

Expected behavior

Actual behavior

The text was updated successfully, but these errors were encountered:

Источник

Runtime Error Uncaught (in promise): Error: Cannot find module «./pages/login» #6139

I am new to ionic . Have been trying using Lazy module. I tried all the solution given , still i am getting the same error. I have been sitting with this error for 2 days. Please let me know where i am making mistake.

Runtime Error
Uncaught (in promise): Error: Cannot find module «./pages/login» Error: Cannot find module «./pages/login» at d (http://localhost:8100/build/polyfills.js:3:3991) at Object.261

Ionic Framework: 3.1.1
Ionic App Scripts: 1.3.6
Angular Core: 4.0.2
Angular Compiler CLI: 4.0.2
Node: 7.4.0
OS Platform: Windows 8.1
Navigator Platform: Win32
User Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36

APP.Module

app.component

Login.Module

Providers

If i tried changing the root page in app.component to any other page like RegisterPage or HomePage i am getting cannot find module for that particular Page.

The text was updated successfully, but these errors were encountered:

Источник

Uncaught (in promise) Error: Cannot find module ‘../node_modules/string_decoder/index.js’ #17125

Prerequisites

  • Put an X between the brackets on this line if you have done all of the following:
    • Reproduced the problem in Safe Mode: https://flight-manual.atom.io/hacking-atom/sections/debugging/#using-safe-mode
    • Followed all applicable steps in the debugging guide: https://flight-manual.atom.io/hacking-atom/sections/debugging/
    • Checked the FAQs on the message board for common solutions: https://discuss.atom.io/c/faq
    • Checked that your issue isn’t already filed: https://github.com/issues?utf8=✓&q=is%3Aissue+user%3Aatom
    • Checked that there is not already an Atom package that provides the described functionality: https://atom.io/packages

Description

When the github package starts up its filesystem watcher the following stack trace is thrown to the console:

Steps to Reproduce

  1. Enable «Filesystem Event Diagnostics» in the github package
  2. Open a project folder that contains a git repository
  3. Open the console and see the errors when the fs watcher starts up

Expected behavior: [What you expect to happen]

Actual behavior: [What actually happens]

Reproduces how often: [What percentage of the time does it reproduce?]

100% of the time.

Note that if the github package’s fs watcher doesn’t initialize, this doesn’t show normally.

Versions

This started happening on builds after 553dec3.

Seen on both Windows (10 x64 Enterprise) and macOS builds.

Additional Information

The changes to text-buffer brought in by that commit can be found here: atom/text-buffer@v13.12.4. v13.13.0. The suspicious commit being merging atom/text-buffer#280 as it introduced cpy-cli as a direct dependency instead of a devDependency as it should have been. That package has string_decoder as a dependency, and although string_decoder was already in the tree that PR moved it from a devDependency to a regular dependency .

I believe that atom/text-buffer#296 will fix it, but have been unable to test without a version of text-buffer on NPM that includes it.

The text was updated successfully, but these errors were encountered:

Источник

App-shell + ssr + lazy loading throw error Cannot find module #12921

Bug Report or Feature Request (mark with an x )

Command (mark with an x )

Versions

Repro steps

create a module with route and configure it for lazy loading. Compile and try request the page point to this module. The server will throw a error. Here is a repo:
https://github.com/csbenjamin/app-shell-plus-univeral-plus-lazy-routing

The log given by the failure

Desired functionality

Mention any other details that might be useful

It seams related to #9202

The text was updated successfully, but these errors were encountered:

@csbenjamin thank you for the reproduction, this will be super helpful to get down debugging the issue straight away.

The problem seems to be that NgModuleFactoryLoader is not using ModuleMapNgFactoryLoader that is being defined in https://github.com/csbenjamin/app-shell-plus-univeral-plus-lazy-routing/blob/b7f95b689336cbb47cd476cd688a7ecf497da632/server.ts#L31-L38, but rather still using the SystemJsNgModuleLoader instead.

@vikerman, any idea why the application still uses the default providers instead of the once configured with ngExpressEngine in the server files?, Is this by design or a bug?

Also previously, with Angular 6 there was another workaround which was to configure the NgModuleFactoryLoader provider in the AppServerModule .

However this cannot be done in Angular 7 as MODULE_MAP is not an optional provider, and will cause a build error. StaticInjectorError(AppServerModule)[NgModuleFactoryLoader -> InjectionToken MODULE_MAP]:

After some more debugging I found a couple of more issues.

Using ModuleMapLoaderModule with the app-shell builder will cause a build error due to the above.

Providers configured in server.ts are not overriding the NgModuleFactoryLoader that was configured to use SystemJsNgModuleLoader when calling the Router.forRoot In app.server.module .

Thanks for this issue, I have been struggling with this aswell. In Angular 6, Universal/SSR + App-Shell always worked perfectly for me straight away, but ever since Angular 7 I have never fully got it to work.

If I have wildcard routes in my router, e.g. path: ‘**’ to catch wrong links and lazily-load a PageNotFound/404 module/component, it already fails when running

ng run my-app:app-shell

If I remove the wildcard route and just leave my normal routes, it builds fine, but I run into the well known

Источник

Version info

Angular: 6.0

Firebase: 5.4.2

AngularFire: 5.0.0-rc.7

Other (e.g. Ionic/Cordova, Node, browser, operating system):
«rxjs»: «^6.3.2»,
«rxjs-compat»: «^6.3.2»,
«sweetalert2»: «^7.26.28»,
«zone.js»: «^0.8.26»

devDependencies:
«typescript»: «^2.9.2»,
«webpack-cli»: «^3.1.0»,
«ws»: «^6.0.0»,
«xmlhttprequest»: «^1.8.0»

How to reproduce these conditions

Failing test unit, Plunkr, or JSFiddle demonstrating the problem

I followed the steps of Server-side Rendering with Universal published in your documentation:
https://github.com/angular/angularfire2/blob/master/docs/server-side-rendering.md
I achieved to compile the whole application without errors but when I was running the application I got the following error:

ERROR { Error: Uncaught (in promise): Error: Cannot find module "./views/sessions/sessions.module.ngfactory". Error: Cannot find module "./views/sessions/sessions.module.ngfactory". at eval (webpack:///./src_lazy_namespace_object?:5:11) at ZoneDelegate.invoke (webpack:///./node_modules/zone.js/dist/zone-node.js?:387:26) at Object.onInvoke (webpack:///./node_modules/@angular/core/fesm5/core.js?:4122:33) at ZoneDelegate.invoke (webpack:///./node_modules/zone.js/dist/zone-node.js?:386:32) at Zone.run (webpack:///./node_modules/zone.js/dist/zone-node.js?:137:43) at eval (webpack:///./node_modules/zone.js/dist/zone-node.js?:871:34) at ZoneDelegate.invokeTask (webpack:///./node_modules/zone.js/dist/zone-node.js?:420:31) at Object.onInvokeTask (webpack:///./node_modules/@angular/core/fesm5/core.js?:4113:33) at ZoneDelegate.invokeTask (webpack:///./node_modules/zone.js/dist/zone-node.js?:419:36) at Zone.runTask (webpack:///./node_modules/zone.js/dist/zone-node.js?:187:47) at resolvePromise (webpack:///./node_modules/zone.js/dist/zone-node.js?:813:31) at resolvePromise (webpack:///./node_modules/zone.js/dist/zone-node.js?:770:17) at eval (webpack:///./node_modules/zone.js/dist/zone-node.js?:872:17) at ZoneDelegate.invokeTask (webpack:///./node_modules/zone.js/dist/zone-node.js?:420:31) at Object.onInvokeTask (webpack:///./node_modules/@angular/core/fesm5/core.js?:4113:33) at ZoneDelegate.invokeTask (webpack:///./node_modules/zone.js/dist/zone-node.js?:419:36) at Zone.runTask (webpack:///./node_modules/zone.js/dist/zone-node.js?:187:47) at drainMicroTaskQueue (webpack:///./node_modules/zone.js/dist/zone-node.js?:594:35) at ZoneTask.invokeTask (webpack:///./node_modules/zone.js/dist/zone-node.js?:499:21) at Server.ZoneTask.invoke (webpack:///./node_modules/zone.js/dist/zone-node.js?:484:48) rejection: { Error: Cannot find module "./views/sessions/sessions.module.ngfactory". at eval (webpack:///./src_lazy_namespace_object?:5:11) at ZoneDelegate.invoke (webpack:///./node_modules/zone.js/dist/zone-node.js?:387:26) at Object.onInvoke (webpack:///./node_modules/@angular/core/fesm5/core.js?:4122:33) at ZoneDelegate.invoke (webpack:///./node_modules/zone.js/dist/zone-node.js?:386:32) at Zone.run (webpack:///./node_modules/zone.js/dist/zone-node.js?:137:43) at eval (webpack:///./node_modules/zone.js/dist/zone-node.js?:871:34) at ZoneDelegate.invokeTask (webpack:///./node_modules/zone.js/dist/zone-node.js?:420:31) at Object.onInvokeTask (webpack:///./node_modules/@angular/core/fesm5/core.js?:4113:33) at ZoneDelegate.invokeTask (webpack:///./node_modules/zone.js/dist/zone-node.js?:419:36) at Zone.runTask (webpack:///./node_modules/zone.js/dist/zone-node.js?:187:47) code: 'MODULE_NOT_FOUND' }, promise: ZoneAwarePromise { __zone_symbol__state: 0, __zone_symbol__value: { Error: Cannot find module "./views/sessions/sessions.module.ngfactory". at eval (webpack:///./src_lazy_namespace_object?:5:11) at ZoneDelegate.invoke (webpack:///./node_modules/zone.js/dist/zone-node.js?:387:26) at Object.onInvoke (webpack:///./node_modules/@angular/core/fesm5/core.js?:4122:33) at ZoneDelegate.invoke (webpack:///./node_modules/zone.js/dist/zone-node.js?:386:32) at Zone.run (webpack:///./node_modules/zone.js/dist/zone-node.js?:137:43) at eval (webpack:///./node_modules/zone.js/dist/zone-node.js?:871:34) at ZoneDelegate.invokeTask (webpack:///./node_modules/zone.js/dist/zone-node.js?:420:31) at Object.onInvokeTask (webpack:///./node_modules/@angular/core/fesm5/core.js?:4113:33) at ZoneDelegate.invokeTask (webpack:///./node_modules/zone.js/dist/zone-node.js?:419:36) at Zone.runTask (webpack:///./node_modules/zone.js/dist/zone-node.js?:187:47) code: 'MODULE_NOT_FOUND' } }, zone: Zone { _properties: { isAngularZone: true }, _parent: Zone { _properties: {}, _parent: null, _name: '<root>', _zoneDelegate: [Object] }, _name: 'angular', _zoneDelegate: ZoneDelegate { _taskCounts: [Object], zone: [Circular], _parentDelegate: [Object], _forkZS: null, _forkDlgt: null, _forkCurrZone: [Object], _interceptZS: null, _interceptDlgt: null, _interceptCurrZone: [Object], _invokeZS: [Object], _invokeDlgt: [Object], _invokeCurrZone: [Circular], _handleErrorZS: [Object], _handleErrorDlgt: [Object], _handleErrorCurrZone: [Circular], _scheduleTaskZS: [Object], _scheduleTaskDlgt: [Object], _scheduleTaskCurrZone: [Circular], _invokeTaskZS: [Object], _invokeTaskDlgt: [Object], _invokeTaskCurrZone: [Circular], _cancelTaskZS: [Object], _cancelTaskDlgt: [Object], _cancelTaskCurrZone: [Circular], _hasTaskZS: [Object], _hasTaskDlgt: [Object], _hasTaskDlgtOwner: [Circular], _hasTaskCurrZone: [Circular] } }, task: ZoneTask { _zone: Zone { _properties: [Object], _parent: [Object], _name: 'angular', _zoneDelegate: [Object] }, runCount: 0, _zoneDelegates: null, _state: 'notScheduled', type: 'microTask', source: 'Promise.then', data: ZoneAwarePromise { __zone_symbol__state: 0, __zone_symbol__value: [Object] }, scheduleFn: undefined, cancelFn: null, callback: [Function], invoke: [Function] } }
I was checking and the error is in the file webpack.server.config.js
With the WebPack plugIn new Webpack.ContextReplacementPlugin
It causes conflict with the aot lazy load.
Can you help me, please, by telling us what other alternatives we have to run the aot lazy load with Server-side Rendering with Universal?

Steps to set up and reproduce

I created a repository for you so that you can reproduce this error that I commented to you before:
https://github.com/IngAjVillalon/Angular-Universal-6-Server-Side-Render
You can execute:
npm install
later
npm run build: ssr && npm run serve: ssr.
and the application will run fine, but when using the application the error appears.

Sample data and security rules

<— include/attach/link to some json sample data (or provide credentials to a sanitized, test Firebase project) —>

Debug output

** Errors in the JavaScript console **

** Output from firebase.database().enableLogging(true); **

** Screenshots **

Expected behavior

Actual behavior

Answer by Amalia Richardson

Dealing with disagreeable students and not compromising

,As given in above code, If I comment out any 2 of 3 paths, Event, Ngo or Volunteer, routing is working good.,Asking for help, clarification, or responding to other answers.,Routing in my VolunteerModule

Renamed the sub folders of the features with a unique name, as follows:

▾ ngo/
  ▸ home/ --> nhome/
  ▸ past/ --> npast/
  ▸ upcoming/ --> nupcoming/
  ▸ volunteer/ --> nvolunteer/
    [  ]ngo.module.spec.ts
    [  ]ngo.module.ts
▸ tabs/
▾ volunteer/
  ▸ achievement/ --> vachievement/
  ▸ event/ --> vevent/
  ▸ home/ --> vhome/
    [  ]volunteer.module.spec.ts
    [  ]volunteer.module.ts
  [  ]app-routing.module.ts

Answer by Hugh Pena

Here is my tab routing module.ts:,Hello, I’ve been having troubles opening my default path in ionic. It opens sometimes but must times it does not.
I usually get an error: «ERROR Error: “Uncaught (in promise): Error: Cannot find module ‘…/home/home.module’”
Here is my app-routing.module.ts,

cancel selecting

Hello, I’ve been having troubles opening my default path in ionic. It opens sometimes but must times it does not.
I usually get an error: «ERROR Error: “Uncaught (in promise): Error: Cannot find module ‘…/home/home.module’”
Here is my app-routing.module.ts

import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';

const routes: Routes = [
  {
    path: '',
    loadChildren: () => import('./pages/tabs/tabs.module').then(m => m.TabsPageModule)
  },
  { path: 'about', loadChildren: './pages/about/about.module#AboutPageModule' },
  { path: 'credit', loadChildren: './pages/credit/credit.module#CreditPageModule' },
  { path: 'contact', loadChildren: './pages/contact/contact.module#ContactPageModule' },

];
@NgModule({
  imports: [
    RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
  ],
  exports: [RouterModule]
})
export class AppRoutingModule {}

Here is my tab routing module.ts:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { TabsPage } from './tabs.page';

const routes: Routes = [
  {
    path: 'tabs',
    component: TabsPage,
    children: [
      { path: 'home', loadChildren: '../home/home.module#HomePageModule' },
      { path: 'mobile', loadChildren: '../mobile/mobile.module#MobilePageModule' },
      { path: 'bank', loadChildren: '../bank/bank.module#BankPageModule' },
      { path: 'tv', loadChildren: '../tv/tv.module#TvPageModule' },
      { path: 'global', loadChildren: '../global/global.module#GlobalPageModule' },
      { path: 'utility', loadChildren: '../utility/utility.module#UtilityPageModule' },
    ]
  },
  { path: '', redirectTo: 'tabs/home', pathMatch: 'full'}
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class TabsPageRoutingModule {}


Answer by Kalani Adams

For now, let’s get back to our main goal of implementing navigation inside our app.,For now, let’s start with a blank Ionic 4 app so we can implement some navigation concepts. Go ahead and run:,The second button brings us back to the previous login page again by animating a complete exchange of pages.,Your routing should now look like this inside your app-routing.module.ts:

For now, let’s start with a blank Ionic 4 app so we can implement some navigation concepts. Go ahead and run:

npm install -g [email protected]
ionic start goFourIt blank 

To understand this we need to open our app/app-routing.module.ts in which we will find:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
 { path: '', redirectTo: 'home', pathMatch: 'full' },
 { path: 'home', loadChildren: () => import('./home/home.module').then(m => m.HomePageModule) },
];

@NgModule({
 imports: [RouterModule.forRoot(routes)],
 exports: [RouterModule]
})
export class AppRoutingModule { }

If you happen to inspect your index.html the only thing you’ll find is:

<body>
 <app-root></app-root>
</body>

The only thing we display is an app-root, which is still not very clear. This app root is replaced by the first real HTML of our app, which is always inside the app/app.component.html:

<ion-app>
 <ion-router-outlet></ion-router-outlet>
</ion-app>

Because a single page is not yet an app, we need more pages! To do so, you can use the Ionic CLI, which provides a wrapper for the Angular CLI. Right now, we could add 2 additional pages like this:

ionic g page pages/login
ionic g page pages/dashboard
ionic g page pages/details

Your routing should now look like this inside your app-routing.module.ts:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
 { path: '', redirectTo: 'login', pathMatch: 'full' },
 { path: 'login', loadChildren: () => import('./pages/login/login.module').then(m => m.LoginPageModule) },
 { path: 'dashboard', loadChildren: () => import('./pages/dashboard/dashboard.module').then(m => m.DashboardPageModule) },
 { path: 'details/:myid', loadChildren: () => import('./pages/details/details.module').then(m => m.DetailsPageModule) }
];

@NgModule({
 imports: [RouterModule.forRoot(routes)],
 exports: [RouterModule]
})
export class AppRoutingModule { }

All routing logic is officially in place, so now we only need to add a few buttons to our app that allow us to move around. Let’s start by adding a first button to our pages/login/login.page.html:

<ion-header>
 <ion-toolbar color="primary">
   <ion-title>Login</ion-title>
 </ion-toolbar>
</ion-header>

<ion-content padding>
 <ion-button expand="block" routerLink="/dashboard" routerDirection="root">
   Login
 </ion-button>
</ion-content>

If you want to animate forward or backward, you would use forward/back instead. This is what we can add now, because we are already able to move from login to our dashboard. So, let’s add the next two more buttons to the pages/dashboard/dashboard.page.html:

<ion-header>
 <ion-toolbar color="primary">
   <ion-title>Dashboard</ion-title>
 </ion-toolbar>
</ion-header>

<ion-content padding>
 <ion-button expand="block" routerLink="/details/42" routerDirection="forward">
   Details
 </ion-button>

 <ion-button expand="block" routerLink="/" routerDirection="root">
   Logout
 </ion-button>
</ion-content>

Of course, you can also dynamically add the ID for the details page or construct the link like this if you have a variable foo inside your class:

<ion-button expand="block" [routerLink]="['/details/', foo]" routerDirection="forward">

First things first, getting the value of the path is super easy. We can inject the ActivatedRoute and grab the value inside our pages/details/details.page.ts like this:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
 selector: 'app-details',
 templateUrl: './details.page.html',
 styleUrls: ['./details.page.scss'],
})
export class DetailsPage implements OnInit {

 myId = null;
  constructor(private activatedRoute: ActivatedRoute) { }

 ngOnInit() {
   this.myId = this.activatedRoute.snapshot.paramMap.get('myid');
 }

}

The markup for our pages/details/details.page.html looks now like this:

<ion-header>
 <ion-toolbar color="primary">
   <ion-buttons slot="start">
     <ion-back-button defaultHref="/dashboard"></ion-back-button>
   </ion-buttons>
   <ion-title>Details</ion-title>
 </ion-toolbar>
</ion-header>

<ion-content padding>
 My ID is: {{ myId }}
</ion-content>

We can create something called guard that checks a condition and returns true/false, which allows users to access that page or not. You can generate a guard inside your project with the Ionic CLI:

ionic g guard guards/auth

This generates a new file with the standard guard structure of Angular. Let’s edit guards/auth.guard.ts and change it’s content to:

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';

@Injectable({
 providedIn: 'root'
})
export class AuthGuard implements CanActivate {
 canActivate(
   next: ActivatedRouteSnapshot,
   state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

   let userAuthenticated = false; // Get the current authentication state from a Service!

   if (userAuthenticated) {
     return true;
   } else {
     return false;
   }
 }
}

By default this guard is not yet enabled, but now the circle closes as we come back to our initial app routing. So, open the app-routing.module.ts once again and change it to:

import { AuthGuard } from './guards/auth.guard';
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
 { path: '', redirectTo: 'login', pathMatch: 'full' },
 { path: 'login', loadChildren: () => import('./pages/login/login.module').then(m => m.LoginPageModule) },
 { path: 'dashboard', loadChildren: () => import('./pages/dashboard/dashboard.module').then(m => m.DashboardPageModule) },
 {
   path: 'details/:myid',
   loadChildren: () => import('./pages/details/details.module').then(m => m.DetailsPageModule),
   canActivate: [AuthGuard]
 }
];

@NgModule({
 imports: [RouterModule.forRoot(routes)],
 exports: [RouterModule]
})
export class AppRoutingModule { }

Answer by Noemi Miller

Im having a lot of issues with Ionic 4 and lazy loaded modules, for some reason it keeps reporting that the below login module cannot be found, if I edit the app-routing.module.ts file and save sometimes it finds it. anyone come across this issue yet and know how to fix ?,the full error in chrome is this:,Successfully merging a pull request may close this issue.,
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

error in app.module.ts Error: Uncaught (in promise): Error: Cannot find module './pages/auth/login/login.module'
Error: Cannot find module './pages/auth/login/login.module'

Answer by Samson Sampson

Я получаю эту ошибку в своей консоли javascript:
,
IONIC 4 + Angular7: ERROR Error: Uncaught (in promise): TypeError: не удается прочитать свойство ‘then’ undefined
,
Я новичок в Angular, и у меня возникли некоторые проблемы с обнаружением модулей в моем проекте. При запуске приложения я всегда получаю следующую ошибку: ERROR Error: Uncaught (in promise): Error:…
,
Angular 2 — Uncaught (in promise): Error: XHR error (404 не найден)

Я получаю эту ошибку в своей консоли javascript:

ERROR Error: "Uncaught (in promise): Error: Cannot find module '../home/home.module/'
webpackAsyncContext/<@http://localhost:8100/main.js:897:12
./node_modules/zone.js/dist/zone.js/</[email protected]://localhost:8100/polyfills.js:2710:17
[email protected]://localhost:8100/vendor.js:34941:24
./node_modules/zone.js/dist/zone.js/</[email protected]://localhost:8100/polyfills.js:2709:17
./node_modules/zone.js/dist/zone.js/</[email protected]://localhost:8100/polyfills.js:2460:24
scheduleResolveOrReject/<@http://localhost:8100/polyfills.js:3194:29
./node_modules/zone.js/dist/zone.js/</[email protected]://localhost:8100/polyfills.js:2743:17
[email protected]://localhost:8100/vendor.js:34932:24
./node_modules/zone.js/dist/zone.js/</[email protected]://localhost:8100/polyfills.js:2742:17
./node_modules/zone.js/dist/zone.js/</[email protected]://localhost:8100/polyfills.js:2510:28
[email protected]://localhost:8100/polyfills.js:2917:25
"
    resolvePromise http://localhost:8100/polyfills.js:3136:31
    resolvePromise http://localhost:8100/polyfills.js:3093:17
    scheduleResolveOrReject http://localhost:8100/polyfills.js:3195:17
    invokeTask http://localhost:8100/polyfills.js:2743:17
    onInvokeTask http://localhost:8100/vendor.js:34932:24
    invokeTask http://localhost:8100/polyfills.js:2742:17
    runTask http://localhost:8100/polyfills.js:2510:28
    drainMicroTaskQueue http://localhost:8100/polyfills.js:2917:25

И вот как я сейчас настраиваю свою маршрутизацию:

const routes: Routes = [
  {
    path: 'tabs',
    component: TabsPage,
    children: [
      {
        path: 'home',
        children: [
            {
                path: '',
                loadChildren: '../home/home.module/#HomePageModule'
            }
        ]
      },
      {
          path: 'add',
          children: [
              {
                  path: 'add',
                  loadChildren: '../add/add.module/#AddPageModule'
              }
          ]
      },
        {
            path: 'settings',
            children: [
                {
                    path: 'settings',
                    loadChildren: '../settings/settings.module/#SettingsPageModule'
                }
            ]
        }
    ]
  },
  {
    path: '',
    redirectTo: '/tabs/home',
    pathMatch: 'full'
  }
];

Answer by Westin Hardy

then the HomePage would be displayed. We also have a default route defined at the bottom so that if no route is supplied, it will use the login route.,NOTE: This is a simple approach to routing, make sure to also read the section on lazy loading later in this article.,This specifies all of the dependencies required for this particular route, and then it also supplies its own HomePageRoutingModule to define any additional routes. That file might look like this:,Need some help with this tutorial? Spotted an error? Got some helpful advice for others? Join the discussion on Twitter

If you’ve been building Ionic applications then you would be used to navigating through your applications by using the NavController to push new pages to navigate forward in the navigation stack:

this.navCtrl.push('SignupPage');

Popping pages to move backward in the navigation stack:

this.navCtrl.pop();

or starting a completely new navigation stack by changing the root page:

this.navCtrl.setRoot('HomePage');

Angular routing is different in that it is based on the browser model of navigation and uses the URL to determine which page/component to show. In your application, you would need to supply a set of routes that might look something like this:

const routes: Routes = [
  { path: 'login', component: LoginPage },
  { path: 'home', component: HomePage },
  { path: 'detail/:id', component: DetailPage },
  { path: '', redirectTo: '/login', pathMatch: 'full' },
];

The path property defines the URL, and the component property defines which component should be displayed by the <ion-router-outlet> when that URL is hit. If I were to go to the following URL:

http://localhost:8100/home

You can use routerLink to link to another page:

<ion-item
  [routerLink]="'/detail/' + item.id"
  routerDirection="forward"
></ion-item>

You can also navigate programmatically by injecting the standard Angular Router into your pages and calling either of these methods:

this.router.navigateByUrl('/login');

or

this.router.navigate(['/detail', { id: itemId }]);

However, the best way to navigate programmatically in an Ionic/Angular application is to use the NavController from @ionic/angular. This is actually quite similar to how you would use the NavController previously to push/pop, except now you would just use one of these methods:

this.navCtrl.navigateForward('/route');
this.navCtrl.navigateForward('/route');
this.navCtrl.navigateBack('/route');
this.navCtrl.navigateBack('/route');
this.navCtrl.navigateRoot('/route');

Lazy loading with Angular routes is not too dissimilar to regular routing. However, your routes would look like this instead:

const routes: Routes = [
  { path: 'login', loadChildren: './pages/login/login.module#LoginModule' },
  { path: 'home', loadChildren: './pages/home/home.module#HomeModule' },
  {
    path: 'detail/:id',
    loadChildren: './pages/detail/detail.module#DetailModule',
  },
  { path: '', redirectTo: '/login', pathMatch: 'full' },
];

If we use the home route as an example, the loadChildren property is:

'./pages/home/home.module#HomeModule'

The router knows that it needs to open the home.module.ts file, and look for the HomeModule. That file might look like this:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { IonicModule } from '@ionic/angular';

import { HomePage } from './home.page';
import { HomePageRoutingModule } from './home-routing.module';

@NgModule({
  imports: [CommonModule, IonicModule, HomePageRoutingModule],
  declarations: [HomePage],
  entryComponents: [],
  bootstrap: [HomePage],
})
export class HomeModule {}

This specifies all of the dependencies required for this particular route, and then it also supplies its own HomePageRoutingModule to define any additional routes. That file might look like this:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { HomePage } from './home.page';

const routes: Routes = [{ path: '', component: HomePage }];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
})
export class HomePageRoutingModule {}

Answer by Anthony Vang

Ionic Template Generator,Once you need to pass more information to the next page, you need to select a way for your app to pass around data. Basically there are three ways to do so:,So router outlets inside our app will be replaced by the Angular Router whenever we find a path match. For all pages that you somehow want to access inside your app, you need to define a path.,And because we told the Angular Router to load the ‘./list/list.module#ListPageModule’ when the path matches /list, the exact page will be displayed!

The Entry Point of Your App

When you inspect the folders of your app, you’ll find one HomePage at the src/app/home path. This is the page you see on screen (compare it’s HTML with what you see if you don’t trust me), but how is it actually loaded?

HomePage

    Table of contents

  • Uncaught Error: Cannot Find Module When Using Dynamic Import for JavaScript
  • webpack
    /
    webpack
    Public
  • Solved — SyntaxError Cannot use import statement outside a module
  • How to solve the Cannot use import statement outside a module

Uncaught Error: Cannot Find Module When Using Dynamic Import for JavaScript

import(`./language-packs/${navigator.language}.js`)
import LazyLoad from 'services/LazyLoad';

export class AppRoutes extends React.Component {
  render() {
    return (
      <Switch>
        <Route
          exact path="/"
          render={(matchProps) => (
            <LazyLoad
              absoluteModulePath='pages/default/HomePage'
              getComponent={() => import('pages/default/HomePage')}
              {...matchProps}
            />
          )}
        />
      </Switch>
    );
  }
}

export default AppRoutes;
import React from 'react';

export const HomePage = () => {
  return (
    <div>
      I'm the default HomePage
    </div>
  );
}

export default HomePage;
import React from 'react';

export class LazyLoad extends React.Component {
  ...

  componentDidMount() {
    import(this.props.absoluteModulePath)  // Critical dependency: the request of a dependency is an expression
      .then(module => module.default)
      .then(AsyncModule => this.setState({AsyncModule}))
  }

  ...
}

export default LazyLoad;
import React from 'react';

export class LazyLoad extends React.Component {
  ...

  componentDidMount() {
    this.props.getComponent()
      .then(module => module.default)
      .then(AsyncModule => this.setState({AsyncModule}))
  }

  ...
}

export default LazyLoad;
NODE_PATH=src/
...
<LazyLoad
    modulePath='HomePage'
    getComponent={() => import('pages/default/HomePage')}
    {...matchProps}
/>
componentDidMount() {
  import(`pages/default/${this.props.modulePath}/index.js`)
    .then(module => module.default)
    .then(AsyncModule => this.setState({AsyncModule}))
}

webpack
/
webpack
Public

 Error: Cannot find module '/Users/hubert_i/Emodyz/launcher-ezgames.eu/modules/test/index.js'.
      at /Users/hubert_i/Emodyz/launcher-ezgames.eu/dist/electron/main.js:10475:9
      at <anonymous>
      at process._tickCallback (internal/process/next_tick.js:188:7)
import( '/Users/hubert_i/Emodyz/launcher-ezgames.eu/modules/test/index.js')
  .then((m) => {
    console.log(m.name)
  })
  .catch(err => {
    console.error('Error during loading module: ' + err)
    callback()
  })
const test = '/Users/hubert_i/Emodyz/launcher-ezgames.eu/modules/test/index.js'
import(test)
  .then((m) => {
    console.log(m.name)
  })
  .catch(err => {
    console.error('Error during loading module: ' + err)
    callback()
  })
import("./locales/" + locale + ".js")
loadJs = ( url, name ) => {
  return new Promise( resolve => {
    import(`/test/${name}`)
    .then((module) => {
      resolve(module.default)
    })
  })
}
import(`http://localhost:3001/api/uicomponents/one/${name}`)
{
  test: /.config.js$/,
  exclude: /node_modules/,
  loader: "file-loader",
  options: { name: "./conf/[name]-[hash:base36:4].[ext]", },
}
const path = require("../conf/" + ENVIRONMENT_NAME + ".config.js");
import(/* webpackIgnore: true */CONFIG_PATH).then(mod => config.init(mod));
function parse (fileName, callback) {
  var path = "./relative/path/to/" + fileName + ".json";
  var cb = process.bind(this, fileName, callback);
  if (typeof webpackJsonp !== "undefined") { // <-- Test if run as Webpack bundle
    // Do dynamic import
    import(path).then(cb);
  } else {
    // Do Ajax call
    request(Config.toUrlFromRoot(path)).then(cb);
  }
}
module.exports = {
  node: { fs: 'empty' }
};
Unhandled Promise rejection: Cannot find module './resources/symbology/labelTemplates/labelTemplates.json' ; Zone: <root> ; Task: Promise.then ; Value: Error: Cannot find module './resources/symbology/labelTemplates/labelTemplates.json'
    at symbology lazy namespace object:5
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:391)
    at Zone.push../node_modules/zone.js/dist/zone.js.Zone.run (zone.js:150)
    at zone.js:889
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
    at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:195)
    at drainMicroTaskQueue (zone.js:601) Error: Cannot find module './resources/symbology/labelTemplates/labelTemplates.json'
...
* get names of files in directory

use reuire.context to get

* dynamic import the file content

IMORTANT: the first parameter in import method should be a constant prefix!
Ref:
webpack/webpack#6680 (comment)

====

Tried but failed method:

      // 1.fs failed, in webpack fs cannot be use
      // const fs = require("fs");
      // console.warn("content=>", fileContent);
      // fs.readFile(filePath, "utf8", (err, data) => {
      //   if (err) {
      //     console.warn("err=>", err);
      //   } else console.warn("data=>", data);
      // });

      // 2.fileReader failed
      // var reader = new FileReader();
      // reader.readAsText(filePath);

      // 3.require raw-loader failed, the require expression not figured out yet
      // var test = require("raw-loader!./static/" + name);
      // console.log("content=>", test);

// import * failed!
// import * as txtFiles from "../../public/lyrics";
{
 target: 'node',
    node: {
      __dirname: false,
      __filename: false,
    }
}
import module from 'module';
const test = '/Users/hubert_i/Emodyz/launcher-ezgames.eu/modules/test/index.js'
module.createRequire(__dirname)(test)
  .then((m) => {
    console.log(m.name)
  })
  .catch(err => {
    console.error('Error during loading module: ' + err)
    callback()
  })
const test = 'Users/hubert_i/Emodyz/launcher-ezgames.eu/modules/test/index.js'
import(`/${test}`)
/**
  * Load custom module with simple require and absolute path
  * 
  * @param {string} path
  */
  private requireDynamically(path: string) {
    path = path.split('\').join('/');
    return eval(`require('${path}');`);
  }
 Error: Cannot find module '/Users/hubert_i/Emodyz/launcher-ezgames.eu/modules/test/index.js'.
      at /Users/hubert_i/Emodyz/launcher-ezgames.eu/dist/electron/main.js:10475:9
      at <anonymous>
      at process._tickCallback (internal/process/next_tick.js:188:7)
export const loadArray = async () => {
  const locale = getLocale().replace('_', '-')
  return await require(`./array/${locale}.js`)
}
export const loadArray = async () => {
  const locale = getLocale().replace('_', '-')
  return await require(`./array/${locale}.js`)
}
const GHub = lazy(() => import('react-switch-app-one'))
const Count = lazy(() => import('@ruben.bernardes.dev/counter'))
const packagesPaths = ['react-switch-app-one', '@ruben.bernardes.dev/counter']
const importComponent = path =>
  lazy(() => import(path).catch((e) => console.log(e)));

const loadedAppPaths = packagesPaths.map(app => importComponent(app))
Sidebar.js:25 Error: Cannot find module 'react-switch-app-one'
    at sidebar lazy groupOptions: {} namespace object:5
import("./locales/" + locale + ".js")

How to Fix “Uncaught SyntaxError: Cannot use import statement outside a module”

<script src="../src/main.js"></script>
<script type="module" src="../src/main.js"></script>
{
  // ...
  "type": "module",
  // ...
}
// import { parse } from 'node-html-parser'; 
const parse = require('node-html-parser');
   "entities": [
      "src/db/entity/**/*.ts",
   ],
   "entities": [
      "dist/db/entity/**/*.js", 
   ],
    "target": "esnext",
    "module": "esnext",
    "target": "esnext",
    "module": "commonjs",

webpack
/
webpack
Public

polyfills.js:1 Error: Cannot find module "."
    at webpackMissingModule (eval at 148 (http://localhost:9000/assets/app.js:1:576363), <anonymous>:8:65) [angular]
    at eval (eval at 148 (http://localhost:9000/assets/app.js:1:576363), <anonymous>:8:144) [angular]
    at Object.onInvoke (eval at <anonymous> (http://localhost:9000/assets/vendor.js:1:92060), <anonymous>:4334:37) [angular]
    at eval (eval at 142 (http://localhost:9000/assets/polyfills.js:1:6901), <anonymous>:758:57) [angular]
    at Object.onInvokeTask (eval at <anonymous> (http://localhost:9000/assets/vendor.js:1:92060), <anonymous>:4325:37) [angular]
    at drainMicroTaskQueue (eval at 142 (http://localhost:9000/assets/polyfills.js:1:6901), <anonymous>:591:35) [<root>]
    at <anonymous> [<root>]
@angular/cli: 1.0.3
node: 7.0.0
os: win32 x64
@angular/common: 4.1.2
@angular/compiler: 4.1.2
@angular/core: 4.1.2
@angular/forms: 4.1.2
@angular/http: 4.1.2
@angular/platform-browser: 4.1.2
@angular/platform-browser-dynamic: 4.1.2
@angular/router: 4.1.2
@angular/cli: 1.0.3
@angular/compiler-cli: 4.1.2
var path = 'path/to/file.js' 
require(path) // Error: Cannot find module "."
require('path/to/file.js' ) // All good
require(`${path}`)
require(`${path_to_file}`);
function getIcon(name) {
  const [category, filename] = name.split(":");

  if (filename) {
    return require(`one_directory/icons/${category}/${filename}.svg`);
  } else {
    return require(`two_directory/icons/${name}.svg`);
  }
}
const _import = (relativePath) => {
  var fullRelativePath = relativePath;
  if(relativePath.indexOf('@') === -1){
    fullRelativePath = '@/components/' + relativePath;
  }
  if (process.env.NODE_ENV === 'development') {
    return require('@/components/' + relativePath).default  // this work and followiing not
    //TODO not work Uncaught Error: Cannot find module '@/components/page/CloudConsole'
    // return require(`${fullRelativePath}`).default
    // TODO not work Uncaught Error: Cannot find module "."
    // return require(fullRelativePath).default
  } else {
    return import(fullRelativePath); // this work
    //work
    // return import(`${fullRelativePath}`)
  }
};

_import('page/CloudConsole')
config = require(`../inc/${process.env.targetNetwork}.config.json`);
config = require('../inc/' + process.env.targetNetwork + '.config.json');
This can seemingly cause problems in webpack (see webpack/webpack#4921).
require(`${path_to_file}`);

How to solve «Error: Cannot find module ‘*.js'» with Node.js

Error: Cannot find module 'C:UsersMemy_app.js'
# In Windows
cd C:UsersMemy_project_directory

# In Mac OS
cd /Users/Me/my_project_directory/

# In Linux
cd /home/Me/my_project_directory/
# In Linux/Mac
pwd

# In Windows
echo %cd%
# In Windows
dir

# In Linux/Mac
ls

Others-How to solve ‘Cannot find module’ or MODULE_NOT_FOUND error when using ‘npm start’

➜  controlpanel git:(master) npm start

> [email protected] start
> node scripts/start.js

node:internal/modules/cjs/loader:936
  throw err;
  ^

Error: Cannot find module 'dotenv'
Require stack:
- /Users/bswen/WebstormProjects/react-and-redux/chapter-02/controlpanel/scripts/start.js
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:999:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (/Users/bswen/WebstormProjects/react-and-redux/chapter-02/controlpanel/scripts/start.js:7:1)
    at Module._compile (node:internal/modules/cjs/loader:1097:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1149:10)
    at Module.load (node:internal/modules/cjs/loader:975:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    '/Users/bswen/WebstormProjects/react-and-redux/chapter-02/controlpanel/scripts/start.js'
  ]
}

Node.js v17.1.0
➜  controlpanel git:(master) 


npm install

Solved — SyntaxError Cannot use import statement outside a module

import fs from 'fs'
import csv from "csv-parser"
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at wrapSafe (internal/modules/cjs/loader.js:1063:16)
    at Module._compile (internal/modules/cjs/loader.js:1111:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1167:10)
    at Module.load (internal/modules/cjs/loader.js:996:32)
    at Function.Module._load (internal/modules/cjs/loader.js:896:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
    at internal/main/run_main_module.js:17:47
Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
<script type="module" src="main.js"></script>

How to solve the Cannot use import statement outside a module

import { add } from './math.js';

console.log(add(1, 2));
Uncaught SyntaxError: Cannot use import statement outside a module
<script type="module" src="main.js"></script>

Next Lesson PHP Tutorial

Понравилась статья? Поделить с друзьями:
  • Uncaught guzzlehttp exception requestexception curl error 60 ssl certificate problem
  • Uncaught exception out of memory error
  • Uncaught exception error eperm operation not permitted
  • Uncaught error no recaptcha clients exist
  • Uncaught error class mongo not found