index.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. return `url('${font['directory']}/${font['formats'][format]}') format('${label_format}')`; // Remove ./ in the front of font["directory"]
  31. });
  32. cssfile += `\tsrc: ${formats.join(', ')};\n`;
  33. cssfile += '}\n\n';
  34. }
  35. compilation.assets[this.options.outputFile] = {
  36. source: function () {
  37. return cssfile;
  38. },
  39. size: function () {
  40. return cssfile.length;
  41. },
  42. };
  43. }
  44. apply(compiler) {
  45. const pluginName = FontsPlugin.name;
  46. // Using webpack 4
  47. compiler.hooks.emit.tapPromise(pluginName, async (compilation) => this.run(compilation));
  48. }
  49. }
  50. module.exports = { FontsPlugin };