Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

javascript - Use of require(lib) versus <script> in Electron apps

I don't have a handle on when to use require('jslib') versus <script src=""></script> in Electron content pages (e.g. index.html). With jQuery, I discovered that it needs to be loaded as follows:

<script>window.$ = window.jQuery = require('./js/jquery-2.2.4.min.js');</script>

I need to start using some other libraries (e.g. Handlebars, ds3.js, Bootstrap, etc.) and I am not sure if I should be loading those with the <script> tag or if I should require them.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Some libraries only expose their variables through a CommonJS interface. Others, like jQuery, will also expose them as global variables.

The reason you can't just do <script src="..."></script> for a library that only exposes through CommonJS is that it won't bind to the global space.

Binding with CommonJS

module.exports = myLibrary;

Bindings to the global scope

window.myLibrary = myLibrary;

If a library only does the former then you will not be able to access the value without using require. If a library only does the latter, then you will not be able to access it with require in the sense of const myLibrary = require('my-library')

In general, it's a better idea to use CommonJS over global variables. Adding variables to the global scope can lead to name collisions and directly loading in your dependencies makes it easier for the next person to tell where that dependency came from. Not to mention, CommonJS allows static analysis tools to work better so you're more likely to get relevant code completions and type definitions.

Using the example of jQuery, it would be better to use it like this.

// main.js
const $ = require('./js/jquery-2.2.4.min.js');
// could also be done like this if you install it as a Node dependency
// const $ = require('jquery');

$(document).ready(...);

<!-- index.html -->
...
<script src="main.js"></script>

TL;DR

Use require('my-library') when possible, load them as globals when it is not.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...