Leo*_*nho 7 static symfony serve
我想复制 Vue.js 生成的 dist 文件夹并在 symfony 路由上提供它,我尝试过:
路线.yaml
vue:
path: /{path}
controller: App\Controller\ApiController::vue
methods: [GET]
requirements:
path: .*
Run Code Online (Sandbox Code Playgroud)
ApiController.php
public function vue()
{
$vuepath = __DIR__.'/../../public/dist/index.html';
return new Response(file_get_contents($vuepath));
}
Run Code Online (Sandbox Code Playgroud)
它启动时index.html不会加载 javascript 文件。我该如何送达我的申请?
这是我为从任意文件夹提供 spa 文件夹而制作的简单控制器(不支持 url 重写 - 当您想在站点根目录之外的某个路径上提供 spa 服务时)。
此实现带来了 symfony 分析器工具栏的好处 - 帮助调试/分析 ajax/fetch 请求。
不过,我建议使用另一种生产方法 - 为 spa 应用程序创建单独的部署。
<?php
namespace App\Controller;
use Symfony\Component\Filesystem\Path;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mime\MimeTypesInterface;
use Symfony\Component\Routing\Annotation\Route;
#[Route(
path: '/',
)]
class SpaController
{
public function __construct(
private readonly MimeTypesInterface $mimeTypes,
private readonly string $documentRootPath,
private readonly string $indexFile,
)
{
}
#[Route(
path: '/{urlPath}',
requirements: [
'urlPath' => '.*',
],
utf8: true,
)]
public function spaIndex(string $urlPath): Response
{
if ('' === $urlPath) {
$urlPath = $this->indexFile;
}
if ($this->indexFile !== $urlPath) {
$filePath = Path::canonicalize($this->documentRootPath . $urlPath);
if (
Path::isBasePath($this->documentRootPath, $filePath)
&& is_file($filePath)
) {
$fileResponse = new BinaryFileResponse($filePath);
$ext = pathinfo($filePath, PATHINFO_EXTENSION);
// symfony guessMimeType returns the wrong mime [`text/plain`] type for `.js`
$mimeType = $this->mimeTypes->getMimeTypes($ext)[0] ?? null;
if ($mimeType) {
$fileResponse->headers->set('Content-Type', $mimeType);
}
return $fileResponse;
}
// fallback to serving the indexFile bellow
}
// for symfony to inject the debug toolbar one must use response with text contents
$indexFileContents = file_get_contents($this->documentRootPath . $this->indexFile);
$response = new Response($indexFileContents);
$response->headers->set('Content-Type', 'text/html');
return $response;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1683 次 |
| 最近记录: |