This bundle allows you to compile TypeScript and use it with Symfony's AssetMapper Component (no Node.js required!).
- Automatically downloads the correct SWC binary
- Adds a
typescript:build
command to compile your TypeScript files - Automatically compiles your TypeScript files when you run
asset-map:compile
command
Install the bundle:
$ composer require sensiolabs/typescript-bundle
Start by setting the sensiolabs_typescript.source_dir
option to the list of locations where your TypeScript files are located.
For instance, if your TypeScript code lives in assets/typescript/
directory, with an assets/typescript/app.ts
entrypoint file, set the option like this:
# config/packages/asset_mapper.yaml
sensiolabs_typescript:
source_dir: ['%kernel.project_dir%/assets/typescript']
Then load your TypeScript files in your templates:
{# templates/base.html.twig #}
{% block javascripts %}
<script type="text/javascript" src="{{ asset('typescript/app.ts') }}"></script>
{% endblock %}
Finally run this command:
# to compile only the TypeScript files
$ php bin/console typescript:build --watch
# to compile ALL your assets
$ php bin/console asset-map:compile
And that's it!
If using the Symfony CLI, you can add the build command as a worker to be started whenever you run symfony server:start
:
# .symfony.local.yaml
workers:
# ...
typescript:
cmd: ['symfony', 'console', 'typescript:build', '--watch']
Tip
If running symfony server:start
as a daemon, you can run symfony server:log
to tail the output of the worker.
The first time you run one of the TypeScript commands, the bundle will download the correct SWC binary for your system into the var/
directory.
When you run typescript:build
, that binary is used to compile TypeScript files into a var/typescript/
directory. Finally, when the contents of assets/typescript/app.ts
is requested, the bundle swaps the contents of that file with the contents of the var/typescript/
directory.
To see the full config from this bundle, run:
$ php bin/console config:dump sensiolabs_typescript
The main option is source_dir
, which defaults to [%kernel.project_dir%/assets]
. This is an array of the directories that will be compiled.
This bundle already installed for you the right SWC binary. However, if you already have a SWC binary installed on your machine you can instruct the bundle to use that binary with the binary
option:
# config/packages/asset_mapper.yaml
sensiolabs_typescript:
binary: 'node_modules/.bin/swc'
You can configure the SWC compiler by setting the swc_config_file
option to the the path to your .swcrc file:
# config/packages/asset_mapper.yaml
sensiolabs_typescript:
swc_config_file: '%kernel.project_dir%/.swcrc'