Search code examples
javascriptnpmwebpackwebpack-2

Webpack reference error between multiple entry points


I have the following webpack.config.js

entry: {
    a:'./src/a.js',
    b:'./src/b.js'
 },
 output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].bundle.js'
 }

the content of a.js is:

const MSG = "Can you see me?";

the content of b.js is:

console.log(MSG);

My index is loading both bundled scripts :

  <script type="text/javascript" src="./dist/a.bundle.js"></script>  
  <script type="text/javascript" src="./dist/b.bundle.js"></script>  

Npm run build, babel-loader, and run task work just fine. However, the reference MSG is not define in the DOM :

 Uncaught ReferenceError: MSG is not defined

Even thou the script a.js does define it. Am I missing something here? Do I need extra configurations to access values between different entry points ?


Solution

  • As mention in comments I needed to export - import the values which are defined in their respective module scope

    a.js:

    const MSG = "HEY CAN YOU SEE ME?";
    module.exports = {
        MSG:MSG
    };
    

    b.js:

    var MSG = require('./a.js').MSG;
    console.log(MSG);