How do I execute these javascript module templates?

I learned how to structure modules using IIFE. Simple example:

export test_module = (function{
    var name = "henry";
    var age = 26;
    var height ="6 monthe";

    var getHeight = function()
    {
        return height;
    }

    return{
        getHeight : getHeight
    }
}());

      

In another file, I have

import {test_module} from './test_module'

      

I would like to learn how to import and export IIFE modules using ECMAScript 6 module export and import. I installed Babel with a transpiler. But when I export my module and try to import it into another file, I get the error:

 (function (exports, require, module, __filename, __dirname) { import {text_module} from './test_module'
                                                                 ^^^^^^
SyntaxError: Unexpected token import
    at createScript (vm.js:56:10)
    at Object.runInThisContext (vm.js:97:10)
    at Module._compile (module.js:542:28)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:393:7)
    at startup (bootstrap_node.js:150:9)

      

What is my problem? Is my syntax wrong?

+3


source to share


1 answer


You have a syntax error as Babel reports. Instead

export test_module =

      

you have to say

export const test_module =

      

ES6 modules make the legacy IIFE-style "modules" obsolete (pretty much) anyway. Just write

// my-module.js

export function getHeight() {
    var name = "henry";
    var age = 26;
    var height = "6 monthe";

    return height;
}

      

Or if you prefer



function getHeight() {
    var name = "henry";
    var age = 26;
    var height = "6 monthe";

    return height;
}

export { getHeight };

      

Then when you want to use it:

import { getHeight } from './my-module';

getHeight();

      

or

import * as myModule from './my-module';

myModule.getHeight();

      

As far as your talk about classes, I don't understand what this is about your question. If you don't like classes in ES6, don't use them. Classes have nothing to do with ES6 modules other than the obvious fact that, like any other value classes, you can export and import.

+3


source







All Articles