webpack-encore
webpack-encore copied to clipboard
Wrong order of babel plugins: enableBabelTypeScriptPreset / allowDeclareFields
When writing Stimulus controllers in TypeScript, given its incomplete typings, one needs to manually declare all targets, values etc:
export default class extends Controller {
declare nameTarget: HTMLInputElement;
declare indexValue: number;
static values = { index: Number };
static targets = ["name"];
…
For this to work, when using @babel/preset-typescript
, the allowDeclareFields
option needs to be added.
But then babel compilation fails with:
Syntax error: TypeScript 'declare' fields must first be transformed by @babel/plugin-transform-typescript.
node_modules/@symfony/stimulus-bridge/lazy-controller-loader.js!./assets/controllers/hello_controller.ts
If you have already enabled that plugin (or '@babel/preset-typescript'), make sure that it runs before any plugin related to additional class features:
- @babel/plugin-proposal-class-properties
- @babel/plugin-proposal-private-methods
- @babel/plugin-proposal-decorators
11 | */
12 | export default class extends Controller {
> 13 | declare nameTarget: HTMLInputElement;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Of course the real solution would be to add proper typings to stimulus itself, but that project was abandoned.
So meanwhile, can we fix the config building for this workaround to work? I would submit a PR but not sure what other consequences would changing the loading order have.
Thank you in advance
You can use a workaround to add the @babel/plugin-transform-typescript
as the first plugin until a fix is submitted:
Encore.
.configureBabel((config) => {
config.plugins.unshift(['@babel/plugin-transform-typescript', {
allowDeclareFields: true
}])
})