Create a UX bundle
Tip
Before reading this, you may want to have a look at Best Practices for Reusable Bundles.
Here are a few tricks to make your bundle install as a UX bundle.
composer.json file
Your composer.json file must have the symfony-ux keyword:
1 2 3
{
"keywords": ["symfony-ux"]
}
Assets location
Your assets must be located in one of the following directories, with a
package.json file so Flex can handle it during install/update:
/assets(recommended)/Resources/assets/src/Resources/assets
package.json file
Your package.json file must contain a symfony config with controllers defined,
and also add required packages to the peerDependencies and importmap (the list
of packages in importmap should be the same as the ones in peerDependencies):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
{
"name": "@acme/feature",
"version": "1.0.0",
"symfony": {
"controllers": {
"slug": {
"main": "dist/controller.js",
"fetch": "eager",
"enabled": true,
"autoimport": {
"@acme/feature/dist/bootstrap4-theme.css": false,
"@acme/feature/dist/bootstrap5-theme.css": true
}
}
},
"importmap": {
"@hotwired/stimulus": "^3.0.0",
"slugify": "^1.6.5"
}
},
"peerDependencies": {
"@hotwired/stimulus": "^3.0.0",
"slugify": "^1.6.5"
}
}
In this case, the file located at [assets directory]/dist/controller.js will be exposed.
Tip
You can either write raw JS in this dist/controller.js file, or you can
e.g. write your controller with TypeScript and transpile it to JavaScript.
Here is an example of how to do so:
Add the following to your
package.jsonfile:1 2 3 4 5 6 7 8 9 10 11 12 13 14
{ "scripts": { "build": "babel src --extensions .ts -d dist" }, "devDependencies": { "@babel/cli": "^7.20.7", "@babel/core": "^7.20.12", "@babel/plugin-proposal-class-properties": "^7.18.6", "@babel/preset-env": "^7.20.2", "@babel/preset-typescript": "^7.18.6", "@hotwired/stimulus": "^3.2.1", "typescript": "^4.9.5" } }Add the following to your
babel.config.jsfile (should be located next to yourpackage.jsonfile):1 2 3 4 5 6 7 8 9 10 11 12
module.exports = { presets: [ ['@babel/preset-env', { "loose": true, "modules": false }], ['@babel/preset-typescript', { allowDeclareFields: true }] ], assumptions: { superIsCallableConstructor: false, }, };- Run
npm installto install the new dependencies. - Write your Stimulus controller with TypeScript in
src/controller.ts. - Run
npm run buildto transpile your TypeScript controller into JavaScript.
To use your controller in a template (e.g. one defined in your bundle) you can use it like this:
1 2 3 4 5 6 7 8 9 10
<div
{{ stimulus_controller('acme/feature/slug', { modal: 'my-value' }) }}
{#
will render:
data-controller="acme--feature--slug"
data-acme--feature--slug-modal-value="my-value"
#}
>
...
</div>
Don't forget to add symfony/stimulus-bundle:^2.9 as a composer dependency to use
Twig stimulus_* functions.
Tip
Controller Naming: In this example, the name of the PHP package is acme/feature and the name
of the controller in package.json is slug. So, the full controller name for Stimulus will be
acme--feature--slug, though with the stimulus_controller() function, you can use acme/feature/slug.
Each controller has a number of options in the package.json file:
enabled:- Whether the controller should be enabled by default.
main:- Path to the controller file.
fetch:-
How controller & dependencies are included when the page loads.
Use
eager(default) to include controller & dependencies in the JavaScript that's downloaded when the page is loaded. Uselazyto make controller & dependencies isolated into a separate file and only downloaded asynchronously if (and when) the data-controller HTML appears on the page. autoimport:- List of files to be imported with the controller. Useful e.g. when there are several CSS styles depending on the frontend framework used (like Bootstrap 4 or 5, Tailwind CSS...). The value must be an object with files as keys, and a boolean as value for each file to set whether the file should be imported.
Specifics for Asset Mapper
To make your bundle's assets work with AssetMapper, you must add the importmap
config like above in your package.json file, and prepend some configuration
to the container:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
namespace Acme\FeatureBundle;
use Symfony\Component\AssetMapper\AssetMapperInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symfony\Component\HttpKernel\Bundle\AbstractBundle;
class AcmeFeatureBundle extends AbstractBundle
{
public function prependExtension(ContainerConfigurator $container, ContainerBuilder $builder): void
{
if (!$this->isAssetMapperAvailable($builder)) {
return;
}
$builder->prependExtensionConfig('framework', [
'asset_mapper' => [
'paths' => [
__DIR__ . '/../assets/dist' => '@acme/feature-bundle',
],
],
]);
}
private function isAssetMapperAvailable(ContainerBuilder $builder): bool
{
if (!interface_exists(AssetMapperInterface::class)) {
return false;
}
// check that FrameworkBundle 6.3 or higher is installed
$bundlesMetadata = $builder->getParameter('kernel.bundles_metadata');
if (!isset($bundlesMetadata['FrameworkBundle'])) {
return false;
}
$frameworkPath = $bundlesMetadata['FrameworkBundle']['path'];
// AssetMapper has its own bundle in recent Symfony versions
return isset($bundlesMetadata['AssetMapperBundle'])
|| is_file($frameworkPath . '/Resources/config/asset_mapper.php');
}
}
When an application installs your package, Symfony Flex runs the
importmap:require command to add each importmap entry to the
importmap.php file of the application. When the application removes your
package, Flex runs the importmap:remove command for these entries, unless
another installed package also declares them.
Instead of a version constraint, an entry can point to a file of your package.
Use the path: prefix and the %PACKAGE% placeholder, which Flex replaces
with the assets directory of your package. If the file is an
entrypoint, use the entrypoint: prefix instead:
1 2 3 4 5 6 7 8
{
"symfony": {
"importmap": {
"@hotwired/stimulus": "^3.0.0",
"@acme/feature/helpers": "path:%PACKAGE%/dist/helpers.js"
}
}
}
Exposing an Entrypoint
An entrypoint is a JavaScript file that must be loaded whenever a specific
part of the application is rendered. It usually initializes the frontend
behavior of that part. In a standard Symfony application, this role is played
by the app entrypoint, loaded via Webpack Encore or AssetMapper.
Exposing an entrypoint is useful when your bundle provides its own sections or
layouts (e.g. an admin backend, a translation editor, a dashboard, etc.). To do
so, declare the entrypoint in the package.json file of your bundle. When
installing the bundle, Symfony Flex registers it in the application so it can
be built with Webpack Encore or loaded with AssetMapper.
Webpack Encore
Define the entrypoint under the symfony.entrypoints key of your
package.json file:
1 2 3 4 5 6 7 8
{
"name": "@acme/feature",
"symfony": {
"entrypoints": {
"@acme/feature/entrypoint": "../node_modules/@acme/feature/entrypoint.js"
}
}
}
The key is the name of the entry used in templates and the value is the path
of the JavaScript file. This path must be relative to the assets/ directory
of the application.
When installing the bundle, Flex copies this entrypoint into the
assets/controllers.json file of the application. Encore only reads the
entrypoints of that file when the Stimulus bridge is enabled, so make sure
that your webpack.config.js file contains
.enableStimulusBridge('./assets/controllers.json').
Then, load the entry in the templates of your bundle:
1 2 3 4 5 6 7 8
{# templates/layout.html.twig #}
{% block stylesheets %}
{{ encore_entry_link_tags('@acme/feature/entrypoint') }}
{% endblock %}
{% block javascripts %}
{{ encore_entry_script_tags('@acme/feature/entrypoint') }}
{% endblock %}
AssetMapper
Define the entrypoint under the symfony.importmap key of your
package.json file, using the entrypoint: prefix:
1 2 3 4 5 6 7 8
{
"name": "@acme/feature",
"symfony": {
"importmap": {
"@acme/feature/entrypoint": "entrypoint:%PACKAGE%/entrypoint.js"
}
}
}
2.7.0
Support for the entrypoint: prefix was introduced in Symfony Flex 2.7.0.
When installing the bundle, Flex adds the entrypoint to the importmap.php
file of the application:
1 2 3 4 5 6 7 8 9 10 11 12
// importmap.php
return [
'app' => [
'path' => './assets/app.js',
'entrypoint' => true,
],
// ...
'@acme/feature/entrypoint' => [
'path' => './vendor/acme/feature-bundle/assets/entrypoint.js',
'entrypoint' => true,
],
];
Then, load the entry in the templates of your bundle:
1 2 3 4
{# templates/layout.html.twig #}
{% block javascripts %}
{{ importmap('@acme/feature/entrypoint') }}
{% endblock %}