2

I'm trying to get rid of the thousand files you get once you npm install various modules having their own dependencies.

Thus I was thinking of compiling only the libraries using webpack into one javascript file (and other required resources), then loading it to the Node.js project this way :

  • Entry point, that will be compiled to bundle by webpack.

    module.exports = {
        lodash : require('lodash'),
        colors : require('colors'),
        test : require('test'),
        abc : require('abc')
    } ;
    
  • Main

    var { lodash, colors, test, abc } = require('./lib/bundle') ;
    

The problem I got is that some modules require system (or uncompilable) modules, such as fs, and webpack tries to bundle them to. You just have to specify in the webpack.config.js file :

node: {
    fs : "empty",
    electron : "empty"
}

However, once packed into bundle, it seems that every require('fs') is replaced by Object.freeze({}) because of this setting, and then the modules fail using fs.


Would anyone have a solution for using packed modules in a Node.js project ?

P.S.: I tried using yarn with yarn autoclean --force to remove all unnecessary files, but it only removed 5% to 10% of the total.

Tot
  • 873
  • 2
  • 13
  • 30

1 Answers1

2

The problem using the current node config object and set fs: 'empty' is that it will provide an empty object for those modules. More info about Webpack Node here.

You can set the Webpack target property to 'node'

Compile for usage in a Node.js-like environment (uses Node.js require to load chunks and not touch any built in modules like fs or path)

module.exports = {
  target: 'node'
};

Read more about Webpack Targets

Also, to import a built-in module, use __non_webpack_require__

Generates a require function that is not parsed by webpack

Carloluis
  • 4,205
  • 1
  • 20
  • 25