简体   繁体   中英

How do ES6 imports/exports work when creating objects/variables in a module?

Given I have a Config class in a file called Config.js and I have the following module in a file called myConfig.js :

import Config from './Config.js';

const myConfig = new Config();

export myConfig;

If I have multiple files that import { myConfig } from 'myConfig.js' , does it instantiate new Configs on each import statement?

ES6 modules are singleton. Each time you import the module you will get the same instance. However, you could have tested it quite easily by logging something in the Config constructor.. ;-)

First: remove the .js extension when loading modules.

Second: your config class should be exported using export default class Config {} if you intend to load it with import Config from 'modulename'

The value exported is a singleton and will not change or reinstanciate but still why have config as a class? It should be a const object like

export const Config = {stuff:1}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM