如何在 Symfony 4 中处理资产

How to handle assets in Symfony 4

我正在使用 Symfony 4 构建应用程序,我想关注 best practices for web assets。我对 SCSS 和 JS 使用 Encore/Webpack,效果很好;生成的 JS+CSS 很好地存储在 /public/build 文件夹中。我被困在如何存储和使用图像、电影、声音等静态资产上。

图像应该存储在'public/images'文件夹中还是'assets/images'?

还有一些后续问题:

如果图像存储在 public/images 中,如果我用 asset('...') 调用污染了模板,我会得到任何好处吗?

如果图片存储在assets/images,那么:

此致,

Should images be stored in 'public/images' folder or in 'assets/images'?

public/ 中的所有内容都可以通过浏览器获得。在这里,只应放置生产就绪和构建的东西。 由于您的图像不需要任何处理(我假设),您可以(应该)确实将图像放在那里。

现在,假设您需要进行一些处理(例如丑陋的 JPEG 压缩),您可以将图像放入 assets/,进行一些处理,然后仅将处理后的图像放入 public/.

If the images are stored in public/images, will I get any benefit if I pollute the templates with asset('...') calls?

是的,asset() 与 Encore 或资产构建管理没有任何关系。它所做的唯一一件事就是修复您的网址。这意味着如果您将应用程序移动到服务器上的子目录 (example.com/app/),URL 将自动适应。在 Asset component 文档中阅读更多相关信息。

在 Symfony 4 中使用 asset() 方法引用图像的另一种好方法是在使用 Encore 构建资产时复制 public/build 中的图像。

在 Webpack Encore 中使用 copyFiles()

Webpack Encore 提供了将图像复制到 public 目录的功能,以允许 asset() 访问这些文件:copyFiles().

在你的webpack.config.js

Encore.
...
.copyFiles({
        from: './assets/images',
        to: 'images/[path][name].[ext]',
        pattern: /\.(png|jpg|jpeg)$/
    })

错误:Encore.copyFiles 不是可识别的 属性 或方法。

请确保您实际使用的是 symfony/webpack-encore-bundle 而不是 symfony/webpack-encore-pack 描述为 here

composer require symfony/webpack-encore-bundle
composer remove symfony/webpack-encore-pack
yarn install
yarn upgrade
yarn run watch

我的package.json

{
    "devDependencies": {
        "@symfony/webpack-encore": "^0.22.0",
        "bootstrap": "^4.1.3",
        "node-sass": "^4.10.0",
        "sass-loader": "^7.0.1",
        "url-loader": "^1.0.1",
        "webpack-notifier": "^1.6.0"
    },
    "license": "UNLICENSED",
    "private": true,
    "scripts": {
        "dev-server": "encore dev-server",
        "dev": "encore dev",
        "watch": "encore dev --watch",
        "build": "encore production --progress"
    }
}
  1. 之后编辑 webpack.config.js

    安可 .setOutputPath('../build/')

  2. 添加以下行。您还可以通过取消注释行

    来进行更多配置
    .enableVersioning()
    .copyFiles({
     from: './assets/images',
    
     // optional target path, relative to the output dir
     to: 'images/[path][name].[ext]',
    
     // if versioning is enabled, add the file hash too
     //to: 'images/[path][name].[hash:8].[ext]',
    
     // only copy files matching this pattern
     //pattern: /\.(png|jpg|jpeg)$/
    })
    
  3. 现在你可以使用图片了

来源:https://symfony.com/doc/current/frontend/encore/copy-files.html 详情:http://toihid.com/?p=332