index.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. 'use strict';
  2. const mime = require('mime');
  3. const createContext = require('./lib/context');
  4. const middleware = require('./lib/middleware');
  5. const reporter = require('./lib/reporter');
  6. const { setFs, toDisk } = require('./lib/fs');
  7. const { getFilenameFromUrl, noop, ready } = require('./lib/util');
  8. require('loud-rejection/register');
  9. const defaults = {
  10. logLevel: 'info',
  11. logTime: false,
  12. logger: null,
  13. mimeTypes: null,
  14. reporter,
  15. stats: {
  16. colors: true,
  17. context: process.cwd()
  18. },
  19. watchOptions: {
  20. aggregateTimeout: 200
  21. },
  22. writeToDisk: false
  23. };
  24. module.exports = function wdm(compiler, opts) {
  25. const options = Object.assign({}, defaults, opts);
  26. if (options.lazy) {
  27. if (typeof options.filename === 'string') {
  28. const filename = options.filename
  29. .replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&') // eslint-disable-line no-useless-escape
  30. .replace(/\\\[[a-z]+\\\]/ig, '.+');
  31. options.filename = new RegExp(`^[/]{0,1}${filename}$`);
  32. }
  33. }
  34. // defining custom MIME type
  35. if (options.mimeTypes) {
  36. mime.define(options.mimeTypes);
  37. }
  38. const context = createContext(compiler, options);
  39. // start watching
  40. if (!options.lazy) {
  41. const watching = compiler.watch(options.watchOptions, (err) => {
  42. if (err) {
  43. context.log.error(err.stack || err);
  44. if (err.details) {
  45. context.log.error(err.details);
  46. }
  47. }
  48. });
  49. context.watching = watching;
  50. } else {
  51. context.state = true;
  52. }
  53. if (options.writeToDisk) {
  54. toDisk(context);
  55. }
  56. setFs(context, compiler);
  57. return Object.assign(middleware(context), {
  58. close(callback) {
  59. callback = callback || noop;
  60. if (context.watching) {
  61. context.watching.close(callback);
  62. } else {
  63. callback();
  64. }
  65. },
  66. context,
  67. fileSystem: context.fs,
  68. getFilenameFromUrl: getFilenameFromUrl.bind(this, context.options.publicPath, context.compiler),
  69. invalidate(callback) {
  70. callback = callback || noop;
  71. if (context.watching) {
  72. ready(context, callback, {});
  73. context.watching.invalidate();
  74. } else {
  75. callback();
  76. }
  77. },
  78. waitUntilValid(callback) {
  79. callback = callback || noop;
  80. ready(context, callback, {});
  81. }
  82. });
  83. };