Achieving webpack bundling for node_modules in Angular 1: A step-by-step guide

I am facing a challenge as I transition my angular 1 + typescript project build setup from gulp to webpack. The issue lies in bundling the node_modules js files in the correct sequence.

Previously, I relied on bower for client-side dependencies, and the use of gulp's wiredep plugin made it easy to determine the dependency order based on the

bower dependencies section + main section
.

Now with webpack, the approach is different. Rather than relying on specific dependency sections, imported modules play a crucial role in determining the order.

To make this work, I need to transfer all dependencies from bower.json to package.json.

Currently, with typings in use, tsc manages the typings automatically without requiring manual imports for bower packages.

If I understand correctly, to make it compatible with webpack,

a) Should I eliminate typings and directly import the js files within my ts files?

Given that npm js modules typically work with modules, do typings files become unnecessary for webpack?

OR

b) Should I create a separate vendor.ts file where I manually organize the import sequence (for js and css)?

This method may be more tedious compared to using wiredep, but it can enable bundling the vendor files separately using chunks-plugin.

OR

c) Is there another common approach to address this issue?

The transition of angular 1 from gulp to webpack proves to be a challenging task.

Answer №1

Importing a module from a TypeScript file that will be loaded by webpack results in the content being pulled from node_modules and bundled into the output file.

index.ts

import * as angular from "angular";

const myApp = angular.module("myApp", []);

myApp.controller("MyController", function PhoneListController($scope) {
  $scope.phones = [
    {
      name: "Nexus S",
      snippet: "Fast just got faster with Nexus S."
    }, {
      name: "Motorola XOOM™ with Wi-Fi",
      snippet: "The Next, Next Generation tablet."
    }, {
      name: "MOTOROLA XOOM™",
      snippet: "The Next, Next Generation tablet."
    }
  ];
});

index.html

<!DOCTYPE html>
<html ng-app="myApp">
<head>
  ...
  <script src="bundle.js"></script>
</head>
<body ng-controller="MyController">

  <ul>
    <li ng-repeat="phone in phones">
      <span>{{phone.name}}</span>
      <p>{{phone.snippet}}</p>
    </li>
  </ul>

</body>
</html>

webpack.config.js

module.exports = {
    entry: "./index.ts",
    output: {
        filename: "./bundle.js"
    },
    devtool: "source-map",
    resolve: {
        extensions: ["", ".webpack.js", ".web.js", ".ts", ".tsx", ".js"]
    },
    module: {
        loaders: [
            { test: /\.tsx?$/, loader: "ts-loader" }
        ],
        preLoaders: [
            { test: /\.js$/, loader: "source-map-loader" }
        ]
    }
};

Add angular, @types/angular, ts-loader, source-map-loader, typescript to your packages.json and run webpack.

All code will be combined into a single file named bundle.js for use in your index.html.

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

In React TS, the function Window.webkitRequestAnimationFrame is not supported

I'm facing an issue where React TS is throwing an error for window.webkitRequestAnimationFrame and window.mozRequestAnimationFrame, assuming that I meant 'requestAnimationFrame'. Any suggestions on what to replace it with? App.tsx import Re ...

Encountering an error while attempting to set up WebDriverIO with Typescript and Cucumber installation

After completing the project setup, the wdio.conf.ts and tsconfig.json files are saved in a folder named tests. However, the wdio.conf.ts file throws an error on this line: import type { Options } from "@wdio/types"; //located in wdio.conf.t ...

Exploring the Power of Angular's Redux Implementation with Lazy Loading Strategy

Implementing Redux with Angular has been incredibly beneficial for me, but I am curious about how lazy loading can be incorporated alongside it. Can these two techniques work well together? ...

I'm curious, which redux architecture would you recommend for this specific scenario?

I'm currently developing an application and I'm facing a challenge in implementing Redux effectively in this particular scenario. Unfortunately, due to restrictions at my workplace, normalizing data is not an option. Let's consider the foll ...

Formatting Time in Angular 2 Using Typescript

Upon reviewing my date source, I found the following: TimeR ="2017-02-17 19:50:11 UTC"; Within the HTML file, I implemented this code snippet <span class="text-lg">{{TimeR | date: 'hh:mm'}}</span> The current output displays the t ...

Testing @microsoft/applicationinsights-web within an Angular project on a local environment

How can I test Microsoft's application insights locally? Most guides I've come across suggest testing it on the Azure portal, but I can't do that as it would mean testing it in a production environment. ...

Filtering the length in AngularJS!

Is there a way to display only values with 2 characters in the select box using the ng-option filter? ng-options="item.NumberValue as item.Title for item in myLists.list1 | filter:{NumberValue.length:2}" ...

Create a package themed with Material UI for export

I am attempting to create a new npm package that exports all @material-ui/core components with my own theme. I am currently using TypeScript and Rollup, but encountering difficulties. Here is the code I have: index.ts export { Button } from '@materia ...

Delete the option "x" from the kendo combobox

Is there a way to eliminate or hide the clear ("x") action from a Kendo combobox using TypeScript? I have attempted to find a solution through SCSS/CSS, but I have not been successful. Alternatively, I would be fine with preventing the event triggered by ...

Find the closing of a $modal by observing the backdrop

Is it possible to use AngularJS with angularUI-bootstrap to detect when a modal is being closed by clicking on the backdrop? I would like to update a boolean value based on the closing of the modal. ...

The behavior of the dynamically generated object array differs from that of a fixed test object array

I'm facing an issue while trying to convert JSON data into an Excel sheet using the 'xlsx' library. Everything works perfectly when I use test data: //outputs excel file correctly with data var excelData = [{ test: 'test', test2: ...

In order to successfully utilize Node.js, Async.js, and Listeners, one must ensure

Here is the log output from the code below, I am unsure why it is throwing an error. It seems that the numbers at the end of each line represent line number:char number. I will highlight some important line numbers within the code. Having trouble with t ...

Using a javascript component in vue.js with typescript - a step-by-step guide!

I have created a component in one project and now I want to make it accessible for use in another project. This is how I am currently exposing it: import ToastNotification from '../ToastNotification'; import Api from './api'; const Vu ...

Having issues with the JavaScript controller when using ng-include in the code

Although I have successfully loaded the controller's JavaScript file, I am hesitant to load all controllers on the main page as they have nothing to do with each other. Here is an example of the main page structure: <html lang="en" ng-app="FirstP ...

Executing functionality based on changes in Angular bindings

I am working on securing user passwords in my HTML form. Currently, the password field is stored in localstorage like this: In JS: $scope.localStorage = localStorage; And then in HTML: <input id="pass" type="password" ng-model="localStorage.pass" re ...

Using ngModel to retrieve and display only the month, year, and date

Currently, I am working with an interface named Person which includes fields such as name, last name, birthday, and others. However, I am facing a confusion when it comes to the person's birthday format, as it contains some additional letters at the e ...

Error Interceptor in AngularJS: Retrieving Current User Data from Backend

Seeking assistance with a function that retrieves the logged in user. I must confess that I obtained this code from a tutorial and do not fully comprehend its inner workings. After a period of inactivity (20 minutes), the token expires and invoking getCurr ...

A guide to seamlessly merging Chart.js with Angular 7 using data sourced from a database

Utilizing Chart.js to display information sourced from this Chart.js documentation Access the screenshot of the code ...

Exploring the Incorporation of String as a Component Identifier in React and TypeScript

My input component can render either a textarea component (from a library) or a regular input. Check out the code below: import React, { useEffect, useRef, useState } from 'react' import './AppInput.css' interface Props { placehold ...

Encountering an issue with Typescript Interfaces: property not found

This is my custom interface creation export interface UserInfo { success?: boolean, user?: User, employer?: Employer, hr?: Hr } After building this, the next task involves: let data = await loginUser(loginData); console.log(data.success); ...