You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3 年之前
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. 'use strict';
  2. const { extname } = require('path');
  3. function namedAssetImportPlugin({ types: t }) {
  4. const visited = new WeakSet();
  5. return {
  6. visitor: {
  7. ImportDeclaration(
  8. path,
  9. {
  10. opts: { loaderMap },
  11. }
  12. ) {
  13. const sourcePath = path.node.source.value;
  14. const ext = extname(sourcePath).substr(1);
  15. if (visited.has(path.node) || sourcePath.indexOf('!') !== -1) {
  16. return;
  17. }
  18. if (loaderMap[ext]) {
  19. path.replaceWithMultiple(
  20. path.node.specifiers.map(specifier => {
  21. if (t.isImportDefaultSpecifier(specifier)) {
  22. const newDefaultImport = t.importDeclaration(
  23. [
  24. t.importDefaultSpecifier(
  25. t.identifier(specifier.local.name)
  26. ),
  27. ],
  28. t.stringLiteral(sourcePath)
  29. );
  30. visited.add(newDefaultImport);
  31. return newDefaultImport;
  32. }
  33. const newImport = t.importDeclaration(
  34. [
  35. t.importSpecifier(
  36. t.identifier(specifier.local.name),
  37. t.identifier(specifier.imported.name)
  38. ),
  39. ],
  40. t.stringLiteral(
  41. loaderMap[ext][specifier.imported.name]
  42. ? loaderMap[ext][specifier.imported.name].replace(
  43. /\[path\]/,
  44. sourcePath
  45. )
  46. : sourcePath
  47. )
  48. );
  49. visited.add(newImport);
  50. return newImport;
  51. })
  52. );
  53. }
  54. },
  55. },
  56. };
  57. }
  58. module.exports = namedAssetImportPlugin;