ES2015 Export inside function - javascript

I am learning export feature of ES2015. I tried understanding it online but my doubts are still not resolved
When I declare export inside a anonymous function, jshint shows following error (at least inside Intellij plugin):
E053 Export declaration must be in global scope.
On the contrary, JSHint always asks to wrap up whole code inside Anonymous function. If I write code in following way:
export const MY_CONSTANT = 1000;
(function(){
'use strict';
//Complete code goes here
}();
We have to write a lot of code in top and bottom of the page. Some code will jump from between the file to the beginning (or end) of page.

The best way I can explain it is the javascript IIFE was way of creating encapsulation. You would place the code of your module inside one and return and object of some kind. If you needed to import code into it you would do so with the argument. The new module syntax lets you do the same in a different fashion. Think of the the imports as arguments to the IIFE and the exports as the return. Here is the full explanation for import export syntax from Mozilla https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
Further more if you want to explore more I have created some boilerplate that uses babel, gulp, browserify, and jasmine so I can write all of my code going forward as es2015. https://github.com/jamesrhaley/es2015-babel-gulp-jasmine.git

If you are using ES2015 module syntax you probably don't need to wrap your code in an anonymous function since the module loader handles what code is exported.
I'm not sure about every module loader but when using TypeScript + browserify, each file gets wrapped to prevent variables cluttering the global namespace. See Why must export import declarations be on top level in es2015 for more on how to work with the module syntax and why variables can be declared globally.

Related

Instantiate an object defined in module A and use its methods in module B javascript

I'm working in a web development project.
Right now i'm using a 3rd party library to instantiate an object of that library in a file called, let's say, fileA.js
so i do:
import libraryExport from "./librarymain.js"
var object = libraryExport( ... );
export default object;
Now, in fileB.js i want to use the methods that the instantiated object has, for example:
import object from "fileA.js"
object.methodOfTheLibrary();
However, when im running this in my browser console i always get "methodOfTheLibrary is not a function", which means, from my point of view, that the library is not being imported properly in fileB.js
Note: I'm using webpack to bundle all of my files and everything was compiling and bundling just fine until i came with issues. I usually know my way around C++ in an advanced way but for JS i just still don't fully understand how to solve these kind of import issues.
Thank you for any help
It's generally* recommended that you avoid using an imported module directly in the body of another module. (One of your own modules, that is... as you'll see in a moment, third-party modules are generally fine to use.)
The big issue is load order. If your fileA also imports some other module, which imports another module which then imports fileB, then fileB will attempt to run and, since fileA is still trying to load dependencies, object will not actually have been instantiated yet.
You'll either need to carefully review your dependencies to look for just such a loop and then eliminate it or, if possible, restructure fileA to wrap your code in a function that can be called once the entry point has finished loading (which will guarantee that all other modules have been resolved):
// fileB.js
import object from "fileA.js"
export function init() {
object.methodOfTheLibrary();
}
// main.js
import init from "fileB.js";
init();
* "generally" meaning that there are plenty of perfectly acceptable situations where it's fine. You just have to mindful of the pitfalls and mitigate against those situations.

Working with IIFE file that used to be an ES6 class-based file

I was working with an ES6 class-based file I developed but because of compatibility issues with IE11, I had to use RollupJS to transpile the class-based file to an Immediately Invoked Function Expression, the problem with that is that in the root index.js file, the class-based file was instantiated like so:
import { XCode } from './Library/Transform/xcode-es6.js';
import * as uIHandler from './Library/Transform/UIHandler.js'
try {
const handler = new uIHandler();
const sdk = XCode();
sdk.setHandler(handler);
}
We are getting an error where it cannot find the uIHandler, I believe the problem is not with the import statement up top, but that we can no longer instantiate an IIFE type file. If I am correct, what would the solution be here? I have very limited experience with IIFE.
You need to apply RollupJS to the entire program, and not just pieces of it.
It has converted UIHandler.js so it is no longer an ES6 module, so you can't treat it as one any more.

Javascript - Where are 'import' and 'export' statements legal?

I'm studying the new import, export feature in Javascript but was wondering, where in code will these statements be syntactically legal?
I understand something like the following won't be legal:
(function(){
import thing from './thing.js';
})();
but does this mean import is only legal at the top of the module script? Or in the global scope? E.g., what about this:
import a from './a.js';
(function(){
// ... do something with a ...
})();
import b from './b.js';
// ...
Also, does this limitation apply to export? E.g., will the following be legal?
(function(){
function internalFunc() {
// ...
}
export { internalFunc };
})();
I couldn't seem to find anything about this in the current drafts of the specification.
There is no such implementation in javascript. It's planned. But no browser implemented it yet. It's implemented in some transpilers like Webpack and Babel. There is also require in NodeJs. But not natively in javascript.
Other way to import files is using RequireJS library.
Reference: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Statements/import
Edit
Answering what you asked in comments: AFAIU in the already available implementations of import and export, yes they are available in the global space, and yes import and export are hoisted.
But what isn't very clear in your comment's question is what you mean by "only available in global space". There is no such this as a close space that can't acess global space. Global space is accessible everywhere, so are import and export.
My reading of the spec is that:
module export statements should be at top level of a module
module import statements should be at top level of a module
function-style module import expressions (which return a promise for the imported items) are allowed anywhere an expression is allowed
As you say, right now it's only supported in transpilers, so I'm not sure how closely existing transpilers (Babel) follow these rules.
1) If you want just to play with import, export statements, then use it without any transpilation (with webpack) in google chrome ;)
I always use ES6 modules while I make some R&D. And then only if my temporarily work worth it, I start to think about transpilation.
Just do not forget to include scripts in such way:
<script type="module" src="index.js"></script>
2) If you need to write some nodejs script, then turn on some experimental flag to use modules - https://nodejs.org/api/esm.html#esm_enabling

import auto invoking function binding this to window object

Inside a jest test, I need to import a javascript module that declare some global functions. This javascript module is autogenerated from django (ex jsi18n) and it's an auto invoking function
(function(globals) {
var django = globals.django || (globals.django = {});
...
}(this));
This is helpful for use the translation inside the react component. For example including a translation string in our .jsx file using a global defined function gettext()
<p>{ gettext('got it') }</p>
I've tried to import the module using the standard form
import './djangojs';
but jest report the error
TypeError: Cannot read property 'django' of undefined
because this it's undefined (strict mode). So I've tried to manual edit the module and adding at the end }(this || window)); and works correctly.
But the module is autogenerated every time. So how I can bind this to window for using the global object without manually editing the file?
Solution:
I have imported the django javascript modules directly using the setupFiles as #dfsq told
"setupFiles": [
"<rootDir>/path/to/jsi18n/djangojs.js",
"<rootDir>/path/to/js/reverse.js"
],
The problem is specific to Babel. Babel is commonly used in Jest testing rig, and it is likely used here.
Babel transform-es2015-modules-commonjs enables strict mode for both ES module imports and require, so this is undefined in imported module.
In order to make a piece of code executed in loose mode while its context is in strict mode, it should be evaluated in global context:
const fs = require('fs');
const script = fs.readFileSync(require.resolve('./djangojs')).toString();
new Function(script)(); // or (0, eval)(script);
instead of import './djangojs' or require('./djangojs').
It's expected that script doesn't have to be transpiled (it will be evaluated as is) and doesn't rely on the context (doesn't use require, because it's not available in global context). I.e. eval will work for regular script like ./djangojs but not for CommonJS module.
This may be useful if a module shouldn't be available globally or may vary between tests.
If it should be available for all tests then setupFiles should be used, as another answer suggests.

Babel.js using Import and Export not working

I'm trying to use import and export to create modules and it's not working.
I added https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.min.js to the index.html header and tried to import a js file and get an error message saying SyntaxError: import declarations may only appear at top level of a module. What can I possibly be doing wrong?
I know I can use require.js but rather use import and export.
HTML
script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.min.js"></script
JS File
import Mymodule from './modules/mymodule';
Babel cannot perform client-side transpiling of modules, or rather it is not universally supported by browsers. In fact, unless you use a plugin, Babel will transform import into require().
If I run the following code:
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.js"></script>
<script defer type="text/babel" data-presets="es2015">
import Mymod from './modules/module';
Mymod();
</script>
</head>
I get the following error:
Uncaught ReferenceError: require is not defined
From Babel Docs:
Compiling in the browser has a fairly limited use case, so if you are working on a production site you should be precompiling your scripts server-side. See setup build systems for more information.
Most people choose a pre-compiled module bundler like Webpack or Rollup.
If you really want to perform this client-side, use RequireJS with Babel run via a plugin, though you may need to use AMD syntax.
Native browser support for ES6 modules is still in early stages. But to my knowledge there isn't a preset/plugin available yet for Babel to tell it not to transform import/export statements.
The scripts that babel-standalone translates execute by default in global scope, so any symbols defined by them are automatically available to every other module. From that perspective, you don't need import/export statements in your modules.
However, you might be trying to maintain source files that can be used both by babel-standalone (e.g. for quick test environments, feature demonstrations, etc) and via bundlers such as webpack. In that case, you need to keep the import and export statements there for compatibility.
One way to make it work is to add extra symbols into the global scope that cause the import and export code that babel generates to have no effect (rather than causing an error as usually occurs). For example, export statements are compiled into code that looks like this:
Object.defineProperty (exports, "__esModule", {
value: true
});
exports.default = MyDefaultExportedClass;
This fails if there is no existing object called "exports". So give it one: I just give it a copy of the window object so anything interesting that gets defined is still accessible:
<script>
// this must run before any babel-compiled modules, so should probably
// be the first script in your page
window.exports = window;
import statements are translated to calls to require(). The result (or properties extracted from it) is assigned to the variable used as the identifier in the import statement. There's a little bit of complication around default imports, which are different depending on whether or not the result of require() contains the property __esModule. If it doesn't, things are easier (but then you can't support having both default and named exports in the same module ... if you need to do this, look at the code babel produces and figure out how to make it work).
So, we need a working version of require(). We can provide one by giving a static translation of module name to exported symbol/symbols. For example, in a demo page for a React component, I have the following implementation:
function require (module) {
if (module === "react") return React;
if (module === "react-dom") return ReactDOM;
}
For a module returning multiple symbols, you'd just return an object containing the symbols as properties.
This way, a statement like
`import React from "react";`
translates to code that is effectively:
`React = React;`
which is roughly what we want.

Categories