如何让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
filtermethod does two critical checks:fs.statSync(fullItemPath).isFile()ensures we skip folders (sincefs.readdirSyncreturns both files and folder names by default)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.htmlwould be handled correctly, whereas splitting on.would break) - Consistent Paths: We use
path.joineverywhere to handle cross-platform path differences (no more manual string concatenation errors)
内容的提问来源于stack exchange,提问作者Aleksandr Gvozdev
相关产品推荐
相关产品推荐

