2

I want to export function from lib.js file to main.js file. I have

// lib.js
export const sqrt = Math.sqrt;
export function square(x) {
   return x * x;
}
export function diag(x, y) {
   return sqrt(square(x) + square(y));
}

// main.js 



import { square, diag } from 'lib';
console.log(square(11)); // 121
console.log(diag(4, 3)); // 5

After I connected main.js file to index.html file, in console I can find:

Uncaught SyntaxError: Unexpected token export  lib.js:1

What am I doing wrong? Or how to use "export" and "import" properly?

2
  • check those links: link1 , link2 PD: Are you using ES6? Commented Jun 19, 2017 at 7:36
  • 3
    import and export are not fully supported in the browser. You usually need a bundler (like Webpack) in order to create a package that has everything in it for the browser. Commented Jun 19, 2017 at 7:40

3 Answers 3

1

The native import is still not supported in node v6 and some browsers.

Import

You can use Typescript for import statement support in browsers

Sign up to request clarification or add additional context in comments.

Comments

1

The problem is finally solved after weeks. I'd never before used node.js enviroment and I had an interview task where functions should look like this:

    exports.functionName = () => {
       // smth here
    };

And that is why I've tried to use import, cause I thought it was misspelling in description of the task. But the solution was to install node globally. Create .js file with that function above, and just run in like this in terminal:

cd TaskDirectory
node nameOfFile.js

For all those newbies, like me. You can all your console.log's inside terminal, so you don't have to stick your .js file to .html to debug and check log's in browser.

Comments

0

You may refer mozilla documentation -

1) export

2) import

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.