browserify / watchify

watch mode for browserify builds
Other
1.79k stars 203 forks source link

Transforms & Watchify - co-exist how? #356

Closed ghost closed 6 years ago

ghost commented 6 years ago

Made simple transform to require-inline files. Basically this:

require(/*inline*/ "path/to/file.js");

paste file.js into line above instead of normal requiring.

But these files aren't watched by watchify. How can I make these files being watched too?

Here goes browserify transform I've made (includify):

const through = require('through2');
const fs = require('fs');
const path = require('path');

const regex = /require\([\s]*\/\*inline\*\/[\s]*"(.+)"\)/g;

function process(pathToFile, contents) {
  while ( (occurence = regex.exec(contents)) ) {
    contents = processOne(pathToFile, contents, occurence);
  }

  return contents;
}

function processOne(pathToFile, contents, occurence) {
  const dir = path.dirname(pathToFile);

  const includePath = occurence[1] + ".js";

  const range = [occurence.index, occurence.index+occurence[0].length-1];

  const pathToInnerFile = dir + "/" + includePath;
  var innerContents = fs.readFileSync(pathToInnerFile, 'utf8');

  innerContents = process(pathToInnerFile, innerContents);

  var output = "";

  output += contents.substring(0, range[0]);

  output += innerContents;

  output += contents.substring(range[1]+1);

  return output;
}

module.exports = function(pathToFile) {
  return through(
    function(buf, enc, next) {
      var result = process(pathToFile, buf.toString('utf8'));

      this.push(result);
      next();
    }
  );
};
goto-bus-stop commented 6 years ago

You can emit a file event on the transform stream to inform watchify about any included files. The argument to the emit() function should be the absolute path to the file.

this.push(result);
var self = this;
includedFiles.forEach(function (file) {
  self.emit('file', file);
})
next();

e; we should update the readme to mention that

ghost commented 6 years ago

@goto-bus-stop LOVE YOU. Big thanks.

ghost commented 6 years ago

@goto-bus-stop what do you think?

https://github.com/browserify/watchify/pull/357/files