yii2-jsloader-requirejs
, (*1)
An Yii2 extension that allows to register asset bundles as RequireJS modules., (*2)
Installation
*Requires PHP >= 7.1, (*3)
*Requires ischenko/yii2-jsloader >= 1.2, (*4)
The preferred way to install this extension is through composer., (*5)
Either run, (*6)
composer require ischenko/yii2-jsloader-requirejs
or add, (*7)
"ischenko/yii2-jsloader-requirejs": "*"
to the require
section of your composer.json., (*8)
Usage
Add the behavior and requirejs loader to the view configuration, (*9)
...
'components' => [
...
'view' => [
'as jsLoader' => [
'class' => 'ischenko\yii2\jsloader\Behavior',
'loader' => [
'class' => 'ischenko\yii2\jsloader\RequireJs',
]
]
]
...
]
...
Modules configuration accepts options described in RequireJS API docs.
It is also possible to set aliases for modules, for example:, (*10)
...
'components' => [
...
'view' => [
'as jsLoader' => [
'class' => 'ischenko\yii2\jsloader\Behavior',
'loader' => [
'config' => [
'shim' => [
'yii\web\JqueryAsset' => [
'exports' => 'jQuery'
],
'app\assets\jQueryFireflyAsset' => [
'deps' => ['yii\web\JqueryAsset']
]
],
'aliases' => [
'yii\web\JqueryAsset' => 'jq',
'app\assets\jQueryFireflyAsset' => 'jqff'
]
],
'class' => 'ischenko\yii2\jsloader\RequireJs',
]
]
]
...
]
...
Or you can set alias, exports, init options from asset bundle:, (*11)
class jQueryFireflyAsset extends AssetBundle
{
public $js
= [
'jquery.firefly.min.js'
];
public $jsOptions
= [
'requirejs' => [
'alias' => 'jqff',
//'init' => 'function(jQuery) { /* do some init here */ }'
//'exports' => 'some-exported'
]
];
public $depends
= [
'yii\web\JqueryAsset',
];
// public function registerAssetFiles($view)
// {
// parent::registerAssetFiles($view);
// $this->jsOptions['requirejs']['init'] =<<<EOS
//function(jQuery) {
// Or do some complex init...
//}
//EOS;
// }
}
This will produce following output:, (*12)
var require = {
"shim": {
"jq": {
"exports": "jQuery"
},
"jqff": {
"deps": ["jq"]
}
},
"paths": {
"jq": ["/assets/e7b76d86/jquery"],
"jqff": ["/assets/4127fff7/jquery.firefly.min"]
}
};
Please note that aliases works only within client-side code. On server-side you still need to operate with actual module names., (*13)