简体   繁体   中英

Revealing module pattern and webpack

I have sample module like this in module1.js file:

export const Module1 = (function() {

    'use strict';

    function init()
    {
        console.log('init');
    }

    return {
        init: init
    };

}());

in bootstrap.js file I have:

require('./module1');

and in app.js I use:

require('./boostrap');

$(function() {
    Module1.init();
});

but I'm getting:

Uncaught ReferenceError: Module1 is not defined

The same is when I try to launch just:

Module1.init();

in bootstrap.js

Just in case - I'm not JavaScript guy, so please explain me step by step what is wrong here if fancy solution is needed. I use Laravel mix under the hood for webpack, I don't use any custom configuration for webpack.

I was trying different scenarios and it seems solution was doing it like this:

const Module1 = (function() {

    'use strict';

    function init()
    {
        console.log('init');
    }

    return {
        init: init
    };

}());

export default Module1;

And then in bootstrap.js including it like this:

import Module1 from './module1';

and in bootstrap.js I can run:

Module1.init();

However it doesn't make Module1.init() will work in app.js so I finnaly I removed this import from boostrap.js and now my app.js looks like this:

require('./boostrap');
import Module1 from './module1';

$(function() {
    Module1.init();
});

require in Javascript does not work like some other languages do. It does not import the code, but the module.

Let's take the 3 modules you have : Module1, Bootstrap, and App.

Bootstrap requires Module1, which works since you exported the module in the file module1.js :

export const Module1 = [...]

However, the file bootstrap.js is only exporting the module Bootstrap. It does not exports Module1.

You have to import Module1 in app.js in order to use it.

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