Error in Webpack ProvidePlugin when trying to access global variable (Module not found)

I'm relatively new to Webpack and I am facing an issue with my ProvidePlugin configuration not working as intended.

Here is the code snippet from my file:

App.js

var App = function() {
    getSomething: function(size) {}
}();

module.exports = App;

I want to make sure that the 'App' variable is accessible globally, as it is being used in other files like this:

Layout.js

var Layout = function () {
    App.getSomething('md');
}();

webpack.config.js

In my webpack.config.js file, the following line is included:

new webpack.ProvidePlugin({ App: 'app' })

Below is how I define my entry:

entry: {
    'app': './angularApp/metronicapp.ts',
}

metronicapp.ts

app represents my app.js as shown above.

Upon checking the browser console, I encountered the error message: Cannot find module "app"

When compiling webpack in the terminal, the error states:

Module not found: Error: Can't resolve 'app'

I am trying to identify what could be causing this issue. Is there something wrong with my app.js code structure? Why is the App variable still not globally available?

Answer №1

Configuration File for Webpack

In order to use the ProvidePlugin in webpack, you must specify the path to your global module App.js.

const path = require('path');
...
plugins: [
  new webpack.ProvidePlugin({
    App: path.resolve(__dirname, './path_to_App.js')
  })
]

Type Declaration File for Global Variables

To avoid TypeScript errors related to undefined constructs, create a global declaration file named global.d.ts.

declare var App: any;

Custom TypeScript File for Metronic App

You do not need to explicitly import ./metronic/global/scripts/app inside metronicapp.ts, as webpack will resolve App during the build process.

App.getSomething('foo');

JavaScript File for Layout

var Layout = function() {
  App.getSomething('md');
}();

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

What is the best way to compare two values using protractor?

How to Extract Values from Element var projectOne = element.all(by.css('a[ng-click="setCurrentGroup(tab)"]')).get(6).getText().then(function(text){console.log(text);}) var projectTwo = element.all(by.css('a[ng-click="setCurrentGroupproject ...

Workspace Settings cannot be saved due to an unregistered configuration

I've been attempting to change the StatusBar color in VScode Setting.json using Configuration and Workspace. However, I encountered an error when trying to make the update: Error: Unable to write to Workspace Settings because workbench.colorCustomizat ...

Is it a common issue that sound.stop() doesn't seem to function properly, while sound.play() operates successfully within Howler

I am having trouble utilizing Howler.js in Reactjs with typescript. While I can successfully play the sound, pausing or stopping it seems to be an issue. Below is the code snippet: This component takes all the audio details as props. I used console.log() ...

What is causing this JavaScript to not function properly? (window.scrollTop)

One CSS class called 'stuck-sm' is included, but the class 'stuck-md' is not currently being added. if ($(window).scrollTop() >= 285) { $('.something').addClass('stuck-sm'); } else if ($(window).scrollTop() > ...

Running JavaScript within the destination of an Ajax request in a drag-and-drop shopping cart without the need for server-side code

My goal is to develop an Ajax Drag and Drop Shopping cart using solely javascript and ajax. The example on this page is currently my reference point. While it functions well with local jQuery, I aim to integrate ajax calls for the cart's functioning. ...

Nextjs is having trouble loading the Infogram script

Struggling to insert an Infogram into my project by pasting the script but it's not working as expected. All other scripts in _app.js are functioning properly, however, this particular script isn't loading the graphic even though it appears when ...

Avoiding data type conversion in JavaScript/TypeScript

Currently delving into the world of JavaScript, I come from a background of working with statically typed languages. Naturally, I opted to dive into TypeScript instead of starting directly with JS. While TypeScript is great and addresses many issues presen ...

Is it recommended to utilize `await` when invoking an `async` function within another `async` function?

In my code, there is an async function that calls another async function: const func1 = async () => {...} const func2 = async () => {func1()} I am curious whether it is necessary or redundant to use await when calling func1() inside func2 ? const f ...

Utilize the jsTimezoneDetect script to showcase a three-letter time zone code

I'm currently utilizing the jsTimezoneDetect script to identify the user's current timezone. The code below shows the result as America/Chicago. Is there a way to display CDT/CST instead (based on today's date)? var timezone = jstz.determin ...

What is the best way to merge javascript files and have them load after the page has already loaded on an asp.net site?

I recently came across a helpful SE Post that discussed combining external javascript files for better optimization, which is something I'm interested in. Following recommendations, I have converted internal javascripts into an external .js file and s ...

What is the best approach for implementing recursion within a foreach loop in TypeScript?

Problem Situation I am attempting to develop a customized typewriting effect similar to the one demonstrated here with a 100ms delay using Angular. The TypeScript code I have written for this purpose is as follows: private arr: string[] = ["Lead Dev ...

What are the steps to resolve the End of Expression issue in my Directive's markup?

Issue: $parse:ueoe Unexpected End of Expression Upon inspecting Chrome's console, the following error is displayed: <div ng-class="{" green-up":="" tgh.tag.direction="=" "positive",="" "red-down":="" "negative",="" ""="" :="" "stagnant"}"=""> ...

React - How to Close Material-UI Drawer from a Nested Menu

Currently, I am utilizing a fantastic example (here) to create a dynamic nested menu for my application. Taking it a step further, I am trying to integrate it into a Material UI appbar/temporary drawer. My goal is to close the drawer when the user clicks o ...

Shifting input and output elements from HTML to Typescript within an Angular framework

Is there a way to transfer all the Inputs and Outputs of a Parent Component into Typescript instead of HTML? I need to work with a Parent Component that has many parameters for sending and receiving data to a Child Component. I want to convert them to Typ ...

Ways to obtain an attribute through random selection

Figuring out how to retrieve the type attribute from the first input element: document.getElementById('button').addEventListener('click', function() { var type = document.querySelectorAll('input')[0].type; document.getE ...

Why won't my AngularJS checkbox stay checked?

In my application, I have the following code: <input type="checkbox" ng-checked="vm.eduToEdit.test" /> {{vm.eduToEdit.test}} <input type="checkbox" ng-model="vm.eduToEdit.test"> The value of vm.eduToEdit.test is displaying t ...

Is it possible to implement cross-domain login with Passport.js?

Is it possible for a user to log in from a different domain? For example, the main site has a login form that uses AJAX to post to a route on my Node.js server. // Submit form to Node server FROM WEBSITE $('#submit-project-form').submit(function ...

Managing location markers with Google Maps API V3: Saving and removing locations

I encountered an issue while using GMAP V3. After realizing the need to save map changes in a database, I struggled to find a way to accomplish this task. Before attempting any workarounds, I thought it would be best to gather some ideas first. The communi ...

Ball Bounce Component

I'm having an issue with a bouncing ball function that I created. The function displays a green bouncing ball on the screen and bounces it around. However, each time the function is called, the ball seems to pick up speed and its velocity increases dr ...

What is the method for extracting latitude and longitude values individually from JSON data?

Upon receiving the JSON response from the Google Maps API stored in a variable named 'obj', I noticed that alerting obj.name returns "Pancakes on the Rocks". To access the icon, I can use obj.icon. However, I am struggling to retrieve separate va ...