Home > Mobile >  Webpack - Bundling multiple js files with respect to resusable methods and variable from one another
Webpack - Bundling multiple js files with respect to resusable methods and variable from one another

Time:05-13

I am trying to bundle around 10 javascript files of my application which are loaded as scripts in the index.html file. They are properly sequenced as per their dependencies with one another.

<script src="/js/main.js"></script>
<script src="/js/user.js"></script>
<script src="/js/contact.js"></script>
...

The code inside each file looks like this:

// main.js
const _main = {};
_main.MethodOne = function(){
  ...
}

// user.js
const _user = {};
_user.MethodTwo = function(){
  // Can access the method from main.js file
  _main.MethodOne();
}

// contact.js
const _contact = {};
_contact.MethodThree = function(){
  // Can access the methods from main.js & user.js file
  _user.MethodTwo();
  _main.MethodOne();
}

Now, when bundling them through webpack, the constant variables _main, _contact & _user gets renamed to some random letters. However, the names used to invoke those methods from other files remain the same in each case i.e. _user.MethodTwo(), _main.MethodOne() doesn't change.

This is my webpack.config.js

entry: {
    vendors: [
        './public/js/colorpicker.js',
        ...
    ],
    app: [
        './public/js/main.js',
        './public/js/user.js',
        './public/js/contact.js'
    ]
},
mode: 'production',
output: {
    filename: 'js/[name].[contenthash].bundle.js',
    path: path.resolve(__dirname, 'dist'),
    clean: true,
    publicPath: 'auto',
    assetModuleFilename: 'img/[hash][ext][query]'
},

I read the webpack documentation however didn't get any clue about this problem.

CodePudding user response:

Your best bet is to move to the module approach by using import and export.

so instead of defining global variables like you do, each file would export the corresponding variable. If a file needs a variable from another file, it simply has to import it.

// main.js
export const _main = {};
_main.MethodOne = function(){
  ...
}

// user.js
import {_main} from "./main.js";
export const _user = {};
_user.MethodTwo = function(){
  // Can access the method from main.js file
  _main.MethodOne();
}

// contact.js
import {_main} from "./main.js";
import {_user} from "./user.js";
const _contact = {};
_contact.MethodThree = function(){
  // Can access the methods from main.js & user.js file
  _user.MethodTwo();
  _main.MethodOne();
}

Read more about import/export here

  • Related