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
Related
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.
In many pieces of code I saw such expression:
require('babel-polyfill').default;
What does it mean property default, and where I can find all properties that could be applied to babel-polyfill, because I didn't see in Babel official documentation usage of this option.
This is an ES6 module convention, where someone is setting the "default" export of the module to a specific object. In ES6 syntax, it's equivalent to:
import Module from 'babel-polyfill'
which will take the default export from babel-polyfill and put it in your current file as Module.
And internally in the babel-polyfill library, they are doing
exports.default = { some: 'Object' }
This is different than named exports, where you want to expose specific named things from your library:
exports.someThing = 'value';
...
import { someThing } from 'that-module';
You can console.log the results of both require('babel-polyfill') and require('babel-polyfill').default to see more. However, babel polyfill mainly provides polyfills in the global namespace, and modifies native prototypes like Array, and you don't use anything from it directly. Simply requiring it has side effects that add correct polyfills to the running Javascript environment.
My code:
import $ from 'jquery'
import jQuery from 'jquery'
import owlCarousel from '../../node_modules/owlcarousel/owl-carousel/owl.carousel'
class App {
…
_initSlider() {
$("#partners-carousel").owlCarousel();
}
}
I have 'jQuery is not defined' in browser console. What's wrong?
I can use jQuery as $ in methods of this class, but not with name 'jQuery'.
According to this comment and apply it to your case, when you're doing:
import $ from 'jquery'
import jQuery from 'jquery'
you aren't actually using a named export.
The problem is that when you do import $ ..., import jQuery ... and then import 'owlCarousel' (which depends on jQuery), these are evaluated before, even if you declare window.jQuery = jquery right after importing jquery. That's one of the ways ES6 module semantics differs from CommonJS' require.
One way to get around this is to instead do this:
Create file jquery-global.js
// jquery-global.js
import jquery from 'jquery';
window.jQuery = jquery;
window.$ = jquery;
then import it in you main file:
// main.js
import './jquery-global.js';
import 'owlCarousel' from '../../node_modules/owlcarousel/owl-carousel/owl.carousel'
class App {
...
_initSlider() {
$("#partners-carousel").owlCarousel();
}
}
That way you make sure that the jQuery global is defined before owlCarousel is loaded.
#Serge You should have mentioned in your question that you are using browserify & babelify to bundle/transpile your code (I knew it from comments), this will help people find the correct answer to your question.
As of 2021, ECMA2015+/ES6+ don't allow the use of import-maps/bare-module-path natively in the browser. So basically you can't do the following directly in the browser, because the browser doesn't behave like nodejs, it doesn't understand how/where to fetch for the source of your scripts, you can't just say:
import $ from 'jquery'
import jQuery from 'jquery'
However, you can do this by the help of bundlers like WebPack which opens that door for import-maps/bare-module-path to be used in the browser. Besides, huge work is currently being done to support the implementation of import-maps directly in the browser without the need of bundlers, but it's not implemented yet. I know that this question is old enough for the OP to follow, but in general, you can use WebPack to bundle your code and import your dependencies the way you mentioned.
P.S. Regarding the answer proposed by #egel in Oct 2016 (which is an old answer with limited solutions at that time) some people asked for more clarifications. Please note the following statement by Nicolás Bevacqua regarding the scope of ES6+ modules:
Declarations in ES6 modules are scoped to that module. That means that any variables declared inside a module aren’t available to other modules unless they’re explicitly exported as part of the module’s API (and then imported in the module that wants to access them).
ES6+ module system is awesome and makes things much more organized, but can we fully implement ES6+ modules in the browser without the need of bundlers/transpilers? This is a tough question. Things may get harder when some of your JavaScript dependencies are just old/classic scripts that do not support the ES6+ modules system, and do not use the export keyword to export functions/values for you. Here, developers tend to do some workarounds to solve the problem in hand. The window object is used to attach functions/variables in order to use them across all modules. Here the window object is used as a carrier to transfer functions/data across different modules within your code base, and this is not a recommended approach though.
Below is quoted from javascript.info:
If we really need to make a window-level global variable, we can explicitly assign it to window and access as window.user. But that’s an exception requiring a good reason.
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.
Is there a way to use a CommonJS module on a site like plnkr, JSFiddle, or JS Bin?
I'd want to turn it into a global.
This is for easily providing demos without having to use UMD.
I'd find the Github repos and then reference the source files using rawgit.com.
requirebin is a jsbin like enviroment that allows for modules built using browserify, but I am not aware of a way to use an unpublished module
You can use https://www.skypack.dev/, it adjusts any npm package to be used in an ESM-ready environment
For example, if you want to use a library that uses UMD (Universal Module Definition) or CJS (Common JS), you can use skypack and the module will be converted to ESM (ES Modules).
Working case
The canvas-sketch-util/random library uses CJS to import and export some modules (it use require('something') inside), but the code is converted to ESM with that service, and can run directly in the user's browser
<script type="module">
// Use 'https://cdn.skypack.dev/' + 'npm package name' + '#version its optional'
import random from 'https://cdn.skypack.dev/canvas-sketch-util#1.10.0/random'
console.log('A random number: ', random.range(1,10))
</script>
Non-working case
The same library doesn't work if we use https://unpkg.com/, as it only distributes what is ready, and the code gives error (at the very beginning of the file there are already some require functions from CJS):
<script type="module">
import random from 'https://unpkg.com/canvas-sketch-util#1.10.0/random'
console.log('A random number: ', random.range(1,10))
</script>
Important
It's important to use type="module" inside the script, jsfiddle and codePen already do that, it can work locally too.
Each library has an export differently, you must understand how the library is being exported to be able to import it into your code. Here are some examples of different ways of importing, not all cases, you have to know which way of import is the right way.
<script type="module">
// Usually when don't have a default export
import * as libOne from 'https://cdn.skypack.dev/lib-one'
libOne.initSomething({someconf:true})
// OR
libOne(someParam1, someParam2)
// Usually when export is just one function/object
import libTwo from 'https://cdn.skypack.dev/lib-two'
libTwo(someParam1, someParam2)
// Usually when there are several things inside the lib and you only want to use one
import { libThree } from 'https://cdn.skypack.dev/lib-three'
libThree(someParam1, someParam2)
</script>
Final considerations - 2022
Their website ( https://www.skypack.dev/ ) says the following
Skypack is free to use for personal and commercial purposes, forever. The basic CDN is production-ready and is backed by Cloudflare, Google Cloud, and AWS. We're fully committed to building a core piece of infrastructure you can rely on.
So it seems to be something you can trust