问题描述
说我有一个文件:
//nonModuled.js
//A non moduled file , let's say I can't "module" it
console.log('0');
function go(a)
{
console.log('go:' + a);
}
我还有另一个文件,我想获取 go
函数:
And I have another file which I want to get the go
function :
//1.js
require('./nonModuled.js');
当我运行 html 文件时,我确实看到了 console.log
,但是我收到了 go
函数的错误:
When I run the html file , I do see the console.log
, But I get an error for the go
function :
我明白为什么会这样.另外 - 我知道我可以做这个补丁:
I do understand why it's happening. Also - I know that I can do this patch :
//nonModuled.js
//A non moduled file , let's say I can't touch it
console.log('hello');
window.go = function go(a)
{
console.log('go:' + a);
}
然后在 1.js
文件中,访问 window.go
但这似乎很笨拙.
And then in the 1.js
file , access window.go
but that seems clumsy.
所以我问:
问题:
如何正确获取go
功能?
如果我能做这样的事情就好了:
It would be nice if I could do something like :
var a= require('./nonModuled.js');
a.go()
有什么帮助吗?
推荐答案
如果您无法使 nonModule.js
正确导出 go
,您可以使用 exports loader 来导入它:
If you're unable to make nonModule.js
properly export go
, you could use the exports loader to import it:
const go = require('exports-loader?go!./nonModule.js');
这篇关于Webpack - 从非模块文件加载函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!