|
| 1 | +/** Generator */ |
| 2 | +module.exports = (api, opts) => { |
| 3 | + api.extendPackage({ |
| 4 | + dependencies: { |
| 5 | + "cloudinary-build-url": "latest", |
| 6 | + }, |
| 7 | + }); |
| 8 | + |
| 9 | + const urlModes = opts.urlModes.reduce( |
| 10 | + (opt, mode) => ({ |
| 11 | + image: opt.image || mode === "buildImageUrl", |
| 12 | + video: opt.video || mode === "buildVideoUrl", |
| 13 | + }), |
| 14 | + { |
| 15 | + image: false, |
| 16 | + video: false, |
| 17 | + } |
| 18 | + ); |
| 19 | + |
| 20 | + api.render("./template", { |
| 21 | + cloudName: opts.cloudName, |
| 22 | + ...urlModes, |
| 23 | + features: opts.urlModes, |
| 24 | + }); |
| 25 | + |
| 26 | + api.onCreateComplete(() => { |
| 27 | + // // inject to main.js |
| 28 | + const fs = require("fs"); |
| 29 | + const mainPath = api.resolve(api.entryFile); |
| 30 | + |
| 31 | + // get content |
| 32 | + let contentMain = fs.readFileSync(mainPath, { encoding: "utf-8" }); |
| 33 | + |
| 34 | + const lines = contentMain.split(/\r?\n/g).reverse(); |
| 35 | + // inject import |
| 36 | + const lastImportIndex = lines.findIndex((line) => line.match(/^import/)); |
| 37 | + |
| 38 | + if (contentMain.includes("createApp(")) { |
| 39 | + //Vue 3x |
| 40 | + lines[ |
| 41 | + lastImportIndex |
| 42 | + ] += `\nimport useCloudinary from './plugins/cloudinary'`; |
| 43 | + |
| 44 | + const lastCreateAppIndex = lines.findIndex((line) => |
| 45 | + line.match(/^createApp\(/) |
| 46 | + ); |
| 47 | + |
| 48 | + if (lastCreateAppIndex !== -1) { |
| 49 | + const sublines = lines[lastCreateAppIndex].split("."); |
| 50 | + sublines[0] = `const app = ${sublines[0]};`; |
| 51 | + const newLines = sublines.map((line, index) => |
| 52 | + index ? `app.${line};` : line |
| 53 | + ); |
| 54 | + |
| 55 | + const createAppLines = newLines.join("\n"); |
| 56 | + |
| 57 | + lines[lastCreateAppIndex] = createAppLines; |
| 58 | + } |
| 59 | + |
| 60 | + contentMain = lines.reverse().join("\n"); |
| 61 | + contentMain += `\nuseCloudinary(app);`; |
| 62 | + } else { |
| 63 | + //Vue 2x |
| 64 | + lines[lastImportIndex] += `\nimport './plugins/cloudinary'`; |
| 65 | + contentMain = lines.reverse().join("\n"); |
| 66 | + } |
| 67 | + |
| 68 | + // modify app |
| 69 | + fs.writeFileSync(mainPath, contentMain, { encoding: "utf-8" }); |
| 70 | + |
| 71 | + api.exitLog("🖼️ Learn more how to use url builder: https://cloudinary-build-url.netlify.com"); |
| 72 | + api.exitLog("💻 Github: https://github.com/mayashavin/cloudinary-api"); |
| 73 | + api.exitLog( |
| 74 | + "❤️ Have fun optimizing your images and videos with Cloudinary ❤️" |
| 75 | + ); |
| 76 | + }); |
| 77 | +}; |
0 commit comments