index.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. const fs = require('fs');
  2. const filenameTailwind = 'tailwind.config.js';
  3. function loadModule(src, filename) {
  4. var Module = module.constructor;
  5. var m = new Module();
  6. m._compile(src, filename);
  7. return m.exports;
  8. }
  9. function readPostcssConfig(api) {
  10. const filename = 'postcss.config.js';
  11. const file = api.generator.files[filename];
  12. if (file) {
  13. const filePath = api.resolve(filename);
  14. fs.writeFileSync(filePath, '');
  15. return loadModule(file, filename);
  16. }
  17. const config = api.generator.originalPkg.postcss;
  18. if (config) {
  19. const copy = { ...config };
  20. delete config.plugins;
  21. return copy;
  22. }
  23. return {};
  24. }
  25. function generateConfig(api, option) {
  26. const args = ['init'];
  27. if (option === 'full') {
  28. args.push('--full');
  29. }
  30. const { spawnSync } = require('child_process');
  31. const tailwind = api.resolve('./node_modules/.bin/tailwind');
  32. if (!fs.existsSync(tailwind)) throw new Error(`${tailwind} not found`);
  33. spawnSync(tailwind, args, {
  34. cwd: api.generator.context,
  35. shell: process.platform === 'win32',
  36. });
  37. }
  38. function injectContentConfig(api) {
  39. const configPath = api.resolve(filenameTailwind);
  40. const tailwindConfig = fs.readFileSync(configPath, 'utf-8');
  41. fs.writeFileSync(
  42. configPath,
  43. tailwindConfig.replace(
  44. 'content: []',
  45. "content: ['./public/**/*.html', './src/**/*.{vue,js,ts,jsx,tsx}']",
  46. ),
  47. );
  48. }
  49. module.exports = (api, options) => {
  50. const postcss = readPostcssConfig(api);
  51. const configs = {
  52. dependencies: {
  53. autoprefixer: '^10',
  54. postcss: '^8',
  55. tailwindcss: '^3',
  56. },
  57. postcss: {
  58. plugins: {
  59. tailwindcss: {},
  60. autoprefixer: {},
  61. },
  62. },
  63. };
  64. configs.postcss.plugins = { ...configs.postcss.plugins, ...postcss.plugins };
  65. api.extendPackage(configs);
  66. api.injectImports(api.entryFile, `import './assets/tailwind.css'`);
  67. api.render('./template');
  68. if (options.replaceConfig) {
  69. delete api.generator.files[filenameTailwind];
  70. const configPath = api.resolve(filenameTailwind);
  71. try {
  72. fs.unlinkSync(configPath);
  73. } catch (error) {
  74. throw new Error(error);
  75. }
  76. }
  77. if (options.initConfig && options.replaceConfig !== false) {
  78. api.onCreateComplete(() => {
  79. generateConfig(api, options.initConfig);
  80. injectContentConfig(api);
  81. });
  82. }
  83. };