Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get the output of webpack, Node API, as a string?

Tags:

webpack

Is there maybe a property of stats or compiler that holds the compiled bundle?

var compiler = require('webpack')({
    entry: entry_point,
    resolve: {
        modulesDirectories: modules,
        extensions: ['', '.js']
    },
    stats: {
        colors: true,
        progress: true,
        hash: true
    }
}, function(err, stats) {
   // compiler
   // stats

});
like image 493
Bryan Grace Avatar asked Oct 07 '16 18:10

Bryan Grace


People also ask

What is output in webpack?

Configuring the output configuration options tells webpack how to write the compiled files to disk. Note that, while there can be multiple entry points, only one output configuration is specified.

What is libraryTarget in webpack?

This is according to their documentation: "libraryTarget: "umd" - This exposes your library under all the module definitions, allowing it to work with CommonJS, AMD and as global variable." Also, I built the exact same code with Webpack 3 and it produced a proper bundle.

Can I use webpack with node?

Webpack provides a Node. js API which can be used directly in Node. js runtime.

Where are webpack files?

Webpack will generate the files and put them in the /dist folder for you, but it doesn't keep track of which files are actually in use by your project. In general it's good practice to clean the /dist folder before each build, so that only used files will be generated.


1 Answers

It should be possible to configure the compiler to use a replacement, in-memory filesystem and retrieve the output once the compilation has completed.

Here is a sample compile() function that returns a promise that will resolve the contents of the output file:

const MemoryFs = require('memory-fs')
const webpack = require('webpack')

function compile () {
  const compiler = webpack({
    output: {
      filename: 'bundle.js',
      path: '/'
    }
  })

  compiler.outputFileSystem = new MemoryFs()

  return new Promise((resolve, reject) => {
    compiler.run((err, stats) => {
      if (err) return reject(err)

      if (stats.hasErrors() || stats.hasWarnings()) {
        return reject(new Error(stats.toString({
          errorDetails: true,
          warnings: true
        })))
      }

      const result = compiler.outputFileSystem.data['bundle.js'].toString()
      resolve({result, stats})
    })
  })
}
like image 121
Filip Dupanović Avatar answered Nov 05 '22 09:11

Filip Dupanović