You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Symfony7.1集成Asset Mapper与Stimulus Bundle时出现映射错误

Symfony 7.1 + Asset Mapper + Stimulus Bundle 故障排查与解决

问题背景

基于Symfony 7.1 / PHP 8.3.8搭建新项目,使用Asset Mapper和Stimulus Bundle,但Stimulus无法正常运行,操作流程如下:

  • 执行初始化命令:symfony new my_project_directory --version="7.1.*" --webapp
  • 检查并创建(若不存在)/config/routes/attributes.yaml文件
  • 编写基础控制器用于渲染Twig模板
  • 在Twig模板中添加Stimulus控制器标记:<div data-controller="hello"></div>

报错信息

页面加载时控制台抛出错误:

Uncaught TypeError: The specifier “@hotwired/stimulus” was a bare specifier, but was not remapped to anything. Relative module specifiers must start with “./”, “../” or “/”.

相关文件内容

bootstrap.js

import { startStimulusApp } from '@symfony/stimulus-bundle';

const app = startStimulusApp();

hello_controller.js

import { Controller } from '@hotwired/stimulus';
export default class extends Controller {
    connect() {
        this.element.textContent = 'Hello Stimulus! Edit me in assets/controllers/hello_controller.js';
    }
}

importmap.php

<?php
return [
    'app' => [
        'path' => './assets/app.js',
        'entrypoint' => true,
    ],
    '@symfony/stimulus-bundle' => [
        'path' => './vendor/symfony/stimulus-bundle/assets/dist/loader.js',
    ],
];

已尝试操作

  • 执行php bin/console importmap:require @symfony/stimulus-bundle或php bin/console importmap:require @hotwired/stimulus,仅返回[OK] 0 new items () added to the importmap.php
  • 执行php bin/console cache:clear,问题未解决
  • 修改importmap.php中@symfony/stimulus-bundle的路径为@symfony/stimulus-bundle/loader.js,无效

解决建议

因服务器不支持Node/npm,需完全依赖Asset Mapper处理依赖,关键修复步骤如下:

  1. 手动添加@hotwired/stimulus到importmap.php
    由于importmap:require未自动添加成功,直接在配置文件中手动声明依赖:

    <?php
    return [
        'app' => [
            'path' => './assets/app.js',
            'entrypoint' => true,
        ],
        '@symfony/stimulus-bundle' => [
            'path' => './vendor/symfony/stimulus-bundle/assets/dist/loader.js',
        ],
        '@hotwired/stimulus' => [
            'url' => 'https://cdn.jsdelivr.net/npm/@hotwired/stimulus@3.2.2/dist/stimulus.js',
        ],
    ];
    

    可根据Stimulus稳定版本调整CDN链接的版本号。

  2. 验证Asset Mapper的控制器目录配置
    检查config/packages/asset_mapper.yaml,确保包含控制器目录的配置:

    asset_mapper:
        paths:
            - assets/controllers
    

    若缺失则手动添加,之后执行php bin/console asset-map:compile生成映射文件。

  3. 确认Twig模板正确引入资产入口
    确保模板中包含Asset Mapper的入口渲染标签:

    {{ importmap('app') }}
    

    该标签会自动渲染importmap配置和入口脚本,保证Stimulus依赖正确加载。

  4. 重新编译资产映射并清除缓存
    执行以下命令强制更新映射文件:

    php bin/console asset-map:compile
    php bin/console cache:clear
    
  5. 检查控制器文件规范
    确认控制器文件命名为hello_controller.js,位于assets/controllers目录下,且导出类正确继承Stimulus的Controller,无语法错误。


内容的提问来源于stack exchange,提问作者Teka B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 15:03:22