js文件结构
var test = 123;
require ('./custom/components/buttons.js');
require ('./custom/components/fixed-buttons.js');
require ('./custom/components/tabs.js');
require ('./custom/components/accordions.js');
require ('./custom/components/sliders');
然后如果你去 sliders.js 并做 console.log,你会得到这个错误:
sliders.js:296 Uncaught ReferenceError: test is not defined at Object.434 (sliders.js:296) at webpack_require (bootstrap 5dd9c166f83054f151df:54) at Object.171 (main.js:15) at webpack_require (bootstrap 5dd9c166f83054f151df:54)在 webpackJsonpCallback (bootstrap 5dd9c166f83054f151df:25) 在 main.js?v=1545639314088:1
在问题的上下文中:要在
test另一个模块(文件)中使用变量,您可以根据 ES-2015 规范使用导出和导入:或者使用 default 关键字只导出一个值(不需要大括号):
在这种情况下,我建议将 Webpack 与babel transpiler结合使用。
Webpack 还提供了一种使用 CommonJS 语法的方法。使用过 NodeJS 的人会很熟悉:
但是,您可以同时使用这两个选项。有关连接模块的所有方式的更多详细信息,请点击此处。
如果在项目构建后需要将变量导出到全局范围,那么它看起来像这样:
或者