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

人走茶凉 提交于 2019-12-10 19:19:07

问题


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) In the tutorial, it has you do:

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:

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

3) In Electron documentation, they use:

const {app} = require('electron')

4) In an Electron boilerplate program, I found:

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. 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:


  • #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.


来源:https://stackoverflow.com/questions/39257088/whats-the-proper-way-to-require-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!