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.
Related
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.
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
I'm making a JavaScript library that can accept various plugins from an external library (cwl-svg). In this library I want to check what kind of plugin they are, so I use code along the lines of this:
import {SVGArrangePlugin} from "cwl-svg";
export default function myFunction(plugins){
for (plugin of plugins)
if (plugin instanceof SVGArrangePlugin)
doSomething();
Then, when I build my library, webpack adds the cwl-svg library to my bundle, as it should.
Now lets say the user of my library writes the following code:
import {SVGArrangePlugin} from "cwl-svg";
import func from "my-library";
func([new SVGArrangePlugin()]);
The problem is that when the user passes in a plugin to this function with new SVGArrangePlugin(), they are passing in an instance of the class from their own version of the cwl-svg library, because my library has its own bundled version. Thus, plugin instanceof SVGArrangePlugin always returns false, even though plugin is identical to an instance of that class.
How do I ensure plugin instanceof SVGArrangePlugin returns true using webpack? I considered having my library import cwl-svg using externals, but that seems to be for libraries that export themselves to the window object, when I would rather keep everything contained in my modules. Is there an obvious design decision I'm missing here?
externals is exactly what you want. It's not only useful for libraries that export something to the global object, webpack still declares it as an explicit dependency. From the docs:
The external library may be available in any of these forms:
root: The library should be available as a global variable (e.g. via a script tag).
commonjs: The library should be available as a CommonJS module.
commonjs2: Similar to the above but where the export is module.exports.default.
amd: Similar to commonjs but using AMD module system.
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.
I recently started using Webpack for frontend and came across the issue with modules.
For example, I have two modules, one uses another (to be specific its angular-bootstrap-slider and bootstrap-slider). angular-bootstrap-slider was failing to initialize due the fact that Slider function was undefined.
Now I understand that I can either export Slider globally (which I did with jquery and angular libs) or import Slider in angular-bootstrap-slider (I picked that).
I don't like both options, because global exports is one of the things I wanted to avoid using webpack and importing something in library means changing it's code.
So am I missing something or maybe there is some best practice to deal with dependencies?
What you are looking for is shimming modules.
This allows you to declare that Slider is in fact to be imported from the module bootstrap-slider:
...
plugins: [
new webpack.ProvidePlugin({
'Slider': 'bootstrap-slider'
})
]
I think you can use imports-loader: https://github.com/webpack/imports-loader
imports loader for webpack
Can be used to inject variables into the scope of a module. This is
especially useful if third-party modules are relying on global
variables like $ or this being the window object.