index.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. class FontsPlugin {
  2. static defaultOptions = {
  3. outputFile: 'assets.md',
  4. };
  5. // Any options should be passed in the constructor of your plugin,
  6. // (this is a public API of your plugin).
  7. constructor(options = {}) {
  8. // Applying user-specified options over the default options
  9. // and making merged options further available to the plugin methods.
  10. // You should probably validate all the options here as well.
  11. this.options = { ...FontsPlugin.defaultOptions, ...options };
  12. }
  13. run(compilation) {
  14. // todo handle old files
  15. // migration
  16. const version = this.options.fonts.version;
  17. let cssfile = '';
  18. for (const font of this.options.fonts.fonts) {
  19. cssfile += '@font-face {\n';
  20. cssfile += `\tfont-family: ${font.fontName};\n`;
  21. if (font['css']) {
  22. const css = font['css'];
  23. if (css['font-weight']) cssfile += `\tfont-weight: ${css['font-weight']};\n`;
  24. if (css['font-style']) cssfile += `\tfont-style: ${css['font-style']};\n`;
  25. if (css['font-display']) cssfile += `\tfont-display: ${css['font-display']};\n`;
  26. if (css['unicode-range']) cssfile += `\tunicode-range: ${css['unicode-range']};\n`;
  27. }
  28. const formats = Object.keys(font['formats']).map((format) => {
  29. const label_format = format === 'ttf' ? 'truetype' : format;
  30. const path = process.env.VUE_APP_NAME === 'aktivisda' ? '' : '/backtivisda/'
  31. return `url('${path}/static/fonts/${font['directory']}/${font['formats'][format]}') format('${label_format}')`; // Remove ./ in the front of font["directory"]
  32. });
  33. cssfile += `\tsrc: ${formats.join(', ')};\n`;
  34. cssfile += '}\n\n';
  35. }
  36. compilation.assets[this.options.outputFile] = {
  37. source: function () {
  38. return cssfile;
  39. },
  40. size: function () {
  41. return cssfile.length;
  42. },
  43. };
  44. }
  45. apply(compiler) {
  46. const pluginName = FontsPlugin.name;
  47. // Using webpack 4
  48. compiler.hooks.emit.tapPromise(pluginName, async (compilation) => this.run(compilation));
  49. }
  50. }
  51. module.exports = { FontsPlugin };