ceving
ceving

Reputation: 23824

How to store an ES6 module in more than one file?

This declares an ES6 module:

<script type="module" src="animals.js"></script>

My problem is: this makes a 1-to-1 connection between a module and a source file.

I would like to split "animals.js" into "dogs.js" and "cats.js". Is this possible with ES6 modules?

I would like to define the module in this way:

<script type="module" name="animals" src="dogs.js" src="cat.js"></script>

Upvotes: 1

Views: 379

Answers (1)

Isaaс Weisberg
Isaaс Weisberg

Reputation: 2824

ES modules are constraint to a single exporting context which happens to correlate to a single automatically created exporting context per file. So you can’t. You can however introduce a new module and it will be its own file/script block.

Alternatively, you can use a bundler that will accept several input files and produce a single ES module output file. Webpack might be a great choice.

Alternatively, you can introduce a module that imports and exports the contents of the other modules, serving as a kind of a wrapper or facade if you will.

Also, keep in mind that 1-to-1 connection between a script file and an ES module is inherent to the whole design of the ES modules, as well as many other bundling and namespacing systems. This is legitimately a feature and the need to have more than one source file per module might designate a flawed architectural design in your software.

If you would like a Java-like module behavior, you should definitely check out Typescript namespaces. Although, you will eventually realize how many different type inference caveats and parallel module visibility issues are there and thus will stop using them altogether in favor of ES2015 modules, they might be useful for just getting used to the modern technology.

Upvotes: 2

Related Questions