Webpack + Express, указать файл c js в зависимости от вида - PullRequest
0 голосов
/ 26 марта 2020

Привет и заранее спасибо за вашу помощь,

Так что я совсем новичок в node.js и использую express.

В моем текущем проекте я использую express + веб-пакет. Все мои представления работают за исключением того факта, что я не могу загрузить файл javascript в других представлениях, кроме индекса.

Я хотел бы иметь файл javascript для каждого просмотра, index будет иметь индекс. js, traduction traduction. js et c, но в настоящее время файл не загружается.

Я пытался использовать HtmlWebpackPlugin и иметь разные чанки для каждого представления, но ничего из того, что я пробовал, не сработало.

Вот мой конфиг веб-пакета:

'use strict';

const path = require('path');
const webpack = require('webpack');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const keys = require('./keys_dev.js');

const __root = path.resolve(__dirname, '../');

module.exports = {
    entry: {
        index: [path.join(__dirname, '../src/scripts/index.js')],
        traduction: [path.join(__dirname, '../src/scripts/traduction.js')],     
    },
    output: {
        filename: 'scripts/[name].js',
    },
    module: {
        rules: [
        {
            test: /\.js$/,
            use: {
                loader: 'babel-loader',
                options: {
                    presets: ['@babel/preset-env'],
                    plugins: ['@babel/plugin-syntax-dynamic-import']
                }
            },
            exclude: /node_modules/
        },
        {
            test: /\.(glsl|frag|vert)$/,
            use: ['glslify-import-loader', 'raw-loader', 'glslify-loader']
        },
        {
            test: /three\/examples\/js/,
            use: 'imports-loader?THREE=three'
        },
        {
            test: /\.css$/,
            use: [MiniCssExtractPlugin.loader, 'css-loader', 'style-loader']
        },
        {
            test: /\.(woff|woff2|eot|ttf|otf)$/,
            use: 'file-loader'
        },
        {
            test: /\.(jpe?g|png|gif)$/i,
            use: 'file-loader'
        }
        ]
    },
    resolve: {
        alias: {
            'three-examples': path.join(__root, './node_modules/three/examples/js'),
        }
    },
    plugins: [
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery',
        }),
        new CleanWebpackPlugin(
            ['dist'],
            { root: __root },
            ),
        new CopyWebpackPlugin([
        {
            from: path.resolve(__root, 'static'),
        }
        ]),
        new HtmlWebpackPlugin(
            {
                filename: 'index.html',
                chunks: ['index'],
                template: './src/index.html',
            }
        ),
        new HtmlWebpackPlugin(
            {
                filename: 'traduction.html',
                chunks: ['traduction', 'index'],
                template: './src/traduction.html',
            }
        ),
        new webpack.ProvidePlugin({
            'THREE': 'three'
        }),
        new webpack.optimize.OccurrenceOrderPlugin(),
        new MiniCssExtractPlugin()
    ]
};

А вот мой сервер. js

const path = require('path');
const express = require('express');
const webpack = require('webpack');
const keys = require('./config/keys_dev.js');
const bodyParser = require('body-parser');
const webpackMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
const config = require('./config/common.js');
const nodemailer = require('nodemailer');
const stripe = require('stripe')(keys.stripeSecretKey);

const isDeveloping = process.env.NODE_ENV !== 'production';
const port = 8080;
const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
app.use(express.static('/src/scripts/'))
app.engine('html', require('ejs').renderFile);

if (isDeveloping) {
    const compiler = webpack(config);
    const middleware = webpackMiddleware(compiler, {
        contentBase: 'src'
    });

    app.use(middleware);
    app.use(webpackHotMiddleware(compiler));
    app.get('/', function response(req, res) {
        res.render(__dirname +"/src/index.html");
    });
    app.get('/cours', function response(req, res) {
        res.render(__dirname +"/src/cours.html");
    });
    app.get('/traduction', function response(req, res) {
        res.render(__dirname +"/src/traduction.html");
    });
    app.get('/boutique', function response(req, res) {
        res.render(__dirname +"/src/boutique.html");
    });
    app.get('/presentation', function response(req, res) {
        res.render(__dirname +"/src/presentation.html");
    });
    app.get('/ateliers', function response(req, res) {
        res.render(__dirname +"/src/ateliers.html");
    });
    app.post('/charge', (req, res) => {
        const amount = 300;
        stripe.customers.create({
            email: req.body.stripeEmail,
            source: req.body.stripeToken
        })
        .then(customer => stripe.charges.create({
            amount,
            description: req.body.cours,
            currency: 'eur',
            customer: customer.id
        }))
        .then(() => {
            var mailOpts, smtpTrans;

            smtpTrans = nodemailer.createTransport({
                service: 'gmail',
                auth: {
                    user: "******",
                    pass: "******"
                }
            });
            var mailoutput = "<html>\n\
            <body>\n\
            <tr>\n\
            <td>*****<br>\n\
            </td>\n\
            </tr>\n\
            </table></body></html>";

            mailOpts = {
                to: req.body.stripeEmail,
                attachments: [{
                    filename: req.body.cours + '.pdf',
                    path: path.join(__dirname, '/static/files/' + req.body.cours + '.pdf'),
                    contentType: 'application/pdf'
                }],
                subject: "******",
                html: mailoutput
            };

            smtpTrans.sendMail(mailOpts, function (error, res) {
                if (error) {
                    return console.log(error);
                }
            });
        })
        .then(charge => res.redirect('/'));
    });
}

Любые предложения о том, что я сделал не так?

1 Ответ

0 голосов
/ 26 марта 2020

попробуйте добавить загрузчик html в конфигурацию вашего веб-пакета https://webpack.js.org/loaders/html-loader/

...