ES6 modules: Are functions and variables not available in global space - es6-modules

Is everything in ES6 part of module.
eg. if I write in a file.
function simpleFunc(){
console.log("test")
}
Is this function not available to code in other places. In regular javascript , this function can also be executed from within html script.
What is the whole concept of modules. I understand polluting global namespace is a bad practice , but when we export a function or const, is it just an approach to avoid polluting global namespace. Can a developer still write var a= 10 in a js file and waste all the efforts of maintaining modules. I suppose this would still be possible because es6 is supposed to be backwards compatible with js.
Simply my question boils down to: Is a js file different when the language is ES6.

Not sure why no-one has answered this question yet, it's a simple answer, so I will answer it in case anyone else stumbles onto it:
Javascript is javascript.
ES5 practices still apply to ES6 in terms of script placement. Modularization allows you to import code from one script to another - this can help you keep large applications maintainable as well as many other structural benefits.
Additionally you are right about not polluting the global namespace - modules are also namespace containers, which protects the global namespace.
Here's a quote from a good (full) explanation to the importance of modules:
Modularization is the basic necessity for any software development. Breaking things into smaller pieces of functionality gives us the power to reuse the code. Modules are also containers for the namespaces.

Related

Clojurescript decoupled file & namespace?

I'm using reagent to build several alternate root components, only one of which will be mounted on any given page; definitely either/or. These have a degree of commonality in their makeup, hence it will be convenient to move what is common among them to a common namespace.
What would be ideal is if in the file for each of these components I had the option to switch namespace into common, and add defs particular to the component, then switch back, thus avoiding circular dependencies nor needing any kind of inheritance.
I recalled this being possible in common lisp, how wonderful it was, and it also seems possible in clojure.
From Clojurescript docs: ns must be the first form and can only be used once, and in-ns is only usable from the repl.
I'm wondering if there's a way to achieve this kind of thing in clojurescript which is still eluding me.
If not I may need to reconsider my assumptions behind multiple alternate root components; the "many builds within one build" kind of idea, if that makes sense.
Update after some futher experimentation and confusion:
another option might be to split a single namespace across multiple files (is this possible?). Not sure what direction to turn in here.
The fact that in reagent I am using atoms in the global namespace is what's creating the need for circular dependencies if I use a separate namespace for common. Hence, wonder about one global namespace, in which case multiple files might help. Or is the way forward one giant file and one namespace??
Update: I've realised there is a great tension between keeping all app state globally (in my current case, multiple atoms), and passing app state around. My pattern currently is everything global, don't pass any of it around. Passing the necessary state as parameters to fns in the common namespace would solve the problem here (duh!), but then there's the question of what principles are being followed here regarding app state. If I just added a param whenever I needed one, but started with the idea that everything was global, there'd be no real principle to it...
In ClojureScript, everything is pre-compiled into a single static JavaScript "executable", so there is nothing like the repl you are used to in Clojure. Indeed, in CLJS the "Var" concept doesn't really after the compiler, they are just static (constant) variables and cannot be rebound.
Having said that, CLJS does emulate the behavior of Clojure dynamic variables via the binding form, so that may help you to reach your goal. As in CLJ, it creates what amounts to a (thread-local) global variable. This is a degenerate case in CLJS since there is only one thread. However, the source code looks identical to the CLJ case.
Another way to accomplish this is to just use a plain atom as a global variable so you don't have to pass a parameter around.
As always, when using a global variable, it reduces the number of parameters in function call trees, but it creates invisible dependencies between different parts of the code. Somethimes convenient, but usually a bad tradeoff.

Public/private moethod declaration-only on ES6 classes with babel

I'm using Babel with default es2015 preset to convert ES6 JS code. Since I'm working in another project with TypeScript, I've come to appreciate the publi/private annotation on methods.
I'd like to use the same annotation in JS code. Even if it won't actually make methods on the exported object private, I find it useful to know quickly if a method is used by other classes, or not.
Is there a Babel plugin or other means to strip away all public/private declarations, so I can use it in my code? even without namespace checking that would still be very helpful.
There is a current proposal for "Private Fields" that is in the process of being implemented, but it not part of Babel yet. In the next month or two I'd expect it to be available.

Minify ceylon-sdk and ceylon-language when compiling to javascript

For an in-browser application written in ceylon-js it would be desirable to reduce the size of the ceylon.language-1.2.0.js file to only that what is actually needed.
This question was answered already.
How to use ceylon js (also with google closure compiler)
But the given solution involves manually editing javascript code resulting from compilation. This is not desirable since a compiler should produce code that hasnĀ“t to be edited manually after compilation (abstraction).
And it is not clear to me if google closure compiler can cope with the ceylon flavour of it in a reliable way.
Is it instead a solution to copy ceylon.language source in ceylon into the project and import only those parts of ceylon.language into the project that are required by it? Then compile to javascript. And then leave away ceylon.language-1.2.0.js at all from the client / in-browser application.
Now my questions:
What parts are needed in the most simple browser application? I think of something like Array(String) and the like.
Has that solution a chance to work absolutely reliable?
Will there be a better solution coming from the authors of ceylon that make this attempt obsolete?
The compilation of the language module to JS is a tricky process, because of the native stuff involved and because there are a couple of declarations that have to be in a certain order for things to work.
Minification is still pending, we are going to do it but it's not the highest priority right now, and we have to determine the best way to solve this problem; one option that has been discussed is to have a version of the language module without any metamodel info, for example.

Share a JavaScript library's namespace or use your own?

It is fairly well known in JavaScript that declaring variables within the global scope is a bad thing. So code I tend to work on contains namespaced JavaScript.
There seems to be two different approaches taken to this -
Adding your application specific functions to the libraries' namespace e.g. $.myCarouselfunction
Creating your own namespace e.g. MyApplication.myCarouselFunction
I wanted to know whether or not there is a better solution or if they tend to meet somewhere close in terms of pros and cons.
The reason for me personally deciding not to go with the library so far is for Seperation / Isolation / Lack of conflict with library code and potential plugins that are likely to share that namespace. Is there more to this that I'm not considering?
I think the most important thing in choosing this sort of thing is semantics.
Does your function/class extend or depend on a library-specific feature? Put it in the library namespace.
Is your function/class library-independent? In this case, it is better to put it in a custom namespace. This makes it possible to reuse your code outside the the library you originally used it with.
Personally I like this sort of approach:
(function(namespace) {
function myPrivateFunction(){};
namespace.myPublicFunction = function(){};
})($); // passing the $ namespace, but if it clutters,
// we can change it to something else
If you've ever tried to pull in more than one library using the same namespace, it can be surprising how likely collisions are to occur, and it can be quite frustrating in that these sorts of bugs often crop up in surprising and hard to debug ways. I think that your intuition about collisions is correct, and that the most import consideration as to whether to define your own namespace or reuse someone else's is to respect namespace ownership. That means that that unless you are in contact with the people who maintain another namespace and they know what you are doing, it's a good idea to use your own namespace.
If you do decide to ignore the advice on namespace ownership and define an API on an existing namespace (for semantics or whatever), one thing to consider would be to use an export function to detect errors. Basically, you can first define something on your own namespace, and then export it to the target namespace, along the lines of:
MyApplication.exportName = function(objToExportTo, name, obj) {
if (objToExportTo[name] === undefined) {
objToExportTo[name] = obj;
} else {
// Possibly assert!
}
};
MyApplication.myCarouselFunction = function() { ... };
MyApplication.exportName($, 'myCarouselFunction', MyApplication.myCarouselFunction);
I tend to prefer adding custom code to the library myself. The biggest reason for that is so that the usage semantics remain consistent across the built-in code and my custom code. That being said I can't really think of any technical advantages or disadvantages to this approach. I think your concern about conflicts is valid, though probably not very likely (if you end up with a component/module that conflicts with one of your custom functions, chances are it will be because you are replacing your code with someone else's).
The correct choice depends on your target environment. You're choosing between two namespaces, both of which can become arbitrarily cluttered. If you think it's more likely that you'll encounter a conflict in the library namespace, you should use the window namespace. If you think the window namespace is more likely to get cluttered, choose the library namespace.
In either case, you usually should only create one "global" name. In other words, if you're going to put your function in the library's namespace, it's best not to name it $.myFn. Name it $.yaya3.myFn and then cache a local reference to it in any context where you're calling myFn multiple times.
One best practice for referencing your function is to pass the namespace that it lives in as an argument to an anonymous function:
(function (yaya3) {
var myFn = yaya3.myFn;
myFn("frobnard!");
}(window.yaya3)); // you could instead pass $.yaya3 or YUI.namespace("yaya3") here
This makes it much easier if you discover that you need to move to a different namespace.

Hiding Complexity by Building Concise Libraries

I'm developing a product with a bunch of interlocking pieces (server, client, libraries, etc) and one of the pieces is a tiny library that users will link into their own client-side code (something kind of like the Flickr API or the Google Maps API). Once they've included that library, all of the interlocking bits magically hook themselves together. So API simplicity is a major, important goal.
The API that I expose to users has a grand total of two classes and seven public methods. Easy peasy, lemon-squeezy.
But the simplicity is a carefully crafted illusion. The library I'm distributing actually depends on another library, with 136 classes of its own (and more than a thousand public methods). During the build process, I link the two libraries together into a single deliverable, for ease of integration and deployment by the API consumer.
The problem I'm facing now is that I don't want the end user (an application developer integrating my software to enhance their own functionality) to ever be bothered with all that extra cruft, drowning in a torrent of unnecessary complexity.
From the outside, the library should look like it contains exactly two public classes, with exactly seven public methods.
How do you handle this sort of thing in your own projects? I'm interested in the language agnostic solutions, as well as the various techniques for different languages, compilers, and build tools.
In my specific case, I'm developing for the flash platform (AIR/Flex/Actionscript) with SWC library files. The build methodology is analagous to the Java platform, where all classes are bundled into a zipped code module with equal visibility (an Actionscript SWC file is, conceptually, almost exactly identical to a Java JAR file).
Doesn't .NET have an "internal" modifier for classes and methods? That's exactly the sort of thing I'm looking for, and if anyone knows of a tricky technique to hide the visibility of classes between SWC boundaries, I'd love to hear it.
It's pretty hard to hide things in AS. There is an internal access specifier and there are also namespaces. Adobe has some help on Packages and namespaces that may be useful to you.
It is important to note that namespaces do not limit access - they are really used to place symbols into a different ... well namespace. This could be used to have 2 versions of the same library accessed in the same swf. My guess is it just does some name-mangling behind the scenes before inserting definitions into the symbol table. If users want, they can just import the namespace and access anything that is "hidden" behind it. I've done that when hacking apart Adobe components. That said, if the user doesn't have the original source and is incapable of determining the namespace identifier than you have a bit of security through obscurity.
package access specifiers (e.g. private and internal) are closer to what you want. But if you can access classes outside package boundaries then the user can too. There are even hacks I've seen around that can examine a swfc and spit out a list of embedded classes which one can use getClassByDefinition to instantiate.
So, you can hide the classes existence in your documentation, use internal and private access specifiers wherever possible and then use namespaces to mangle the classnames. But you cannot prevent a determined person from finding and using these classes.
I think you can pull this off by using namespaces:
http://livedocs.adobe.com/flash/9.0/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00000040.html
Notice that namespaces is not the same in actionscript as in C#, it is more like namespaces in xml.
Incidentally, one of the other tricks that I've used (since I didn't know about the "internal" modifier or namespaces) is to hide classes by declaring them outside the current package, like this:
package com.example {
public class A {
// ...
}
}
class B {
// ...
}
class C {
// ...
}
I've even though about writing a little tool that will analyze all the "import" directives within a project and move all external dependencies into these kinds of hidden private classes.