generate.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. 'use strict';
  2. var css = require('css');
  3. var acorn = require('acorn');
  4. var SourceMapGenerator = require('source-map').SourceMapGenerator;
  5. function generateJs(sourcePath, fileContent) {
  6. var generator = new SourceMapGenerator({ file: sourcePath });
  7. var tokenizer = acorn.tokenizer(fileContent, { allowHashBang: true, locations: true });
  8. while (true) {
  9. var token = tokenizer.getToken();
  10. if (token.type.label === 'eof') {
  11. break;
  12. }
  13. var mapping = {
  14. original: token.loc.start,
  15. generated: token.loc.start,
  16. source: sourcePath,
  17. };
  18. if (token.type.label === 'name') {
  19. mapping.name = token.value;
  20. }
  21. generator.addMapping(mapping);
  22. }
  23. generator.setSourceContent(sourcePath, fileContent);
  24. return generator.toJSON();
  25. }
  26. function generateCss(sourcePath, fileContent) {
  27. var generator = new SourceMapGenerator({ file: sourcePath });
  28. var ast = css.parse(fileContent, { silent: true });
  29. function registerTokens(ast) {
  30. if (ast.position) {
  31. generator.addMapping({
  32. original: ast.position.start,
  33. generated: ast.position.start,
  34. source: sourcePath,
  35. });
  36. }
  37. for (var key in ast) {
  38. if (key === 'position' || !ast[key]) {
  39. break;
  40. }
  41. if (Object.prototype.toString.call(ast[key]) === '[object Object]') {
  42. registerTokens(ast[key]);
  43. } else if (Array.isArray(ast[key])) {
  44. ast[key].forEach(registerTokens);
  45. }
  46. }
  47. }
  48. registerTokens(ast);
  49. generator.setSourceContent(sourcePath, fileContent);
  50. return generator.toJSON();
  51. }
  52. module.exports = {
  53. js: generateJs,
  54. css: generateCss,
  55. };