跳到内容

使用 Webpack Encore 复制和引用图像

编辑此页

需要引用静态文件 - 例如 img 标签的图像路径? 如果您将资源存储在公共文档根目录之外,这可能会很棘手。 幸运的是,根据您的情况,有一个解决方案!

从 Webpack 打包的 JavaScript 文件内部引用图像

要从 JavaScript 文件内部引用图像标签,require 该文件

1
2
3
4
5
6
7
// assets/app.js

// returns the final, public path to this file
// path is relative to this file - e.g. assets/images/logo.png
import logoPath from '../images/logo.png';

let html = `<img src="${logoPath}" alt="ACME logo">`;

当您 require (或 import) 图像文件时,Webpack 会将其复制到您的输出目录,并返回该文件的最终公共路径。

从模板中引用图像文件

要从 Webpack 处理的 JavaScript 文件外部(例如模板)引用图像文件,您可以使用 copyFiles() 方法将这些文件复制到最终输出目录中。 首先在 webpack.config.js 中启用它

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// webpack.config.js

  Encore
      // ...
      .setOutputPath('public/build/')

+     .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)$/
+     })

然后重启 Encore。 当您这样做时,它会为您提供一个可以运行的命令,以安装任何缺少的依赖项。 运行该命令并重启 Encore 后,就完成了!

这会将所有文件从 assets/images 复制到 public/build/images。 如果您启用了版本控制,则复制的文件将包含基于其内容的哈希值。

要在 Twig 中渲染,请使用 asset() 函数

1
2
3
4
5
{# assets/images/logo.png was copied to public/build/images/logo.png #}
<img src="{{ asset('build/images/logo.png') }}" alt="ACME logo">

{# assets/images/subdir/logo.png was copied to public/build/images/subdir/logo.png #}
<img src="{{ asset('build/images/subdir/logo.png') }}" alt="ACME logo">

确保您已启用 json_manifest_path 选项,该选项告诉 asset() 函数从 manifest.json 文件中读取最终路径。 如果您不确定要将哪个路径参数传递给 asset() 函数,请在 manifest.json 中找到该文件,并使用作为参数。

这项工作,包括代码示例,均根据 Creative Commons BY-SA 3.0 许可获得许可。
目录
    版本