Friday, August 12, 2016

How to use custom source template to construct specific module in webpack

Leave a Comment

I know a bit inner functionality inside Webpack. Something about dependencies, template, and module building. However, there is little comment inside its source and no full document site for now. So, i can't chain them all to deal with my problem.

With my current requirement, i need to render specific module with custom source template.

For example, i have a module call main.js. In build time, it need to be dynamically generated with target dependencies like(for being not sure which modules would be dependencies):

// main.js var a = require('./a') var b = require('./b') var c = require('./c') var d = require('./d') ... 

In fact, if i only need to dynamically require them all, i can just construct an entry point dynamically.

// webpack.config.js {     entry: {         main: [             './a',             './b',             './c',             ...         ]     }, } 

and it(webpack) will generate a module may like this:

__webpack_require__(1); __webpack_require__(2); __webpack_require__(3);  return __webpack_require__(4); 

But i need to do something more:

var a = __webpack_require__(1); var b = __webpack_require__(2); var c = __webpack_require__(3); var d = __webpack_require__(4); ...  // do something with a,b,c,d... ...  return somthing or nothing; 

As you guys who know about webpack, it's very very complicated and hard to understand and track its plugin(event) hierarchy.

Need some expertise! :)

1 Answers

Answers 1

Often in webpack you're only requiring one file, and maybe different libs that the files depend on. If you require main, then webpack is going to resolve the dependencies based on the CommonJS syntax which you can read about here. Does removing the extra requirements in your webpack.config.js file solve this? e.g. having only the following as the config:

// webpack.config.js {   entry: [ "./main" ],   ... } 

It sounds like you don't really understand how webpack works-- the idea of it is to emulate how Node's CommonJS syntax allows your javascript to be modular and placed in separate files, while also being performant and not requiring tons of AJAX requests by your browser. If you want to read more about Webpack's config file, check out this page.


As a side note, returning at the end of the module does absolutely nothing. If you want to export, you can use module.exports, but having a line like return true or something at the end of your main.js file doesn't get caught anywhere meaningful.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment