Webpack ProvidePlugin global variable (module cannot be found)

I am new to Webpack but cannot understand why my ProvidePlugin call does not work as expected.

I have the following file:

App.js

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

I want the "App" variable to be available globally because other files use it like this:

Layout.js

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

webpack.config.js

In webpack.config.js I have the following line:

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

This is my entry:

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

metronicapp.ts

  import './metronic/global/scripts/app'; 

Where app is my app.js which is displayed above.

The following error appears in the browser: Cannot find module "app"

And when I compile webpack in the console: Module not found: Error: Can't resolve 'app'

I can’t understand what I’m missing. Is app.js app not in the correct format? Why is the app still unavailable worldwide?

+5
source share
1 answer

webpack.config.js

ProvidePlugin needs a path to your global App.js module.

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

global.d.ts

For Typescript, don't complain about the undefined create global.d.ts

 declare var App: any; 

metronicapp.ts

No need to import ./metronic/global/scripts/app inside metronicapp.ts , webpack will allow the App to build.

 App.getSomething('foo'); 

Layout.js

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

Source: https://habr.com/ru/post/1273926/


All Articles