filemap.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. const path = require('path')
  2. const compiler = require('miniprogram-compiler')
  3. const compilerResCache = {}
  4. const escapeContent = content => {
  5. return content.replace(/\\/g, '\\\\').replace(/'/g, '\\\'').replace(/\r?\n/g, '\\n\' +\n \'');
  6. };
  7. const createFileMapPreprocessor = (logger, basePath) => {
  8. const log = logger.create('preprocessor.filemap')
  9. let compileString
  10. if (basePath) {
  11. if (compilerResCache[basePath]) {
  12. compileString = compilerResCache[basePath]
  13. } else {
  14. global.window = global.window || {}
  15. compileString = compiler.wxmlToJs(basePath)
  16. compilerResCache[basePath] = compileString
  17. }
  18. }
  19. return (content, file, done) => {
  20. log.debug('Processing "%s".', file.originalPath)
  21. if (basePath && path.extname(file.originalPath) === '.wxml') {
  22. const relativeWxmlPath = path.relative(basePath, file.originalPath).replace(/\\/ig, '/')
  23. done(`
  24. if (!window.$gwx) {
  25. var compileFunc = new Function('${escapeContent(compileString)}');
  26. window.$gwx = compileFunc();
  27. }
  28. window.__webview_engine_version__ = 0.02;
  29. window.__FILE_MAP__ = window.__FILE_MAP__ || {};
  30. window.__FILE_MAP__['${file.originalPath}'] = window.$gwx('${relativeWxmlPath}');
  31. `);
  32. } else {
  33. done(`
  34. window.__FILE_MAP__ = window.__FILE_MAP__ || {};
  35. window.__FILE_MAP__['${file.originalPath}'] = '${escapeContent(content)}';
  36. `);
  37. }
  38. }
  39. }
  40. createFileMapPreprocessor.$inject = ['logger', 'config.basePath']
  41. module.exports = createFileMapPreprocessor