Рендеринг на стороне сервера с Webpack и Express во время выполнения - PullRequest
1 голос
/ 20 апреля 2019

Можно ли динамически визуализировать файлы шаблонов (например, Pug или Handlebars) во время выполнения, используя Webpack и Express?

Моя проблема заключается в том, что при загрузке моей корневой страницы (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"
                }
            }
        ]
    }
})
}
...