Express 集成ect.js时视图路径错误问题求助
Hey there, let's break down why your ECT templates are being searched in the wrong directory. The core issue here is a mismatch between Express's default view directory settings and how you've configured ECT's root path. Here's what's happening and how to fix it:
Why the error occurs
Express has a built-in default: it looks for view files in a /views directory at your project root. Even though you set ECT's root to __dirname+'/src', if you don't update Express's own views configuration, it will still prepend /views to whatever path you pass to res.render(). That's why you're seeing the error about not finding src/index in /views — Express is trying to look for /views/src/index instead of your actual /src/index.ect file.
The fix: Align Express and ECT configurations
You need to make sure Express knows to use your /src directory as the root for views, and properly wire up ECT as the template engine. Here's the corrected configuration for your server.js:
const express = require('express'); const ect = require('ect'); const sassMiddleware = require('node-sass-middleware'); const app = express(); // 1. Configure ECT renderer const ectRenderer = ect({ root: __dirname + '/src', // ECT's template root (matches your existing setup) ext: '.ect' // Specify your template file extension }); // 2. Tell Express to use ECT for rendering .ect files app.engine('ect', ectRenderer.render); app.set('view engine', 'ect'); // Set ECT as the default view engine // 3. Critical: Update Express's view root to match ECT's root app.set('views', __dirname + '/src'); // 4. Node-sass-middleware config (this doesn't affect the view path issue, but double-check paths) app.use(sassMiddleware({ src: __dirname + '/src/scss', // Path to your raw SCSS files dest: __dirname + '/public/css', // Path to output compiled CSS debug: process.env.NODE_ENV !== 'production', // Enable debug in dev mode outputStyle: 'compressed' })); // Serve static files (like compiled CSS, JS, images) app.use(express.static(__dirname + '/public')); // Your root route app.get('/', (req, res) => { // Render 'index' — this will look for /src/index.ect now res.render('index'); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Key checks to confirm
- Make sure your template file exists at
/src/index.ect(with the.ectextension matching what you set in ECT's config). - Don't add a
src/prefix when callingres.render()— since we've set Express's view root to/src, just use the filename (without extension, since we setview enginetoect). - The
node-sass-middlewaresetup isn't causing this view path error, but ensure your SCSS and output paths are correct so your styles load properly.
内容的提问来源于stack exchange,提问作者Druckles

