scss 中的 webpack 5 图像/字体未正确编译

Rob*_*ieC 4 javascript sass node.js webpack

我的问题是;我的 .scss 文件中的图像和字体被重命名为 hash,并且 scss 文件中的 url 路径正在更改。我的 .scss 文件被导入到文件最顶部的 app.js 中,如下所示:

import '../scss/app.scss';
Run Code Online (Sandbox Code Playgroud)

我的 .scss 文件中的示例:

@font-face {
  font-family: 'FTBase';
  src: url("../fonts/FTBase-Book.woff2") format("woff2"),
    url("../fonts/FTBase-Book.woff") format("woff");
  font-weight: 350;
  font-style: normal;
  font-display: swap
}
.event--1 {
  background: var(--salmon) url("../images/leading-women.jpg") no-repeat center;
  background-size: contain;
}
Run Code Online (Sandbox Code Playgroud)

我运行 dev/build/product 后的输出是:

@font-face {
  font-family: "FTBase";
  src: url(../51ebe4030489fa0868f9.woff2) format("woff2"), url(../be034b081210fbdf38a2.woff) format("woff");
  font-weight: 350;
  font-style: normal;
  font-display: swap;
}
.event--2 {
  background: var(--salmon) url(../485639d38ea610d7bba2.jpg) no-repeat center;
  background-size: cover;
}
Run Code Online (Sandbox Code Playgroud)

并将图像/字体输出到/dist。

这是我的 webpack 文件:webpack.config.js:

const templateFiles = fs.readdirSync(environment.paths.source)
  .filter((file) => path.extname(file).toLowerCase() === '.html');

const htmlPluginEntries = templateFiles.map((template) => new HTMLWebpackPlugin({
  inject: 'body',
  hash: false,
  minify: false,
  filename: template,
  template: path.resolve(environment.paths.source, template),
  favicon: path.resolve(environment.paths.source, 'images', 'favicon.ico'),
}));

module.exports = {
  entry: {
    app: path.resolve(environment.paths.source, 'js', 'app.js'),
  },
  output: {
    filename: 'js/[name].js',
    path: environment.paths.output,
  },
  module: {
    rules: [{
        test: /\.((c|sa|sc)ss)$/i,
        use: [{
          loader: MiniCssExtractPlugin.loader,
          options: {
            publicPath: '../',
          }
        }, {
          loader: 'css-loader',
        }, {
          loader: 'sass-loader',
        }, {
          loader: 'postcss-loader',
        }],
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: ['babel-loader'],
      },
      {
        test: /\.(png|gif|jpe?g|svg|jpg)$/i,
        use: [{
          loader: 'file-loader',
          options: {
            name: '[name].[ext]',
            outputPath: 'images/',
          },
        }, ],
      },
      {
        test: /\.(eot|ttf|woff|woff2)$/,
        use: [{
          loader: 'file-loader',
          options: {
            name: '[name].[ext]',
            outputPath: 'fonts/',
          },
        }, ],
      },
    ],
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: 'css/[name].min.css',
    }),
    new ImageminWebpWebpackPlugin({
      config: [{
        test: /\.(jpe?g|png)/,
        options: {
          quality: 76,
        }
      }],
      overrideExtension: true,
      detailedLogs: false,
      silent: false,
      strict: true,
    }),
    new CleanWebpackPlugin({
      verbose: true,
      cleanOnceBeforeBuildPatterns: ['**/*', '!stats.json'],
    }),
    new CopyWebpackPlugin({
      patterns: [{
        from: path.resolve(environment.paths.source, 'images'),
        to: path.resolve(environment.paths.output, 'images'),
        toType: 'dir',
        globOptions: {
          ignore: ['*.DS_Store', 'Thumbs.db'],
        },
      }, ],
    }),
  ].concat(htmlPluginEntries),
  target: 'web',
};
Run Code Online (Sandbox Code Playgroud)

webpack.dev.config.js:

const webpackConfiguration = require('../webpack.config');
const environment = require('./environment');

module.exports = merge(webpackConfiguration, {
  mode: 'development',

  /* Manage source maps generation process */
  devtool: 'eval-source-map',

  /* Development Server Configuration */
  devServer: {
    contentBase: environment.paths.output,
    watchContentBase: true,
    publicPath: '/',
    open: true,
    historyApiFallback: true,
    compress: true,
    overlay: true,
    hot: false,
    watchOptions: {
      poll: 300,
    },
    ...environment.server,
  },

  /* File watcher options */
  watchOptions: {
    aggregateTimeout: 300,
    poll: 300,
    ignored: /node_modules/,
  },

  /* Additional plugins configuration */
  plugins: [],
});
Run Code Online (Sandbox Code Playgroud)

webpack.prod.config.js:

const webpackConfiguration = require('../webpack.config');

module.exports = merge(webpackConfiguration, {
  mode: 'production',

  /* Manage source maps generation process. Refer to https://webpack.js.org/configuration/devtool/#production */
  devtool: false,

  /* Optimization configuration */
  optimization: {
    splitChunks: {
      chunks: 'all',
      name: 'vendor',
    },
    minimize: true,
    minimizer: [
      new TerserPlugin({
        parallel: true,
      }),
      new CssMinimizerPlugin(),
    ],
  },

  /* Performance treshold configuration values */
  performance: {
    maxEntrypointSize: 512000,
    maxAssetSize: 512000,
  },

  /* Additional plugins configuration */
  plugins: [],
});
Run Code Online (Sandbox Code Playgroud)

在我的 webpack.config.js 文件中,我尝试将 css-loader 和 sass-loader 上的 sourceMaps 设置为 true,更改 publicPath 以及我从其他论坛尝试过的其他一些操作,但没有成功。

Rob*_*ieC 6

所以我想通了,我必须从图像和字体中删除文件加载器。我将其替换为:

{
   test: /\.(png|jpg|gif|svg)$/,
   type: 'asset/resource',
}, {
   test: /.(ttf|otf|eot|woff(2)?)(\?[a-z0-9]+)?$/,
   type: 'asset/resource',
},
Run Code Online (Sandbox Code Playgroud)

然后我必须将输出编辑为:

  output: {
    filename: 'js/[name].js',
    path: environment.paths.output,
    assetModuleFilename: 'assets/[name][ext]',
  },
Run Code Online (Sandbox Code Playgroud)

因此,现在当我运行 dev/build/product 时,它会获取 scss 文件中的所有资产,使它们保持相同的名称,并创建一个名为“assets”的文件夹,该文件夹位于“/dist/assets”,并且它会自动更改 url在 scss 文件中添加到 '../assets/image.jpg'