index.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  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. if (options.lazy) {
  26. if (typeof options.filename === 'string') {
  27. const filename = options.filename
  28. .replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&') // eslint-disable-line no-useless-escape
  29. .replace(/\\\[[a-z]+\\\]/gi, '.+');
  30. options.filename = new RegExp(`^[/]{0,1}${filename}$`);
  31. }
  32. }
  33. // defining custom MIME type
  34. if (options.mimeTypes) {
  35. const typeMap = options.mimeTypes.typeMap || options.mimeTypes;
  36. const force = !!options.mimeTypes.force;
  37. mime.define(typeMap, force);
  38. }
  39. const context = createContext(compiler, options);
  40. // start watching
  41. if (!options.lazy) {
  42. context.watching = compiler.watch(options.watchOptions, (err) => {
  43. if (err) {
  44. context.log.error(err.stack || err);
  45. if (err.details) {
  46. context.log.error(err.details);
  47. }
  48. }
  49. });
  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. // eslint-disable-next-line no-param-reassign
  60. callback = callback || noop;
  61. if (context.watching) {
  62. context.watching.close(callback);
  63. } else {
  64. callback();
  65. }
  66. },
  67. context,
  68. fileSystem: context.fs,
  69. getFilenameFromUrl: getFilenameFromUrl.bind(
  70. this,
  71. context.options.publicPath,
  72. context.compiler
  73. ),
  74. invalidate(callback) {
  75. // eslint-disable-next-line no-param-reassign
  76. callback = callback || noop;
  77. if (context.watching) {
  78. ready(context, callback, {});
  79. context.watching.invalidate();
  80. } else {
  81. callback();
  82. }
  83. },
  84. waitUntilValid(callback) {
  85. // eslint-disable-next-line no-param-reassign
  86. callback = callback || noop;
  87. ready(context, callback, {});
  88. },
  89. });
  90. };