是否可以使用Webpack和Express在运行时动态地呈现模板文件(如Pug或工具栏)?
我的问题是当加载我的根页面(index.pug)时,html加载,但是没有加载任何资产。
示例:
app
.set('views', path.join(__dirname, 'views'))
.set('view engine', 'pug')
.use('/', function(req, res) {
res.render('index', {some: 'param'})
})如果我删除'/'路由处理程序,页面将装载所有资产。
客户端webpack.config.js文件:
module.exports = {
entry: {
main: ['webpack-hot-middleware/client?path=/__webpack_hmr&timeout=60000', './index.js', './css/main.css']
},
output: {
path: path.join(__dirname, 'dist'),
publicPath: '/',
filename: '[name].js'
},
mode: 'development',
target: 'web',
devtool: '#source-map',
module: {
rules: [
{
test: /\.pug$/,
use: ['html-loader?attrs=false', 'pug-html-loader']
}
]
},
plugins: [
new HtmlWebPackPlugin({
template: './views/index.pug',
filename: "./index.html",
excludeChunks: [ 'app' ]
})
]
}服务器webpack.server.config.js
module.exports = (env, argv) => {
return ({
entry: {
app: 'app.js',
},
output: {
path: path.join(__dirname, 'dist'),
publicPath: '/',
filename: '[name].js'
},
target: 'node',
node: {
// Need this when working with express, otherwise the build fails
__dirname: false, // if you don't put this is, __dirname
__filename: false, // and __filename return blank or /
},
externals: [nodeExternals()], // Need this to avoid error when working with Express
module: {
rules: [
{
// Transpiles ES6-8 into ES5
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
}
]
}
})
}发布于 2021-08-10 10:26:14
您可以通过两个简单的步骤(基于上面的代码)使其工作。
app
.set("views", "./dist");
.set('view engine', 'pug')
.use('/', function(req, res) {
res.render('index', {some: 'param'})
})此时,在运行构建脚本并启动服务器之后,我们将得到一条消息,显示dist文件夹中没有视图,这是正确的,因为引擎正在寻找模板,我们所拥有的只是html文件
plugins: [
new HtmlWebPackPlugin({
template: './views/index.pug',
filename: "./index.pug",
excludeChunks: [ 'app' ]
})
]就是这样。现在,模板引擎将在dist中找到具有注入样式和脚本的index.pug,并从中生成html。
注意:在生产中,为静态文件设置路径很重要,否则即使正确插入链接标记,也不会显示css
app.use(express.static(__dirname));当我遇到同样的问题时,上面的解决方案对我有效,但是使用了ejs模板。我在任何地方都找不到答案,所以希望它能拯救一些人几个小时的沮丧。
https://stackoverflow.com/questions/55770020
复制相似问题