首页 > 解决方案 > js 捆绑包和范围混淆

问题描述

我试图更好地理解带有节点组件和其他 js 的 webpacked 包中的范围。

假设我的入口导入了八个要捆绑的文件: // entry point import './components/file1'; 导入'./components/file2'; ...导入'./components/file8';

并假设在 file1.js 我有:

// file1.js

let bubbles = () => {
  console.log('likes cats');
};

// or

function bubbles() {
  console.log('likes cats');
}

那么,如果我在 files8 中有这个(最后导入),为什么会引发未定义的错误?如何调用在其他导入中声明的函数?

// file8.js

bubbles(); // fails in any file other than file1.js where it's declared.

标签: javascriptnode.jsscope

解决方案


您需要export在打算从外部访问的函数/原语上显式使用:

https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export


推荐阅读