Lukas Chen Lukas Chen - 6 months ago 70
Javascript Question

Importing angular in typescript using webpack load

Hi folks on the Internet! Today I am presenting you another problem! (Yay?)

I am using webpack with the ts-loader to compile typescript code. However when I'm importing angular like this:

import * as angular from "angular";
angular.module("app", []);

It is actually importing 2 scripts as presented below:

[18:11:21] Starting 'build'...
ts-loader: Using typescript@2.0.6 and C:\testProject\tsconfig.json
[18:11:24] [webpack] Hash: 155db0dc394ae32ae9e6
Version: webpack 1.13.2
Time: 2845ms
Asset Size Chunks Chunk Names
app.js 3.11 MB 0 [emitted] main
chunk {0} app.js (main) 1.19 MB [rendered]
[0] ./app/app.module.ts 2.26 kB {0} [built]
[1] ./~/angular/index.js 48 bytes {0} [built]
[2] ./~/angular/angular.js 1.19 MB {0} [built]

  • index.js
    : The entry point of the angular library code

  • angular.js
    : The angular library

This is a problem because
also loads the angular library in which the result is the angular library loaded twice.

Here is my

entry: "./app/app.module.ts",

output: {
publicPath: "/lib/",
path: path.join(__dirname,"lib"),
filename: "app.js"

// source map
devtool: "#inline-source-map",

module: {
loaders: [
test: /\.ts$/,
// Exclude node modules
exclude: [/node_modules/],
loader: 'ts-loader'
test: /\.html$/,
// Exclude node modules
exclude: [/node_modules/],
loader: 'raw-loader'


I think you mis-understand how webpack works. All modules are executed once no matter how many times you require them. For example if you do:

 var angular = require('angular');
 var anotherAngular = require('angular');

The angular script will only really execute once, and the result "cached" for all subsequent calls to require.

In your case what you are seeing is perfectly normal. When you load angular from an npm package, the npm package uses the index.js which looks like:

module.exports = angular;

It is common in npm packages to have a minimal index.js that just re-exports another script. When you are loading with webpack webpack will load index.js which will in turn load angular.js and return the result. This shouldn't cause you any problems, and nothing is really getting loaded twice.