Node.js中要求的正确方法是什么? [英] What's the proper way to require in Node.js?

查看:110
本文介绍了Node.js中要求的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我才刚开始使用Node.js和Electron,并且在文档和示例代码中已经看到了有关如何要求模块的各种方式.具体来说,我正在尝试教程.在这个特定示例中,我认为我需要electron中的app.

I'm just getting started with Node.js and Electron, and I've seen various ways both in the documentation and in example code on how to require modules. Specifically, I am trying to follow this tutorial. In this particular example, I think I am requiring app which is in electron.

1)在本教程中,您可以执行以下操作:

1) In the tutorial, it has you do:

var app = require('app')

2)在 electron-quick-start 示例中,该示例由Electron提供为了帮助您入门,他们可以帮助您:

2) In the electron-quick-start example, which is provided by Electron to help you get started, they have you do:

const electron = require('electron')
const app = electron.app

3)在电子文档中,他们使用:

3) In Electron documentation, they use:

const {app} = require('electron')

4)在电子样板程序中,我发现:

import { remote } from 'electron'
var app = remote.app

这是怎么回事?我大多数人在Internet上看到过#1,而且varconst似乎可以互换,因为您不需要修改这些模块.我无法理解的是,如果app位于electron中,那么为什么#1可以直接要求它(而不是诸如require('electron.app')之类的东西)?我进一步感到困惑,因为#4似乎暗示app实际上在electron.remote中.其次,因为在文档中使用了#3是首选吗?还是#4是首选?程序中针对#4的注释为对所有内容使用新的ES6模块语法".这是否意味着这就是JavaScript的未来?当然,我想知道这些仅仅是语法上的差异还是它们实际上影响了程序的运行方式.

What is going on here? I have mostly seen #1 around the Internet, and it seems that var and const can be essentially interchanged because you don't modify these modules. What I'm failing to understand is if app is in electron, then why can #1 directly require it (rather than something like require('electron.app'))?. I am further confused because #4 seems to imply app is actually in electron.remote. Secondly, is #3 preferred because it's used in the documentation? Or is #4 preferred? The comment in the program for #4 says "Use new ES6 modules syntax for everything". Does this mean this is the future of JavaScript? And of course, I would like to know if these are just syntactic differences or if they actually affect how the program is run.

推荐答案

  • #1在Electron v1.0 +中不再起作用.
  • #2#3是等效的,#3仅使用破坏性作业.
  • #4使用 ES6模块导入语法哪个NodeJS尚未本地处理,因此仅当您使用Babel或TypeScript或其他可以将这些import语句转换为require语句的其他编译器来编译代码时,它才有效.
    • #1 no longer works in Electron v1.0+.
    • #2 and #3 are equivalent, #3 just uses a destructuring assignment.
    • #4 uses ES6 module import syntax which NodeJS doesn't handle natively yet, so it only works if you transpile your code with Babel, or TypeScript, or some other transpiler that can transform those import statements to require statements.
    • 这篇关于Node.js中要求的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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