common.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. 'use strict';
  2. const debug = require('debug')('ScriptExt');
  3. const separator = '/';
  4. const isScript = (tag) => tag.tagName === 'script';
  5. const isResourceLink = (tag) => tag.tagName === 'link' && tag.attributes && tag.attributes.as === 'script';
  6. const hasScriptName = tag => {
  7. if (isScript(tag)) {
  8. return tag.attributes && tag.attributes.src;
  9. } else if (isResourceLink(tag)) {
  10. return tag.attributes && tag.attributes.href;
  11. } else {
  12. return false;
  13. }
  14. };
  15. const getRawScriptName = tag => {
  16. if (isScript(tag)) {
  17. return (tag.attributes && tag.attributes.src) || '';
  18. } else if (isResourceLink(tag)) {
  19. return (tag.attributes && tag.attributes.href) || '';
  20. } else {
  21. return '';
  22. }
  23. };
  24. const getPublicPath = options => {
  25. const output = options.compilationOptions.output;
  26. if (output) {
  27. let publicPath = output.publicPath;
  28. if (publicPath) {
  29. return publicPath.endsWith(separator) ? publicPath : publicPath + separator;
  30. }
  31. }
  32. };
  33. const getScriptName = (options, tag) => {
  34. let scriptName = getRawScriptName(tag);
  35. const publicPath = getPublicPath(options);
  36. if (publicPath) {
  37. scriptName = scriptName.replace(publicPath, '');
  38. }
  39. if (options.htmlWebpackOptions.hash) {
  40. scriptName = scriptName.split('?', 1)[0];
  41. }
  42. return scriptName;
  43. };
  44. const matches = (toMatch, matchers) => {
  45. return matchers.some((matcher) => {
  46. if (matcher instanceof RegExp) {
  47. return matcher.test(toMatch);
  48. } else {
  49. return toMatch.includes(matcher);
  50. }
  51. });
  52. };
  53. module.exports = {
  54. debug,
  55. getPublicPath,
  56. getRawScriptName,
  57. getScriptName,
  58. hasScriptName,
  59. isResourceLink,
  60. isScript,
  61. matches
  62. };