1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Vite plugin for Craft CMS 3.x |
4
|
|
|
* |
5
|
|
|
* Allows the use of the Vite.js next generation frontend tooling with Craft CMS |
6
|
|
|
* |
7
|
|
|
* @link https://nystudio107.com |
|
|
|
|
8
|
|
|
* @copyright Copyright (c) 2021 nystudio107 |
|
|
|
|
9
|
|
|
*/ |
|
|
|
|
10
|
|
|
|
11
|
|
|
namespace nystudio107\pluginvite\services; |
12
|
|
|
|
13
|
|
|
use Craft; |
14
|
|
|
use craft\web\AssetBundle; |
15
|
|
|
|
16
|
|
|
/** |
|
|
|
|
17
|
|
|
* @author nystudio107 |
|
|
|
|
18
|
|
|
* @package Vite |
|
|
|
|
19
|
|
|
* @since 1.0.0 |
|
|
|
|
20
|
|
|
*/ |
|
|
|
|
21
|
|
|
class VitePluginService extends ViteService |
22
|
|
|
{ |
23
|
|
|
// Constants |
24
|
|
|
// ========================================================================= |
25
|
|
|
|
26
|
|
|
const MANIFEST_FILE_NAME = 'manifest.json'; |
27
|
|
|
|
28
|
|
|
// Public Properties |
29
|
|
|
// ========================================================================= |
30
|
|
|
|
31
|
|
|
/** |
|
|
|
|
32
|
|
|
* @var string AssetBundle class name to get the published URLs from |
33
|
|
|
*/ |
34
|
|
|
public $assetClass; |
35
|
|
|
|
36
|
|
|
/** |
|
|
|
|
37
|
|
|
* @var string The environment variable to look for in order to enable the devServer; the value doesn't matter, |
38
|
|
|
* it just needs to exist |
39
|
|
|
*/ |
40
|
|
|
public $pluginDevServerEnvVar = 'VITE_PLUGIN_DEVSERVER'; |
41
|
|
|
|
42
|
|
|
/** |
|
|
|
|
43
|
|
|
* @inheritDoc |
44
|
|
|
*/ |
|
|
|
|
45
|
|
|
public function init() |
46
|
|
|
{ |
47
|
|
|
parent::init(); |
48
|
|
|
// Do nothing for console requests |
49
|
|
|
$request = Craft::$app->getRequest(); |
50
|
|
|
if ($request->getIsConsoleRequest()) { |
51
|
|
|
return; |
52
|
|
|
} |
53
|
|
|
$this->invalidateCaches(); |
54
|
|
|
// See if the $pluginDevServerEnvVar env var exists, and if not, don't run off of the dev server |
55
|
|
|
$useDevServer = getenv($this->pluginDevServerEnvVar); |
56
|
|
|
if ($useDevServer === false) { |
57
|
|
|
$this->useDevServer = false; |
58
|
|
|
} |
59
|
|
|
// If we have no asset bundle class, or the dev server is running, don't swap in our `/cpresources/` paths |
60
|
|
|
if (!$this->assetClass || $this->devServerRunning()) { |
61
|
|
|
return; |
62
|
|
|
} |
63
|
|
|
// If we're in a plugin, make sure the caches are unique |
64
|
|
|
if ($this->assetClass) { |
65
|
|
|
$this->cacheKeySuffix = $this->assetClass; |
66
|
|
|
} |
67
|
|
|
// Map the $manifestPath and $serverPublic to the hashed `/cpresources/` path & URL for our AssetBundle |
68
|
|
|
$bundle = new $this->assetClass; |
69
|
|
|
$baseAssetsUrl = Craft::$app->assetManager->getPublishedUrl( |
70
|
|
|
$bundle->sourcePath, |
71
|
|
|
true |
|
|
|
|
72
|
|
|
); |
73
|
|
|
$this->manifestPath = $this->createUrl($bundle->sourcePath, self::MANIFEST_FILE_NAME); |
74
|
|
|
if ($baseAssetsUrl !== false) { |
75
|
|
|
$this->serverPublic = $baseAssetsUrl; |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|