generate.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. 'use strict';
  2. var acorn = require('acorn');
  3. var postcss = require('postcss');
  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, {
  8. allowHashBang: true,
  9. locations: true,
  10. });
  11. /* eslint no-constant-condition: 0 */
  12. while (true) {
  13. var token = tokenizer.getToken();
  14. if (token.type.label === 'eof') {
  15. break;
  16. }
  17. var mapping = {
  18. original: token.loc.start,
  19. generated: token.loc.start,
  20. source: sourcePath,
  21. };
  22. if (token.type.label === 'name') {
  23. mapping.name = token.value;
  24. }
  25. generator.addMapping(mapping);
  26. }
  27. generator.setSourceContent(sourcePath, fileContent);
  28. return generator.toJSON();
  29. }
  30. var postcssSourceMapOptions = {
  31. inline: false,
  32. prev: false,
  33. sourcesContent: true,
  34. annotation: false,
  35. };
  36. function generateCss(sourcePath, fileContent) {
  37. var root = postcss.parse(fileContent, { from: sourcePath });
  38. var result = root.toResult({ to: sourcePath, map: postcssSourceMapOptions });
  39. return result.map.toJSON();
  40. }
  41. module.exports = {
  42. js: generateJs,
  43. css: generateCss,
  44. };