0

I'm attempting to introduce webpack for a legacy SPA. I'm in a very similar position to the author of this article, where I've adapted their code to webpack v4.

The application needs myApp defined globally, so I've exposed myApp like so:

app.js

export var myApp = angular.module('app', ['ui.router']);

webpack.config.js

module.exports = {
    entry: './client/entryPoint.js',
    module: {
        rules: [
            {
                test: /app\.js$/,
                loader: 'expose-loader',
                options: {
                    exposes: {
                        globalName: 'entry'
                    },
                }
            }
        ]
    },

This works perfectly to recursively "inject" that global variable by adding some additional code:

entryPoint.js

function importAll (r) {
    r.keys().forEach(function(file) {
        if (!file.includes('app.js')) {
            r(file);
        }
    });
}
importAll(require.context("imports-loader?additionalCode=var%20myApp%20=%20entry.myApp;!./app/", true, /.*\.js/));

This doesn't work defining it in the webpack.config.js:

webpack.config.js

module.exports = {
    entry: './client/entryPoint.js',
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /(app\.js|entryPoint\.js|node_modules)/,
                loader: 'imports-loader',
                options: {
                    additionalCode: 'var myApp = entry.myApp;'
                }

            },
            {
                test: /app\.js$/,
                loader: 'expose-loader',
                options: {
                    exposes: {
                        globalName: 'entry'
                    },
                }
            }
        ]
    },

Inpecting the bundle, webpack hasn't added added the additionalCode as it did when using the inline imports-loaders.

Any pointers to where the translation to configuration has gone awry?

EDIT 10/08/2020

Here's the structure of my app:

.
├── client
│   ├── app
│   │   ├── app.js
│   │   ├── home
│   │   │   ├── about.html
│   │   │   └── about.js
│   │   ├── landing.html
│   │   └── landing.js
│   ├── index.html
│   └── entryPoint.js
├── dist...
├── package.json
├── node_modules...
└── webpack.config.js

The angular controllers expect myApp to be defined like so, e.g.:

landing.js

myApp.controller('LandingCtrl', function($http){
    ...
}
Khei
  • 73
  • 3
  • 11
  • 1
    Is all the code that consumes `myApp` is in your respository? Can I suggest an alternative solution with `exports-loader` and `import-loader`? This is the way shim is configured in webpack 4 – Raz Ronen Aug 09 '20 at 09:19
  • Yes please, open to alternative solutions, not particularly attached to this solution. I've clarified the structure of the app in the question if that helps – Khei Aug 10 '20 at 01:32

0 Answers0