Aakash
Aakash

Reputation: 23717

How to access a module in source-files inside a custom webpack plugin?

A very simple project:

Files:

// ./src/foo.js
export default {
  foo: 'foo'
}

// ./src/index.js
import foo from './foo'
console.log(foo);

// webpack.config.js
const path = require('path');
var HelloWorldPlugin = require('./hello-world-plugin');

module.exports = {
  entry: './src/index.js',
  plugins: [
    new HelloWorldPlugin({ options: true })
  ]
};

// HelloWorldPlugin.js
class HelloWorldPlugin {
  apply(compiler) {
    compiler.hooks.afterEmit.tapAsync("HelloWorldPlugin", (compilation, next) => {
      console.log(arguments);
      // let foo = the module as imported from ./src/foo.js i.e. {foo: 'foo'}
      next();
    });
  }
}

module.exports = HelloWorldPlugin;

Question is:

Is it possible to access {foo:'foo'} from the foo-module inside HelloWorldPlugin?

Upvotes: 2

Views: 2042

Answers (1)

d7my
d7my

Reputation: 197

If you're trying to get the source code in your plugin, you can get it from compilation.assets[fileName].source(), and you can do that:

class HelloWorldPlugin {
  apply(compiler) {
    compiler.hooks.afterEmit.tapAsync("HelloWorldPlugin", (compilation, next) => {
      console.log(arguments);
      compilation.hooks.afterOptimizeAssets.tap({ name: 'name' }, (modules) => {
        for (let fileName in modules) {
          const source = compilation.assets[fileName].source();
          console.log(source); // source of files
        }
      })
      next();
    });
  }
}

by hooking into one of compilation hooks you can access all your modules and get filenames and their content

Upvotes: 3

Related Questions