Webpack ProvidePlugin全局变量(找不到模块) [英] Webpack ProvidePlugin global variable (Cannot find module)

查看:660
本文介绍了Webpack ProvidePlugin全局变量(找不到模块)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Webpack很新,​​但无法弄清楚为什么我的ProvidePlugin调用没有按预期工作。



我有以下文件:



App.js



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

module.exports = App;

我希望这个'App'变量可以全局访问,因为其他文件使用它是这样的:



Layout.js



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



webpack.config.js



In webpack.config.js我有以下几行:

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

这是我的条目:

 条目:{
'app':'。/ angularApp / metronicapp.ts',
}



metronicapp.ts



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

其中 app 是我的 app.js 显示在上面。



我在浏览器中收到以下错误:
无法找到模块app



当我在控制台中编译webpack时:
找不到模块:错误:无法解析'app'



<我无法想象我错过了什么。我的app.js格式不正确吗?为什么 App 仍然无法全局使用?

解决方案

webpack.config。 js



ProvidePlugin 需要全局模块的路径 App.js

  const path = require('path'); 
...
插件:[
new webpack.ProvidePlugin({
App:path.resolve(__ dirname,'。/ path_to_App.js')
})
]



global.d.ts



对于Typescript,不要抱怨未定义的构造创建
global.d.ts

  declare var App:any; 



metronicapp.ts



无需导入 ./ metronic / global / scripts / app metronicapp.ts 内,webpack将解析应用构建。

  App.getSomething('foo'); 



Layout.js



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


I'm pretty new to Webpack, but can't figure out why my ProvidePlugin call is not working as expected.

I have the following file:

App.js

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

module.exports = App;

I want this 'App' variable to be globally accessible 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.

I get the following error 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 figure what I'm missing. Is my app.js not in the correct format? Why is App still not available globally?

解决方案

webpack.config.js

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

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

global.d.ts

For Typescript not to complain about undefined constructs create global.d.ts

declare var App: any;

metronicapp.ts

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

App.getSomething('foo');

Layout.js

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

这篇关于Webpack ProvidePlugin全局变量(找不到模块)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆