Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 139923

How to use ES6 module in another module without importing it in both modules?

$
0
0

I have the following code structure

index.html

...

<head>
    <script type="module" src="/cars.component.js"></script>
</head>

...

cars.js

const cars = [{...}];

export default cars;

cars.component.js

import cars from 'cars.js';
import Component from 'component.base.js';

class CarsComponent extends HTMLElement {
    constructor() {
        super();    

        console.log(cars); // logs [{...}]

        // construct Component
        new Component();
    }

    ...
}

component.base.js

I want to use the const cars defined in cars.js also in this module without using import cars ... inside this module.

class Component {
    constructor() {
        console.log(cars); // ReferenceError: cars is not defined
    }

    ...
}

export default Component;

I thought this would be possible because Component.constructor is called aftercars has been loaded.

If we use the old way like so

...

<head>
    <script src="/cars.js">
        // this would be inside cars.js
        const cars = [{...}];
    </script>
    <script src="/component.js">
        // this would be inside component.js
        class Component {
            constructor() {
                console.log(cars); // this works correctly and logs [{...}]
            }
        }

        new Component();
    </script>
</head>

...

How to do the same using modules?

Side note: the real live code is much more complex, ive tried to write it as clear as possible. I know that in the above code I can just use new Component(Cars); inside cars.js. However, that would be impossible with the actual code.

The actual code can be found here https://codepen.io/richardmauritz/project/editor/XGWVBJ#


Viewing all articles
Browse latest Browse all 139923

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>