When saving the file, the extension operation is blocked
(ES6) What is the difference between "import * as" compared to importing a class?
Pass options to ES6 module imports
es6 modules - How can I use an ES6 import in Node.js? - Stack Overflow
Videos
(Note: assuming both view1 and view2 have the same functions/methods and variables/properties)
What is the difference between
import * as view1 from './view1.js';
which has a bunch of function and variables being exported.
----------
That being compared to
import view2 from './view2.js';
which exports one object initialized from an object initialized from a function constructor that contains functions(methods) and variables(properties).
I was learning about mvc architecture from a video and they used a function constructor instead of exporting a bunch of functions and variables. Is there an advantage to this?
There is no way to do this with a single import statement, it does not allow for invocations.
So you wouldn't call it directly, but you can basically do just the same what commonjs does with default exports:
// module.js
export default function(options) {
return {
// actual module
}
}
// main.js
import m from 'module';
var x = m(someoptions);
Alternatively, if you use a module loader that supports monadic promises, you might be able to do something like
System.import('module').ap(someoptions).then(function(x) {
…
});
With the new import operator it might become
const promise = import('module').then(m => m.default(someoptions));
or
const x = (await import('module')).default(someoptions)
however you probably don't want a dynamic import but a static one.
Concept
Here's my solution using ES6
Very much inline with @Bergi's response, this is the "template" I use when creating imports that need parameters passed for class declarations. This is used on an isomorphic framework I'm writing, so will work with a transpiler in the browser and in node.js (I use Babel with Webpack):
./MyClass.js
export default (Param1, Param2) => class MyClass {
constructor(){
console.log( Param1 );
}
}
./main.js
import MyClassFactory from './MyClass.js';
let MyClass = MyClassFactory('foo', 'bar');
let myInstance = new MyClass();
The above will output foo in a console
EDIT
Real World Example
For a real world example, I'm using this to pass in a namespace for accessing other classes and instances within a framework. Because we're simply creating a function and passing the object in as an argument, we can use it with our class declaration likeso:
export default (UIFramework) => class MyView extends UIFramework.Type.View {
getModels() {
// ...
UIFramework.Models.getModelsForView( this._models );
// ...
}
}
The importation is a bit more complicated and automagical in my case given that it's an entire framework, but essentially this is what is happening:
// ...
getView( viewName ){
//...
const ViewFactory = require(viewFileLoc);
const View = ViewFactory(this);
return new View();
}
// ...
I hope this helps!
Node.js has included experimental support for ES6 support. Read more about here: https://nodejs.org/docs/latest-v13.x/api/esm.html#esm_enabling.
TLDR;
Node.js >= v13
It's very simple in Node.js 13 and above. You need to either:
- Save the file with
.mjsextension, or - Add
{ "type": "module" }in the nearestpackage.json.
You only need to do one of the above to be able to use ECMAScript modules.
Node.js <= v12
If you are using Node.js version 9.6 - 12, save the file with ES6 modules with .mjs extension and run it like:
node --experimental-modules my-app.mjs
You can also use npm package called esm which allows you to use ES6 modules in Node.js. It needs no configuration. With esm you will be able to use export/import in your JavaScript files.
Run the following command on your terminal
yarn add esm
or
npm install esm
After that, you need to require this package when starting your server with node. For example if your node server runs index.js file, you would use the command
node -r esm index.js
You can also add it in your package.json file like this
{
"name": "My-app",
"version": "1.0.0",
"description": "Some Hack",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node -r esm index.js"
},
}
Then run this command from the terminal to start your node server
npm start
Check this link for more details.
The first thing to do is to put type="module" as an attribute of your <script> tag
Full example:
<script type='module' src='module-a.mjs' />
<script type="module">
import * as moduleA from 'module-a.mjs'
</script>
You may want to add a .mjs extension to explicitly tell that this file is a js module and avoid syntax errors in your IDE.
Currently import / export syntax is supported by 97+% of all users browser (caniuse.com).
Documentation:
- import
- export
- Very good article on how to use module in browsers
The issue, as you said is that import is currently only being supported globally via Node. If you want to quickly import code on the client side, and jQuery is an option, then you can use:
$.getScript( "ajax/test.js" )
.done(function( script, textStatus ) {
console.log( textStatus );
})
.fail(function( jqxhr, settings, exception ) {
$( "div.log" ).text( "Triggered ajaxError handler." );
});
This will load and execute the JavaScript code from the server. The callback done is called when the script has finished downloading, but not necessarily completed execution.
For more info, you can look at the official reference