resolve_imports.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright 2021 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. /**
  5. * This script resolves node imports to relative paths that can be consumed by
  6. * rollup. If this script becomes unmaintainable, consider using
  7. * @rollup/plugin-node-resolve instead.
  8. */
  9. const path = require('path');
  10. const resolve = require('resolve');
  11. const fs = require('fs');
  12. const { ArgumentParser } = require('argparse');
  13. const acorn = require('acorn')
  14. const parser = new ArgumentParser();
  15. parser.add_argument('--basedir');
  16. parser.add_argument('files', { nargs: '+' })
  17. const args = parser.parse_args();
  18. const inputFiles = args.files;
  19. for (const inputFile of inputFiles) {
  20. const inputDir = path.dirname(inputFile);
  21. const data = fs.readFileSync(inputFile, {encoding: 'utf8'})
  22. const ast = acorn.parse(data, {sourceType: 'module'});
  23. const NODE_TYPES_TO_RESOLVE = [
  24. 'ImportDeclaration',
  25. 'ExportAllDeclaration',
  26. 'ExportNamedDeclaration',
  27. ];
  28. const resolveNodes =
  29. ast.body.filter(n => NODE_TYPES_TO_RESOLVE.includes(n.type));
  30. const replacements = [];
  31. for (let i of resolveNodes) {
  32. const source = i.source;
  33. if (!source) {
  34. continue;
  35. }
  36. let resolved =
  37. resolve.sync(source.value, {basedir: args.basedir || inputDir});
  38. resolved = path.relative(inputDir, resolved);
  39. if (!resolved.startsWith('.')) {
  40. resolved = './' + resolved;
  41. }
  42. replacements.push({
  43. start: source.start,
  44. end: source.end,
  45. original: source.raw,
  46. replacement: `'${resolved}'`,
  47. });
  48. }
  49. const output = [];
  50. let curr = 0;
  51. for (const r of replacements) {
  52. output.push(data.substring(curr, r.start));
  53. output.push(r.replacement);
  54. curr = r.end;
  55. }
  56. output.push(data.substring(curr, data.length));
  57. fs.writeFileSync(inputFile, output.join(''));
  58. }