What steps do I need to take for webpack to locate angular modules?

I'm currently in the process of setting up a basic application using Angular 1 alongside Typescript 2 and Webpack. Everything runs smoothly until I attempt to incorporate an external module, such as angular-ui-router.

An error consistently arises indicating that the dependency cannot be located:

ERROR in ./src/app.ts Module not found: Error: Cannot resolve module 'angular-ui-router' in ./src/app.ts 3:26-54

To see the issue in action, check out this demo: https://github.com/jxc876/angular-ts

My suspicion is that I am not importing the routing dependency correctly. I have attempted the following:

  • import uiRouter from 'angular-ui-router';
  • import * as uiRouter from 'angular-ui-router'

I've experimented with both angular-route and ui-router, but neither seem to work. Furthermore, I have tried utilizing both ts-loader and awesome-typescript-loader without success.

App

import * as angular from 'angular';
import uiRouter from 'angular-ui-router';

let myApp = angular.module('myApp', [uiRouter]);

myApp.config(function($stateProvider) {
  let homeState = {
    name: 'home',
    url: '/home',
    template: '<div>It works !!!</div>'
  }

  $stateProvider.state(homeState);
});

Config

package.json

{
  "name": "ts-demo",
  "scripts": {
    "start": "webpack-dev-server --content-base ./src"
  },
  ...
  "devDependencies": {
    "@types/angular": "^1.5.16",
    "@types/angular-ui-router": "^1.1.34",
    "awesome-typescript-loader": "^3.0.0-beta.3",
    "typescript": "^2.0.9",
    "webpack": "^1.13.3",
    "webpack-dev-server": "^1.16.2"
  },
  "dependencies": {
    "angular": "^1.5.8",
    "angular-ui-router": "^0.3.1",
    "enhanced-resolve": "^2.3.0"
  }
}

webpack.config.js

module.exports = {
  entry: './src/app',
  output: {
    filename: './dist/bundle.js'
  },
  resolve: {
    extensions: ['.ts', '.tsx', '.js', '.jsx']
  },
  devtool: 'source-map',
  module: {
    loaders: [
      {
        test: /\.ts$/,
        loader: 'awesome-typescript-loader'
      }
    ]
  }
};

tsconfig.json

{
    "compilerOptions": {
        "outDir": "./dist/",
        "allowJs": true,
        "target": "es5",
        "module": "commonjs",
        "moduleResolution": "node",
        "strictNullChecks": true,
        "listFiles": true
    },
    "include": [
        "./src/**/*"
    ],
      "exclude": [
        "node_modules"
    ]
}

Answer №1

Finally got to the bottom of this.

The initial problem is caused by the typescript compiler removing import statements that are not utilized.

The compiler checks if each module is utilized in the generated JavaScript code. If a module identifier is only used in type annotations and not as an expression, no require call is included for that module. This optimization reduces unused references and allows for optional loading of modules.

source: https://github.com/Microsoft/TypeScript/issues/4717

I resolved this by assigning the imported value to a dummy array, which seemed to resolve the issue. Also, logging the value to the console proved effective (Refer to my final note on why passing it into the dependency array was not possible).

EDIT: A better approach is to utilize the import "module"; syntax as it is always emitted according to the source mentioned above, for example: import 'angular-ui-router';


Secondly, the webpack configuration file was lacking an empty string in the extensions under resolve:

resolve { extensions: ['', '.ts', '.js'] }

This absence prevented the import of the file for UI Router.

Some observations during this process: webpack --display-error-details was extremely helpful. It was searching for double .js.js extensions within

node_modules/angular-ui-router/release
:

resolve file
  /Users/mich2264/projects/angular-ts/node_modules/angular-ui-router/release/angular-ui-router.js.ts doesn't exist
  /Users/mich2264/projects/angular-ts/node_modules/angular-ui-router/release/angular-ui-router.js.js doesn't exist

--traceResolution was equally beneficial for typescript debugging.

EDIT: Seems to be a bug with awesome-typescript-loader loader: https://github.com/s-panferov/awesome-typescript-loader/pull/264


Lastly, I encountered a peculiar behavior where importing the default value from angular-ui-router showed correctly as ui.router when logged or used with a breakpoint. However, when trying to pass it into the dependency array, it became undefined.

The export defined in @types/angular-ui-router type file is as follows: export default "ui.router";

Answer №2

Here's a solution that should work well for you:

import * as ngCore from '@angular/core';
import * as ngRouter from '@angular/router';

let myApp = ngCore.NgModule({
  imports: [ngRouter.RouterModule]
});

It's important to note that the import statement is simply bringing in router code, and within your application module, you need to include the string '@angular/router'.

Answer №3

When working with UI-Router for AngularJS (1.x), it seems necessary to include the following import statement:

import '@uirouter/angularjs'

This should be used instead of the deprecated:

import 'angular-ui-router'

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue: Property is not found within the parameters of the Generic Type

Currently, I am delving into the world of Typescript and have been exploring various exercises that I stumbled upon online. However, I have encountered some trouble with the feedback on incorrect solutions. Specifically, I am facing an issue with the follo ...

When attempting to run npm install for @types/jquery, an error is returned stating "Invalid name: @types/jquery"

npm install @types/jquery npm ERR! Windows_NT 10.0.10586 npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-c ...

The component triggering the redirect prematurely, interrupting the completion of useEffect

I set up a useEffect to fetch data from an endpoint, and based on the response, I want to decide whether to display my component or redirect to another page. The problem I'm facing is that the code continues to run before my useEffect completes, lead ...

What is the best way to incorporate variables into strings using JavaScript?

Can someone help me achieve the following task: var positionX = 400px; $(".element").css("transform", "translate(0, positionX)"); Your assistance is greatly appreciated! ...

Dealing with compilation errors in TypeScript

I'm working on a simple TypeScript program that looks like this - const users = [{ name: "Ahmed" }, { name: "Gemma" }, { name: "Jon" }]; // We're trying to find a user named "jon". const jon = users.find(u => u.name === "jon"); However, wh ...

Upon calling set() on Map, the object returned does not conform to a Map data structure

I've been exploring the transition to using immutable.js for managing states: class Register extends Component<{}, Map<string, string>> { state = Map<string, string>(); onInputValueChange(e) { const { name, value } ...

HELP! Imagemaps are being ruined by overlapping DIVs!

I encountered a minor issue. In summary, I have a container div that displays rotating images and image maps with clickable links within each image setup like a gallery with built-in navigation. Recently, I was tasked with adding simple animations to the i ...

Customize the border width and color of a specific column in HighCharts based on dynamic data

I am looking to dynamically change the border width and color of only one column in a basic column chart. Here is an example: var chartingOptions = { chart: { renderTo: 'container', type: 'column' }, xAxis: { categories: [ ...

The rule 'import/no-cycle' definition could not be located

After removing my npm package along with the package.lock.json file, I proceeded to run 'npm install' and followed up with 'npm update'. However, upon starting my application using 'npm run start', an error occurred. Upon lau ...

Having trouble consuming data from a service in Angular 6?

I'm in the process of creating a basic cache service in Angular; a service that includes a simple setter/getter function for different components to access data from. Unfortunately, when attempting to subscribe to this service to retrieve the data, t ...

The operation of moveImage does not exist

Currently, I am attempting to incorporate setInterval with my moveImage function in order to modify the position of an image. Here is a snippet of my code: <template> <div class="randImg"> <img v-bind:style="{top: imgTop + 'px&ap ...

Is there a way to determine if a webpage is being accessed from a website or from a local file system?

While this question has been raised in the past, none of the answers provided seem to be accurate. Unfortunately, I am unable to comment on the original question or answers. Thus, following suggestions given to me, I have decided to create a new question. ...

I am looking to sort users based on their chosen names

I have a task where I need to filter users from a list based on the name selected from another field called Select Name. The data associated with the selected name should display only the users related to that data in a field called username. Currently, wh ...

Tips for Iterating through Nested Arrays using the Inside Array in a Dynamic Way

I am facing an issue with my code as it lacks flexibility when a new array is added to the nested array, in which case the new array is not considered. My main concern is how to access the elements of each nested array simultaneously. Here's an examp ...

Having difficulty connecting images or photos to CodePen

I've been attempting to connect images and sound files to my CodePen project using a Dropbox shared link. <div class="container"> <div class="row second-line"> <div class="col-12"> <div d ...

The object returned by bodyParser is not a string but a data structure

I have been working on implementing a JSON content listener in Typescript using Express and Body-parser. Everything is functioning perfectly, except when I receive the JSON webhook, it is logged as an object instead of a string. import express from 'e ...

Ensuring consistency of variables across multiple tabs using Vue.js

In my vuejs front-end, a menu is displayed only if the user is logged in. When I log out, the variable isLogged is updated to false, causing the menu to hide. If I have multiple tabs open with the frontend (all already logged in) and I logout from one tab ...

How can I retrieve the Google Maps URL containing a 'placeid' using AJAX?

I have a specific URL that I can access through my browser to see JSON data. The URL appears as follows: https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJZeH1eyl344kRA3v52Jl3kHo&key=API_KEY_HERE However, when I attempt to use jQuer ...

Engaging with the crossrider sidepanel extension

When it comes to the crossrider sidepanel, I prefer using an iframe over js-injected html to avoid interference with the rest of the page. However, I am struggling to establish any interaction between my browser extension and the iframe. I believe adding ...

Variable scope not properly maintained when there is a change in the Firebase promise

I am currently working on developing a controller function to handle signup submissions using Firebase. However, I've encountered an issue where the variables within the scope (controllerAs: $reg) do not seem to update correctly when modified inside a ...