是否可以在运行时使用 Webpack 和 Express 动态呈现模板文件(例如 Pug 或 Handlebars)?
我的问题是在加载我的根页面 ( 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"
}
}
]
}
})
}