fasfrtewqt2354r2edrq
fasfrtewqt2354r2edrq

Reputation: 166

Does JS import always requires export?

I spent a little more time in Python and there, importing from another file just takes a from file import functionName Is export required in Javascript when importing? I would like to split my single file into several different ones as it becomes more and more difficult to read. There should be only one function in each of the additional files. When I tried to import these extra files just by import {functionName} from './modules/filename.js' then I was getting Uncaught SyntaxError: The requested module './modules/filename.js' does not provide an export named 'functionName', but when I added when I wrote export before the function like export function functionName() {}, everything works fine. Do I understand correctly that in JS, import always requires export?

Upvotes: 2

Views: 2226

Answers (3)

Lajos Arpad
Lajos Arpad

Reputation: 76424

An import requires an export somewhere, not necessarily in the same file. You have a module JS file which exports some resources and at the point you use the given module, you import the resources you need. So, if you attempt to import some resource, then that resource must be specified by an export command in a module file you use.

Upvotes: 1

Arcord
Arcord

Reputation: 1909

Your JS file is a module and you need to specify what will be exposed by this module:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export

You could create a library where you do not want to expose all internal methods but only some of them and you can achieve that with the export keyword.

Upvotes: 2

Geo Daz
Geo Daz

Reputation: 184

It depends on how you use javascript.
In Node JS : https://nodejs.org/api/modules.html
In SPA like React Angulat Vue / modern JS:

If you use the old JavaScript way, then you should probably use multiple <script/> import tags in your html

Upvotes: 2

Related Questions