How would a JS module be created? [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I'm a little confused on what to do here. I've seen a lot of people create modules in JS, but everyone usually does it differently. I've seen people wrap their WHOLE module in a (function(){})(); , or they declare an object literal, or do something crazy like window.Module = {};. I want to know what would be the best choice to be used (as in what you would think is most useful). Help would really be appreciated, and thanks.

There is only one official solution to create JavaScript modules. Anything else you have seen is either a polyfill for that solution, or a pale echo of the real thing.
The basic syntax is like so:
import otherStuff from "otherStuff.js";
var myThing = {};
myThing.stuff = function(){ /*...*/ };
myThing.do = function(){ otherStuff.doOther(); );
export default myThing;
It can get much more complicated, but the basics are:
Your module must be in a unique file. A file is a module.
Your module should probably export something, although this is not strictly necessary.
This is coming down the pipeline in JavaScript. Unfortunately, no one has been able to agree on the official specification of how to load the modules, so they are not on a track for any near-future release. That said, the specification is under development, and a polyfill that implements it has been created.
Your best bet to use the official module syntax is to run it through BabelJS and compile to a shim like Require (which uses the AMD format) so you can use it without the loader specification.
You can read more about the syntax here and here.

I would say : It depends on the final usage of your "module". If it's something that will be used internally, which means that no one else outside your business will use it, then anything can be used as long as you all agreed on the proper method. Otherwise, if it would be used by others : less global variables you create, better it is. As example, jQuery use "$" and "jQuery" as global variables (maybe others, but I'm not sure). When people adds modules to it, they always add them to window.jQuery.[Under jQuery var] where [Under jQuery var] shall be read on jQuery documentation for proper use.

Related

Is there a suitable or recommended design pattern for the airbnb style guide? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed last month.
Improve this question
I learned about the revealing module pattern which I've taken a liking to. This pattern was described as being useful for not polluting the global scope by wrapping a function in an IIFE and returning only public methods and variables.
const foo = (function() {
const _private = function() {
... do private stuff
}
const method = function(){
... do public stuff
}
return {
method: method
}
})();
export default foo
However, now that I am using esLint and the airbnb style guide, I got to the section about IIFE where it says:
7.2 Wrap immediately invoked function expressions in parentheses. eslint: wrap-iife jscs: requireParenthesesAroundIIFE
Why? An immediately invoked function expression is a single unit - wrapping both it, and its invocation parens, in parens, cleanly expresses this. Note that in a world with modules everywhere, you almost never need an IIFE.
So I understand that the revealing module pattern is best suited for avoiding polluting the global scope, and since modules are in a local scope it isn't needed in this context. My question is if there exist any design patterns that are well suited to the airbnb style guide, and better abide by the guide itself. The styleguide itself doesn't make mention of any design patterns.
Apologies in advance if this is subjective - I'm not looking for the best design pattern, but for one that is useful in the context of a project using the airbnb style guide, and module export/imports.
As stated by some of the comments below my question, the style guide deliberately avoids recommending any design patterns so as to be applicable to as many users as possible. Many higher level design patterns should not interfere with the linter config the way the revealing module pattern does.
As for the revealing module pattern, it is not really necessary to use in ES6 as long as your code is separated into modules. It might still be useful if you want to create different local scopes within the same module, but this kind of code can easily be separated into modules with their own global scopes to avoid scope pollution.

Javascript Custom Variable Syntax instead of var use $ [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am making a javascript library and wanted to make a custom variable syntax so instead of using var use $ like php. To be clear I DO NOT want to use PHP. I am making a special library for public use.
I honestly don't care if you give me a function I just really need to use $ instead of var please I really need this.
var x = 10; // Normal JavaScript variable
$x = 10; // Custom Variable Syntax which is what I would like
JavaScript provides no means to extend the language in this way.
If you want to invent your own syntax, you'll need to design your own programming language and transpile it to JavaScript (as CoffeeScript does, for example).
(NB: $x is a valid identifier in JavaScript, you just can't cause any variable name starting with a $ to be inferred (by JS) as being a locally scoped variable when you assign something to it. $x = 10; would therefore throw an error (or create a global if you weren't using strict mode)).
JavaScript Syntax is not customization and keywords can not be overloaded.
Language is language, you can't jump over it's rules. But you can look around, use it's native possibilities.
As I know- there is no option to write
$x = 10;
in javascript. Just no.
But you can dance like jQuery ($ as alias of window.jQuery- that's not solution, but just first think about similar actions).
Can you tell more about that problem? Why do you need that? Maybe there's simpler way?

JS: RequireJS strategy: require once or each time it is necessary? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
There is something I am confused while writing modern JS (ECMA6, NodeJS, React Native)
I have a core file, which requires most of the content I need, say app.js:
var dependency1 = require('dependency1');
var dependency2 = require('dependency2');
And in subfile1.js, I'll need to access dependency1 too. I see two ways to achieve this:
Solution 1: require once and forward to others
Should I write in app.js:
var subfile1 = require('./subfile1')(dependency1);
and in subfile1.js:
module.exports = function(dependency1) {
var subfile1;
// do many things;
return subfile1;
}
Solution 2: require each time
OR in app.js
var subfile1 = require('./subfile1');
and in subfile1.js:
var dependency1 = require('dependency1');
module.exports = subfile1;
Comparison
My intuition is that it is cleaner to use solution #1, because it builds only one instance of each dependency.
But on the other hand, it is much more painful to write, especially when dependencies start to become numerous.
Also it fails at the black-box effect, which is often appreciated when writing independent modules.
My understanding is that both solutions shouldn't make a difference iff the module is completely stateless (ie. not calling var dependency1 = new Dependency1()).
Which brings me several questions:
How can we be sure it is actually the case?
When I am writing modules, should I keep this in mind?
When using external modules, shouldn't the author precise whether it is stateless or not?
Is there a best practice out-there? (writing functional code?)
Ain't there a risk this becomes even less true with classes available in ES6?
Is there any impact memory-wise?
Is what I am saying somehow wrong?
Node.js's require internal behavior solves your problems since modules are cached. They will be created once and you retrieve the instance after. You do not have extra problems due to statefulness with your second method but the same behavior (which is, when using stateful modules, good to know).
Furthermore, you should not have to worry about a module dependencies when you want to use it (especially, you should not have to modify your main code when a dependency is added to a submodule, especially when it is not yours).
Therefore #2 is a better approach.
In app.js:
var subfile1 = require('./subfile1');
In subfile1.js:
var dependency1 = require('dependency1');
var subfile1;
// many things
module.exports = subfile1;

Organizing large javascript files [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I've started to accumulate quite a few lines of Javascript code for a website. Everything has been in one file so far and that file is becoming impossible to maintain. If there is an error in one line, the entire file breaks.
I've tried splitting the code up into multiple files but there are some shared methods across objects like: validateEmail(address).
Right now, I have my code organized into objects, like so:
var ProductPage = {
addToCartBtn: "#add-to-cart",
init: function() {
ProductPage.initAddToCartPopup();
ProductPage.initSidebar();
...
},
...
};
Then, I call ProductPage.init() on $(document).ready.
My issue is: when splitting ProductPage into a separate file as ContactPage, for example I cannot access ContactPage.validateEmail(). I believe this is because my code is wrapped in jQuery's:
(function ($) {
...
})(jQuery);
Does anyone have insight on how they have organized large systems of Javascript? Also, I plan on doing optimization with putting all of this into one file and compressing it. So, any method which will benefit both maintainability and ease of optimization would be awesome.
validateEmail like methods are functional in my opinion. By functional I mean, y = f(x). These functions are not changing the state but returning an output which are being computed on the passed input.
You might want to keep all this utility functional methods in a separate module and tag it to a global namespace. Make sure to load this(these) utility module(s) before utilizing them.
You can use require.js for dependency management.

How to organise Javascript functions within complex object [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I'm interested in how you guys lay out your Javascript objects/classes when they contain lots of functions, all of which need to be on the same 'level' (i.e. they need to remain as first level functions of the object).
So with a structure like this...
Namespace.class = {
abc: 1,
def: 2,
ghi: 3,
funcA: function(){
// Some logic
},
funcB: function(){
// Some logic
},
// Lots more functions
funcN: function(){
// Some logic
}
}
This can all get pretty unwieldy. How do you lay out these types of objects to make them readable, easy to maintain and quick for new developers to pick up?
My approach has been to organise everything in alphabetical order, so you know roughly where to go if you know a function's name.
But does it make more sense to group functions that are closely related in what they do and those that refer to eachother?
There are many approaches here and it depends on how exactly you interact with your code.
Some things to keep in mind:
1) If the code is unwieldy, a refactoring is probably overdue.
Consider breaking your class into smaller classes each dealing with different aspects of what the big class does. Split functionality in multiple namespaces if you use static functions rather than classes.
Consider splitting functionality over multiple files (one-class-per-file for example) and having a build process that combines and minifies your output.
2) Tools can help.
If you deal with large codebases it's probably a good idea to find an editor (or learn to use its functions better) that can help you deal with it. Your IDE will probably have some functionality to help you navigate the file structure better, like a file structure overview, or code regions, or objects view
3) Organize functions by what makes sense.
An alphabetic solution could make sense in some situations, but grouping by functionality is probably better. Putting exported methods all in one place is probably a good idea as well:
Namespace = function() {
var f1 = function() { };
var f2 = function() { }; // this is internal
// Exported methods
return {
f1 : f1
}
}();
4) Document your code.
While reading the code is invaluable in giving someone an in-depth understanding, code ducmentation is essential in having a first-glance understanding. It can also be useful to you during development because you don't have to remember all the quirks of your code.
5) Enforce a coding style that can help you.
Your coding style can help you find things in the code easier. If you always use the same spacing, put braces the same way, etc, finding a function definition can be as easy as Ctrl-f: myFunc:.
One approach is to modularize the class, and split it across multiple files. Typically this approach is used to provide plugins to a core class. jQuery is a great example of where the class has been extended using plugins.
When you're not interested in splitting the same class across multiple files, I find alphabetizing the function order helps.
In the end the order of the functions shouldn't matter so long as you have a good enough IDE that it lets you jump to the definition for that function.
God objects are an anti-pattern and a good indicator that you have some serious design flaws.
If you follow the single responsability principle and have a smart IDE that supports intellisense and other similar features, the investment for trying to keep everything ordered is not worth and not necessary since that would be the IDE's job to show all function definitions ordered in a panel for quick-access and to have a global overview.
If you really want to order your functions you could have an automated process that keeps your object literals structured.
However that doesn't mean you shouldn't have any coding standards. I also still organize my code in a way that makes sense e.g. private/public/priviledged members together.

Categories