使用 webpack 通过文件共享变量 [英] Sharing variables through files with webpack

查看:32
本文介绍了使用 webpack 通过文件共享变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 2 个 js 文件.第一个文件:

I have 2 js files. First file:

var object1 = {
    foo: 'bar'
}

第二个文件

var object2 = {
    foo2: 'bar2'
}
console.log(object1.foo);

这两个文件是用 webpack 构建成 bundle.js 文件的.但在这种情况下,我遇到了麻烦 - 未定义 object1 变量.

These 2 files are build with webpack to bundle.js file. But in this case I have troubles - object1 variable is not defined.

我分析了 bundle.js 文件中的代码 - webpack 为每个文件匿名函数创建 - 我明白为什么我会出错.

I analyzed code in bundle.js file - webpack create for every file anonymous function - and I understand why I have error.

是否可以使用 webpack?

It's possible do with webpack or not ?

当然我可以将此变量用作全局变量,但我认为 - 这不是一个好主意.

Off course I can use this variable as global variable, but I think - it's not a good idea.

推荐答案

回答很简单,用require

Answer it's very simple, just use require

var object1 = require('./object1.js');
var object2 = {
    foo2: 'bar2'
}
console.log(object1.foo);

这篇关于使用 webpack 通过文件共享变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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