3

I have a modularised application based on NodeJS. The structure of the application looks like

  • server.js
  • controllers
    • controller1.js
    • controller2.js
  • dao
    • dao1.js
    • dao2.js
  • node_modules

Now I want to minify and concatenate the entire project into a single file. The challenge I am facing is every controller and dao files are using "require" (relative paths) to include the node modules
Is there any easy way to achieve this?

Edit

Tried webpack module
My webpack.config.js looks like

var webpack = require('webpack');
var path = require('path');
var fs = require('fs');

var nodeModules = {};
fs.readdirSync(path.resolve(__dirname, 'node_modules'))
.filter(x => ['.bin'].indexOf(x) === -1)
.forEach(mod => { nodeModules[mod] = `commonjs ${mod}`; });

module.exports = {
  name: 'server',
  target: 'node',
  entry: './server.js',
  output: {
    path: path.join(__dirname, 'build'),
    filename: 'bundle.js'
  },
  externals: nodeModules,
  module: {
    loader: [
      {
        test: /\.json$/, loader: 'json-loader'
      }
    ]
  }
}

It is giving this error:

ERROR in ./~/npm/~/npm-registry-client/test/unpublish-scoped.js Module not found: Error: Cannot resolve 'file' or 'directory' ./fixtures/@npm/np m-registry-client/cache.json in D:\OTTAFW\node_modules\npm\node_modules\npm-regi stry-client\test

Rushi Suthar
  • 61
  • 1
  • 4

2 Answers2

0

Did you take a look at webpack? https://webpack.js.org/concepts/

Bharat
  • 21
  • 6
0

You can use a task runner like gulp to stitch and minify. See here if you want to bluntly stitch and minify files. In order to manage dependency you have to define a dependency tree and write the logic so that multiple dependencies are not added in the final build.

server.js
controllers
|-- controller1.js
          require('lodash')
|-- controller2.js
          require('./controller1')
dao
|-- dao1.js
          require('lodash')
          require('../controllers/controller2')
|-- dao2.js
          require('../controllers/controller1')
node_modules

Hypothetically, if this is the case you have to careful of the fact that the files gets attached only once.

On the contrary, you can use rollup

Community
  • 1
  • 1
years_of_no_light
  • 938
  • 1
  • 10
  • 24