robsch
robsch

Reputation: 9728

How to use Yii2 with require.js?

I have a normal, not a REST application. But I don't know if this is relevant. I'd like to use require.js as I have a couple of JS files. I know that AssetBundles can be used, however, my application is not started with a HTML-GET requeset, so AFAIK I cannot use them since assets will not be created.

Background info: my application behaves like a REST application. It provides one JS file that will load other JS files (with require.js; this JS files contain AJAX requests to get JSON data from the application). There are no HTML actions. It provides just JSON data.

Some of those files are libraries like jQuery. jQuery is already provided by Yii2 so I thought the browser could fetch this jquery.js file by require.js somehow. However, it is stored in a @web/assets/54509f77/ folder where 545097ff is dynamic. Same is with bootstrap.js or CSS files. So, how could I define it in require.js?

Can anyone provide an example how to set up a require.js scenario with the Yii2 assets? Or doesn't this make sense and I should provide my own jquery.js?

Feel free to downvote if this is all stupid. I have no experience with require.js...

Upvotes: 3

Views: 934

Answers (1)

Jørgen
Jørgen

Reputation: 3567

I've never used require.js, but I have had to turn off Assets when using grunt.

In my experience, if you're not taking advantage of the benefits of Assets (Bundles and dependencies) - you might as well turn it off and provide your own libraries.

$config = [
    // ...
    'components' => [
        // ...
        'assetManager' => [
            'bundles' => false,
        ],
    ],
];

The tricky bit is to get all the Yii JS files back in, and i would refer you to samdarks chapter on Grunt even if you're not using it. It might be helpful.

The following JS files must be included to use the Yii Widgets

"vendor/bower/jquery/dist/jquery.js",

"vendor/bower/bootstrap/dist/js/bootstrap.js",

"vendor/yiisoft/yii2/assets/yii.js",

"vendor/yiisoft/yii2/assets/yii.validation.js",

"vendor/yiisoft/yii2/assets/yii.activeForm.js"

Upvotes: 3

Related Questions