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

Leverage promises to alter reactive data, strategically placing them to minimize the frequency of triggers being activated

Initial Method const list = reactive([1, 2, 3, 4, 5]); const clickHandler = () =>{ list.push(...[11, 12, 13, 14, 15]); list.push(...[16, 17, 18, 19, 20]); Promise.resolve().then(() => { list.push(33) ...

The Ajax request is not successfully communicating with the PHP script

I am struggling with an issue regarding ajax calling a PHP code without changing the current page. Despite checking the php_error.log, I cannot find any reference to the PHP file. There are no errors displayed on screen, leaving me clueless about how to re ...

There was an issue encountered while trying to install Electron using the command 'npm install electron'

While attempting to install electron using npm install electron, I encountered the following error: 908 error code 1 909 error path C:\Users\name\Documents\name\Code\code\node_modules\gl 910 error command failed ... ...

dynamic rendering in React based on the value passed through props

I am attempting to render a component using react.lazy, where the path is a variable in my props. However, I am encountering an error with webpack. The parent component sends the props like this: <DynamicModal url = 'Impuesto/formulario&apo ...

Issue with Ajax submit button failing to pass ID

I am encountering an issue while trying to update data using bootstrap modal. When the CGridView selectionChanged event is triggered, it should call a function to display a modal dialog form and populate the form with the selected data. Below is my CGrid ...

What is preventing Node.js from executing my JavaScript code in the terminal?

I need help understanding why my JavaScript code isn't working properly. Can someone explain the Uncaught SyntaxError: Unexpected Identifier error message? ...

Stop a loop that includes an asynchronous AJAX function

Embarking on my Javascript journey as a beginner, I find myself facing the first of many questions ahead! Here is the task at hand: I have a directory filled with several .txt files named art1.txt, art2.txt, and so on (the total count may vary, which is ...

Using the base tag in Angular HTML5 mode can cause script links to break

Issue Following the configuration of a base tag to enable Angular 1.x in HTML5 mode, encountering an error where the browser (Chrome) sends requests to an incorrect path for scripts when directly accessing the app via localhost:3000/resource/id. Specific ...

Custom AngularJS directive for ensuring the selection of a required HTML element

Today brings another question as I continue working on my web application. I've encountered an issue with the 'required' attribute not being widely supported in major browsers. The attribute only works if the first option value is empty, whi ...

Creating an HTML string and then displaying its outer HTML in IE10 can be easily achieved. Just write the

My task is to write an HTML string to an element and then retrieve the resulting outer HTML from that element. This needs to be operational in IE10, latest versions of FF, Chrome, Safari, Android, iOS Safari but does not have to support any older browsers. ...

Enhance React scrollbar functionality without relying on third-party dependencies

Currently working on enhancing the appearance of the scrollbar within my ReactJS project. Specifically, I am aiming for a design similar to this example: https://i.stack.imgur.com/2Q0P4.png Experimented with CSS properties like -webkit-scrollbar, -webki ...

Send all of the elements within an array as arguments to a function

My challenge involves working with an array of values: ['a', 'b', 'c', 'd'] I must pass these values as parameters to a function like this: window.myFunction('a', 'b', 'c', 'd&ap ...

AngularJS throws the error message "$digest already in progress" upon logging out

When a user logs out, I would like to automatically redirect them to the main page. $rootScope.logOut = function() { myService.logOut().then(function(data) { $rootScope.$apply(function() { $location.path("/"); }); }); } However ...

The Vue JS Router is prominently displayed in the center of the webpage

I have been delving into Vue JS and working on constructing an app. I've implemented vue router, however, it seems to be causing the content within the routed component to display with excessive margins/padding. I've attempted various solutions s ...

Reasons Why Vue Component Does Not Update When Select Changes

I'm encountering an issue with a form that is supposed to change text within a vue component based on the selection made in a select box. To demonstrate the problem I'm facing, I've created a simplified version of the code on jsfiddle: http ...

HookWebpackError: There seems to be an issue with reading the properties of undefined, specifically regarding 'e'. An inner error has occurred, resulting in a TypeError when trying to read properties of undefined for 'e'

I have been using npx-create-react-app for years, but now I am unable to build with npm run build. Even after updating my node and npm and clearing the cache with npm cache clean --force, the projects are still not working. Neither the old ones nor the ne ...

How can these lines be drawn in a simple manner?

I have been using the div tag to create a line, but I'm looking for an easier solution. If you have another method in mind, please share it with me. #line{ background-color:black; height:1px; width:50px; margin-top:50px; margin-left:50px; f ...

Creating route paths within a single .js file

I'm a beginner when it comes to Node/Express, and I have a question about my app structure. Here is a simplified version of how my app is set up: /app /routes filter.js index.js app.js In my app.js file, I have defined my routes like th ...

Transfer the HTTP functionality to a separate service using Angular2 and TypeScript

Currently diving into learning Angular2 and TypeScript after years of using Angular 1.*. I have a top level component that has a property derived from a custom type created in another class. When ngOnInit() is triggered, it makes an HTTP call to a mock RES ...

Javascript: recursive function fails to return existing value

I'm attempting to recursively loop through an array in search of a key that matches a specified regex pattern. Once the condition is met, the loop should halt and return the value of the key. The issue I am facing is that although the loop stops corr ...