简体   繁体   English

Webpack捆绑简单的JS文件

[英]Webpack bundling simple JS files

I realize this might prove a total misunderstanding of what Webpack is for but I've not been able to find a straight answer anywhere. 我意识到这可能完全误解了Webpack的用途 ,但是我在任何地方都找不到一个直接的答案。

Basically I have two files: 基本上我有两个文件:

hello.js hello.js

function hello() {
    console.log('Hello, world!');
}

entry.js entry.js

require('./hello.js');

hello(); // should log 'Hello, world!'

I wanted to pack them into a single file for faster loading using Webpack . 我想将它们打包到一个文件中,以便使用Webpack更快地加载。 My condition was that I should not have to modify hello.js in any way (let's say it is a big, obfuscated library that I don't have the right to modify). 我的条件是我不必以任何方式修改hello.js (假设它是一个庞大的,混淆的库,我无权修改)。

I expected that running 我希望跑步

webpack entry.js result.js

will give me a usable bundle in result.js but instead result.js gives me this error: 将在result.js给我可用的捆绑包,但是result.js却给我这个错误:

Uncaught ReferenceError: hello is not defined

Is there a way to achieve what I want? 有没有办法实现我想要的? Just simply bundle scripts together to make them available in the global namespace without having to add anything to them ? 只是简单地将脚本捆绑在一起,以使它们在全局名称空间中可用,而无需向其添加任何内容?

File hello.js is not exporting anything, you have to export hello function from hello.js file like this, 文件hello.js没有导出任何内容,您必须像这样从hello.js文件中导出hello函数,

module.exports = function () {
  console.log('Hello, world!');
}

and then in your entry file. 然后在您的输入文件中。

var hello = require('./hello.js');
hello();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM