Issue with webpack ProvidePlugin and vendor bundle: The error "angular.module is not a function"

Currently, my Angular application is compiled into a single bundle using Webpack, including all dependencies and app code in one file. I am trying to split this code into two separate bundles: one for dependencies and one for application code.

In my webpack.config.js file, I have the following setup:

var webpack = require('webpack');
var path = require('path');

var definePlugin = new webpack.DefinePlugin({
    'process.env': {
        NODE_ENV: `"${process.env.NODE_ENV}"`
    }
});

var SRC = path.resolve(__dirname, 'src/main/client');
var APP = path.resolve(SRC, 'app/index.js');
var DEST = path.resolve(__dirname, 'target/webapp/dist');

module.exports = {
    entry: {
        vendor: [
            'angular',
            'angular-animate',
            'moment',
            'angular-moment',
            'angular-translate',
            'angular-ui-bootstrap',
            'angular-ui-router',
            'lodash'
        ],
        app: APP
    },
    plugins: [
        new webpack.ProvidePlugin({
            _: 'lodash',
            angular: 'angular',
            angularMoment: 'angular-moment',
            angularTranslate: 'angular-translate',
            moment: 'moment',
            ngAnimate: 'angular-animate',
            uibootstrap: 'angular-ui-bootstrap',
            uirouter: 'angular-ui-router'
        }),
        new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.bundle.js'),
        definePlugin
    ],
    output: {
        path: DEST,
        filename: 'bundle.js',
        publicPath: '/',
        hash: true
    },
    module: {
        preLoaders: [],
        loaders: [
            { test: /\.html$/, loaders: ['html'] },
            { test: /\.css$/, loaders: ['style', 'css'] },
            { test: /\.scss$/, loaders: ['style', 'css', 'sass'] },
            {
                test: /\.js$/,
                exclude: /(node_modules|bower_components)/,
                loaders: ['ng-annotate', 'babel?presets[]=es2015', 'eslint']
            },
            {
                test: /\.(ttf|eot|svg|woff2?)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                loader: 'file'
            }
        ]
    },
    sassLoader: {
        includePaths: [path.resolve(__dirname, './node_modules')]
    }
};

After splitting the code into two bundles, one for dependencies and one for application code, I encountered an issue when trying to load the application. I received an error message stating:

Uncaught TypeError: angular.module is not a function
. This error was linked back to the angular-moment.js file within the vendor.bundle.js. It seems that the angular dependency is not accessible to other modules loaded in the vendor.bundle.js file. I am unsure how to resolve this issue and make these dependencies visible to each other.

Answer №1

In response to the headline question, achieving compatibility between Angular 1 and webpack may require a shim (refer to https://github.com/webpack/webpack/issues/2049). Consider utilizing this webpack loader configuration:

module: {
    loaders: [
        /*
         * Essential for integrating angular 1 with webpack as detailed in https://github.com/webpack/webpack/issues/2049
         */
        {
            test: require.resolve('angular'),
            loader: 'exports?window.angular'
        },
    ]
},
plugins: [
    new webpack.ProvidePlugin({
        'angular': 'angular',
    }),
],

By implementing this setup, the initialization of the angular object will occur correctly instead of defaulting to an empty object without the module property.

Answer №2

To optimize your code, the following snippet will move all scripts that are not located in the src folder to the vendor chunk.

const path = require('path');
const projectRoot = path.resolve('./');

      new webpack.optimize.CommonsChunkPlugin({
        name: 'vendor',
        minChunks: (module) => module.resource && module.resource.indexOf(path.join(projectRoot, 'src')) === -1,
      }),

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

Step-by-step guide on building a factory in Angular for a pre-existing service

Currently, I am delving into the world of angularjs and exploring articles on service and factory functionalities. One particular example that caught my attention is showcased in this ARTICLE, which includes a demonstration using a Service Fiddle. As I de ...

Seeking a quick conversion method for transforming x or x[] into x[] in a single line of code

Is there a concise TypeScript one-liner that can replace the arrayOrMemberToArray function below? function arrayOrMemberToArray<T>(input: T | T[]): T[] { if(Arrary.isArray(input)) return input return [input] } Trying to cram this logic into a te ...

Is it necessary to link event handlers to `this` when using TypeScript and React?

One issue I encountered was with a component's button handler method. If the onClick handler is not bound to this in the constructor or inline on the onClick itself, an error occurs because the context of the handleAdd method is not tied to the instan ...

How can I access the rendered HTML element from a component in Vue 3?

This particular component is known as LayerComponent (placeholder). <script> export default { data() { return { count: 0 } } } </script> <template> <button @click="count++">You have clicked me {{ count ...

Manipulating Object Properties in the Browser's Console

When I log a JavaScript object in the browser, my curiosity leads me to expand it in the console window. An example of this is: console.log(console); I discover what's inside, but then a thought crosses my mind. When I dig deeper and expand the obje ...

Javascript Alert not functioning as expected

echo "<td><a onclick=\"confirm('Do you really want to delete this post permanently?');\" href='posts.php?id=".$res['id']."'>view</a></td>"; I'm using PHP to generate the code, but the co ...

Adding JavaScript files to a project in Ionic2 with Angular2 integration

I'm looking to incorporate jQuery into my Ionic2 app, which requires loading several JavaScript files: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <script type="text/j ...

Implementing multiple condition-based filtering in React Native for arrays

I am looking to apply multiple filters to an array based on certain conditions defined by toggling switches. The issue arises when toggling two or more switches simultaneously, resulting in an empty array. My goal is to retrieve an array containing the tru ...

Utilizing Angular.JS to apply the attribute selected="selected" to a specific option within a field

I am facing a situation where I have a scope object that consists of various Ratings that can be chosen from a dropdown: $scope.ratings = [{ id: 1, name: "Good", value: 9}, { id: 2, name: "Bad", value: 1 }]; The specific object I am rating looks like thi ...

Utilizing Ajax and jQuery to extract information from an XML file based on an identification number

Currently, I am looking for a way to showcase a specific product with its description from my XML file by using the product's ID. The structure of my XML file is shown below: https://i.sstatic.net/wFWgW.png Below is the JavaScript code I am using: ...

Creating a multi-tiered cascading menu in a web form: Harnessing the power of

In my form, there is a field called 'Protein Change' that includes a multi-level dropdown. Currently, when a user selects an option from the dropdown (for example, CNV->Deletion), the selection should be shown in the field. However, this funct ...

What is the best way to incorporate Howler into an Ionic 1 project?

within index.html file <script src="../node_modules/howler/dist/howler.js" type="text/javascript"></script> in app.js file angular.module('starter', ['ionic', 'ngCordova', 'ion-gallery', 'ngKookie ...

Is it possible to refresh a div on one .aspx page using content from another .aspx page?

Just beginning my journey with asp.net and currently tackling a project that involves two .aspx pages. Events.aspx: This page is where the site admin can update upcoming events and webinars using an available panel to input event title, date, information ...

Error: The function "navigate" has not been declared or defined

Just starting out in reactjs and embarking on a new project. I've successfully implemented a register and login function using firebase, but hit a snag when trying to navigate to a new page like the dashboard upon user login, I encountered this error: ...

MeteorJS encountered an issue stating "Invalid modifier. The modifier must be in object form."

After removing the if statements containing UserSession.insert, everything runs smoothly. However, when they are included, an error regarding an invalid modifier is triggered. What caused this issue? Your assistance is appreciated! server/helpers/b.s Me ...

Issues with unchecking modal icheck box when closing in Bootstrap JavaScript

Here is the HTML code that I am working with: <div class="modal inmodal" id="handleUserModal" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog"> &l ...

What is the best way to implement webpack (2.x) in elixir phoenix (1.3.x) as a replacement for brunch?

Attempting to switch from brunch to webpack for developing with hot-module-replacement and access to more advanced build tools. However, struggling because most tutorials are outdated, focusing on Phoenix 1.2.x and Webpack 1.x. Appreciate any advice or gu ...

Changing a URL parameter based on the element's width is a simple task when

I'm trying to display elements on a page by replacing a string in the URL parameter with the width of each element of a certain class. I'm new to JavaScript, so any help would be appreciated! Here's an example of the HTML for objects on the ...

Trouble with NodeJS NPM

I'm encountering difficulty when trying to install npm packages. npm ERR! Windows_NT 6.3.9600 npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules&bso ...

Tips for toggling the visibility of a <div> element with a click event, even when there is already a click event assigned

No matter what I try, nothing seems to be working for me. I'm looking to hide the <div id="disqus_thread"> at first and then reveal it when I click on the link "commenting", after the comments have loaded. This particular link is located at the ...