编译.pug为HTML后外部CSS加载失败的解决方法(非Express环境)
Hey there! Let's walk through the common fixes for your CSS not loading issue—since you're not using Express, we can focus on path-related problems which are almost always the culprit here.
1. Double-Check Your Pug Link Tag Path
The most common issue is an incorrect href path in your Pug file's link tag. Remember: when Pug compiles to HTML, the path in the generated HTML is relative to the HTML file's location, not the original Pug file (though they're in the same folder here).
Based on Your Original Directory Structure:
Your setup looks like this:
-Directory |-Styles | |-example.css |-Examples |-example.pug |-example.html (after compilation)
So your Pug file should use a relative path pointing up one level to the Styles folder:
link(rel='stylesheet', href='../Styles/example.css')
If You Moved CSS to the Same Folder as Pug/HTML:
If you put example.css directly in the Examples folder, your link tag should be:
link(rel='stylesheet', href='example.css')
Or explicitly:
link(rel='stylesheet', href='./example.css')
2. Verify the Compiled HTML's Link Path
After running pug example.pug, open the generated example.html in a text editor and check the href attribute of the link tag. It should match the correct relative path we mentioned above. If it doesn't, double-check your Pug syntax—typos here are easy to miss!
3. Use Browser DevTools to Diagnose
Open your example.html in the browser, hit F12 to open DevTools, and go to the Network tab. Refresh the page and look for your example.css file:
- If you see a
404status: The path is wrong—adjust thehrefin your Pug file and recompile. - If the file loads (status 200) but styles still don't show: Check for CSS syntax errors in the Console tab, or make sure your selectors are targeting the right HTML elements.
4. Check for Case Sensitivity
If you're on Linux or macOS, filenames and folder names are case-sensitive. Make sure example.css isn't named Example.css or EXAMPLE.css, and that your path in the Pug tag matches the exact case of the folder/file names.
内容的提问来源于stack exchange,提问作者Josh

