Webpack:多个js文件的单一范围? [英] Webpack: single scope for multiple js files?

查看:36
本文介绍了Webpack:多个js文件的单一范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象两个 javascript 文件和一个入口点文件:

Imagine two javascript files and one entry point file:

app.js:

require(a.js);
require(b.js);

a.js:

var a = 4;

b.js:

var b = a+1;
console.debug(b);

不幸的是,这不起作用,因为文件 a 的上下文在文件 b 中丢失了,这意味着 b.js 不知道任何名为 a 的变量.

This unfortunately does not work because the context of file a is lost in file b, meaning b.js does not know of any variable called a.

如何使用 Webpack 解决这个问题 - 我只想得到与

How can I fix that using Webpack - I simply want get the same result as

<script src="a.js"></script>
<script src="b.js"></script>

具有通过 Webpack 进行捆绑的附加效果.

with the added effect of bundling through Webpack.

推荐答案

使用 ES2015 模块(可能不适合您,您可以使用 require 代替)

Using ES2015 modules (which may not be available for you, you can use require instead)

a.js:

export var a = 4;

b.js

import { a } from "./b.js";
var b = a+1;
console.debug(b);

Webpack 是一个模块构建/捆绑系统,它通过从 javascript 文件创建 UMD(通用模块)来工作.您必须导入/导出这些模块才能使它们在范围内.

Webpack is a module building/bundling system that works by creating UMD (universal modules) from javascript files. You have to import/export these modules in order for them to be in scope.

这篇关于Webpack:多个js文件的单一范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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