样式的图像不由文件加载器处理

时间:2019-07-04 07:39:44

标签: angular webpack migration angular8 webpack-loader

我目前正在将 AngularJs 1.7 迁移到 Angular 8.0 。因此,我使用了 webpack.config.js ,并扩展了一些规则来处理 Angular 相关内容。

那怎么了?

当我在 Scss 中引用属于 AngularJs 组件的图像时,如下所示:

import React, { useEffect, useState } from 'react';

const Table = () => {

 const [data, setData] = useState([]);

 useEffect(() => {

 setData([...data, getFakeApiData()]);

 }, [data]);


const renderTable = () => {

  return Table.data.map((user) => {

    const { name, email, address, company } = user;

    return (
      <tr key={name}>
          <td>{name}</td>
          <td>{email}</td>
          <td>{address.city}</td>
          <td>{company.name}</td>
      </tr>
    )
  })
 }
};

输出 Css 类似于:

.my-image-container {
  background: url('../../assets/images/my-fancy-image.png')
}

但是,应用于 Angular 组件的 Scss 不会发生这种情况。在这种情况下,路径将保持不变。 显然这是一个问题,因为我没有将所有资产复制到dist文件夹中,更糟糕的是,即使图像中发生了某些更改,纯文件名也将图像保留在浏览器缓存中。

我的问题

如何为 Angular 相关样式获得哈希图像文件名?

WebPack配置(仅适用于规则)

.my-image-container {
  background: url('89a8d90asd8as8d0a8sdfa8fsd.png') // MD5 hashed file name
}

有关测试表达式的一些信息

我以 AngularJs Angular .html和.scss的方式进行区分,方法是在后缀 .component Angular 文件,例如rules: [{ test: /[\/\\]@angular[\/\\].+\.js$/, parser: { system: true } }, { test: /(?<!\.component)\.scss$/, use: [ { loader: prod ? MiniCssExtractPlugin.loader : "style-loader" }, { loader: "cache-loader" }, { loader: "css-loader", options: cssLoaderOptions }, { loader: "postcss-loader", options: { sourceMap: !prod } }, { loader: "fast-sass-loader", options: { includePaths: [ path.resolve(__dirname, "node_modules"), path.resolve(__dirname, "src") ] } } ] }, { test: /\.component\.scss/, use: [ { loader: "raw-loader" }, { loader: "fast-sass-loader", options: { includePaths: [ path.resolve(__dirname, "node_modules"), path.resolve(__dirname, "src") ] } } ] }, { test: /\.ts|\.js?$/, exclude: /node_modules/, use: [{ loader: "ts-loader" }, "angular-router-loader", "angular2-template-loader"] }, { test: /(?<!\.component)\.html$/, use: [{ loader: "ngtemplate-loader?relativeTo=" + (path.resolve(__dirname, "src")) }, { loader: "html-loader", options: { collapseWhitespace: true } }], exclude: [ path.resolve(__dirname, "src/index.html"), path.resolve(__dirname, "src/index-cloud.html"), /node_modules/ ] }, { test: /\.component\.html$/, use: [{ loader: "raw-loader" }] }, { test: /\.(jpe?g|gif|png|svg|ico)$/, use: [{ loader: "file-loader?relativeTo=" + (path.resolve(__dirname, "src/assets")), options: { name: "[hash].[ext]" } }] }, { test: /.(woff|woff2|eot|ttf|otf)$/, use: [{ loader: "file-loader", options: { name: "[hash].[ext]" } }] }] my-component.component.scss。 然后,要应用不同的加载程序,我使用negative lookahead expression AngularJs 加载程序中排除 Angular 文件,就像我对所做的那样Scss HTML 像这样:

my-component.component.html

相同
 /(?<!\.component)\.scss$/ // negative lookahead; excludes .component.scss but includes .scss

0 个答案:

没有答案