index.js 2.4 KB

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