【问题标题】:How to define export for a module in javascript?如何在javascript中定义模块的导出?
【发布时间】:2017-09-30 07:30:51
【问题描述】:

嘿,我正在使用 react-app 做一个小项目,我 整天都在尝试为this module 创建导出。

我已经用 npm 安装了它,我想编辑它,以便我可以在我的 app.js 中导入和使用它

我尝试使用 class\function\let 定义“reddit”并使用:

export default
module.exports

还有一个

 import reddit from 'reddit.js';
 var reddit = require('reddit.js');

并尝试使用模块中的一个简单函数进行检查:

console.log(reddit.hot('cats'));

但我仍然得到:

Uncaught TypeError: reddit.hot is not a function

我有点迷茫,我做错了什么?

【问题讨论】:

    标签: javascript node.js reactjs create-react-app reddit


    【解决方案1】:

    模块使用 window.reddit 全局变量。不要覆盖它! 因此,如果您在客户端,只需使用:

    require('reddit.js')
    //...
    reddit.hot('cats')
    

    对于服务器端 - 您必须采取一些技巧才能使其正常工作,因为在服务器端您没有“窗口”全局变量。

    更新:

    后端使用示例:

    const window = {};
    const r = require('./reddit.js') // You don't really use r 
    const reddit = window.reddit;
    
    reddit.hot('cats')
    

    【讨论】:

    • 在服务器端,他们可以设置window = global
    • 带或不带 var reddit = ?没有我从 npm 开始得到“无法编译错误'reddit'未定义 no-undef”,我仍然得到 reddit.hot is not a function
    【解决方案2】:

    Reddit 不导出任何内容,因为它主要是为了添加为脚本标签而设计的!

    // So for CommonJS module:
    require('reddit.js');
    
    //And for ES6 modules
    import 'reddit.js';
    

    您将能够通过 window 对象访问 reddit 和 reddit.hot() 方法。

    【讨论】:

    • 感谢 import 'reddit.js';让reddit; reddit=window.reddit; console.log(reddit.hot('cats'));解决了。​​
    猜你喜欢
    • 1970-01-01
    • 2018-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    相关资源
    最近更新 更多