Import user-created modules in javascript

Asked

Viewed 107 times

0

I read in that reply here on the site I can import modules in javascript similar to what is done in python. However, I am not able to apply this in JS.

Follow an example. In python varies:

#arquivo mym.py
def my_sqr(a):
    return a**(1/2)

In another file:

#arquivo main.py
from mym import my_sqr

my_sqr(9)

Output:

3

Already in the javascripit:

//arquivo mym.js
export my_sqr = function(a){
    return a**(1/2)
}

Em main.js

import {my_sqr} from 'mym'

mym(9)

Error:

SyntaxError: Cannot use import statement outside a module

1 answer

2


I believe the problem lies in the configuration of the project. Node by default does not understand es6 and es5, this varies according to the V8 engine used in Node, the default syntax would be to use

module.exports

If you want to use es6 you must use a compiler, I recommend Babel.

npm install --save-dev @babel/core @babel/node

Then you can use

export default my_sqr

import my_sqr from 'mym'

Browser other questions tagged

You are not signed in. Login or sign up in order to post.