简体   繁体   English

在Node.js中要求的正确方法是什么?

[英]What's the proper way to require in Node.js?

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. 我刚开始使用Node.js和Electron,我已经在文档和示例代码中看到了各种方法,如何需要模块。 Specifically, I am trying to follow this tutorial. 具体来说,我正在尝试按照教程。 In this particular example, I think I am requiring app which is in electron . 在这个特殊的例子中,我想我需要的是app ,它是electron

1) In the tutorial, it has you do: 1)在本教程中,您可以:

var app = require('app')

2) In the electron-quick-start example, which is provided by Electron to help you get started, they have you do: 2)在Electron提供的电子快速启动示例中,为了帮助您入门,他们可以:

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

3) In Electron documentation , they use: 3)在Electron文档中 ,他们使用:

const {app} = require('electron')

4) In an Electron boilerplate program , I found: 4)在Electron样板程序中 ,我发现:

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

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. 我在互联网上大多看到#1,似乎varconst基本上可以互换,因为你不修改这些模块。 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') )?. 我无法理解的是,如果app处于electron ,那么为什么#1直接需要它(而不是像require('electron.app') )? I am further confused because #4 seems to imply app is actually in electron.remote . 我更进一步感到困惑,因为#4似乎暗示app实际上是在electron.remoteelectron.remote Secondly, is #3 preferred because it's used in the documentation? 其次,#3是首选,因为它在文档中使用? Or is #4 preferred? 或者#4是首选? The comment in the program for #4 says "Use new ES6 modules syntax for everything". #4计划中的评论说“使用新的ES6模块语法”。 Does this mean this is the future of JavaScript? 这是否意味着这是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 no longer works in Electron v1.0+. #1不再适用于Electron v1.0 +。
  • #2 and #3 are equivalent, #3 just uses a destructuring assignment . #2#3是等价的, #3只使用解构赋值
  • #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. #4使用ESJ模块导入语法,NodeJS本身尚未处理,因此只有在使用Babel,TypeScript或其他可以将这些import语句转换为require语句的其他转换器转换代码时,它才有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM