You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让fs.readdirSync仅读取指定目录下的.html文件?

Fix: Only Process .html Files in Specified Directory with HtmlWebpackPlugin

Got it, let's adjust your code so it only targets the .html files in your src directory and ignores folders/other file types. The key is adding a filter step to narrow down the files we process, plus some more reliable path handling.

Modified Code

const path = require('path'); // Make sure this is imported if not already
const fs = require('fs');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const rootDir = process.cwd(); // Adjust this if your root directory is different

function generateHtmlPlugins(templateDir) {
  const templateFiles = fs.readdirSync(path.join(rootDir, templateDir));

  // Filter to keep only .html files (and exclude folders)
  const htmlFiles = templateFiles.filter(item => {
    const fullItemPath = path.join(rootDir, templateDir, item);
    // Check if it's a file first, then verify it's an .html file
    return fs.statSync(fullItemPath).isFile() && path.extname(item) === '.html';
  });

  return htmlFiles.map(item => {
    // Get the filename without the .html extension (more reliable than splitting)
    const fileName = path.basename(item, '.html');
    return new HtmlWebpackPlugin({
      filename: `${fileName}.html`,
      template: path.join(rootDir, templateDir, item),
      inject: false
    });
  });
}

const htmlPlugins = generateHtmlPlugins('./src');

Key Changes Explained

  • File Filtering: The filter method does two critical checks:
    1. fs.statSync(fullItemPath).isFile() ensures we skip folders (since fs.readdirSync returns both files and folder names by default)
    2. path.extname(item) === '.html' guarantees we only keep files with the correct extension
  • Reliable Filename Handling: Using path.basename(item, '.html') avoids issues with filenames that have multiple dots (e.g., page.v2.html would be handled correctly, whereas splitting on . would break)
  • Consistent Paths: We use path.join everywhere to handle cross-platform path differences (no more manual string concatenation errors)

内容的提问来源于stack exchange,提问作者Aleksandr Gvozdev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:39:02