Функция Webpack для генерации экземпляров HtmlWebpackPlugin - не определено - PullRequest
0 голосов
/ 02 мая 2019

Я пытаюсь настроить веб-пакет для генерации HtmlWebpackPlugin экземпляров в зависимости от того, сколько .handlebars файлов у меня в папке с исходным кодом.

Проблема здесь в том, что, хотя внутри функции все возвращается правильно (имена, каталоги файлов и т. Д.), Когда я пытаюсь вызвать функцию в разделе плагинов в веб-пакете, я ничего не получаю. Под ничем я имею в виду, что я не получаю ошибок, но когда сервер запускается (сервер разработки), я получаю сообщение «Не удается получить» на страницах.

Я почти уверен, что я делаю (или думаю что-то не так) здесь, но почему он не генерирует экземпляры для меня, как следует?

Конфигурация веб-пакета:

var path = require('path');
var MiniCssExtractPlugin = require("mini-css-extract-plugin");
var HtmlWebpackPlugin = require('html-webpack-plugin');
var fs = require('file-system');
const templateFiles = fs.readdirSync(path.resolve(__dirname, "./Source/"));
//const devMode = process.env.NODE_ENV !== 'production'
const generateHtml = () => {
    templateFiles.forEach((file) => {
        if (file.indexOf(".handlebars") > -1) {

            const name = file.split(".")[0];
            const fileName = '.Source/' + file;
            console.log("the file name@");
            console.log(fileName);
            return new HtmlWebpackPlugin({
                title: name,
                fileName: name + ".html",
                template: fileName
            });
        }
    });

};    
const publicPath = '/';

module.exports = {
    // set this to your entry point - make sure you go in there and request the css file that you need to be built
    entry: {
        index: "./Source/js/index.js"
    },


    output: {
        //destination (dist) folder

        path: path.resolve(path.join(__dirname, 'Build')),




        filename: path.join('js', "bundle-[name].js"),
        //folder where there actual server will throw files in
        publicPath: publicPath,
    },

    // create a map file for debugging
    devtool: 'source-map',

    module: {
        rules: [
            {
                test: /\.(sa|sc|c)ss$/,
                exclude: /node_modules/,
                use: [{
                    loader: MiniCssExtractPlugin.loader,
                },
                {
                    loader: "css-loader", options: {
                        sourceMap: true
                    }
                }, {
                    loader: "sass-loader", options: {
                        sourceMap: true
                    }
                }]

            },
            {
                test: /\.(png|jpg|gif)$/,
                use: [
                    {
                        loader: 'file-loader',
                        options: {
                            name: '[name].[ext]',
                        },
                    },
                ],
            },
            {
                test: /\.handlebars$/,
                loader: "handlebars-loader"
            }
        ],
    },
    watch: false, // change this to true to keep webpack running

    plugins: [
        new MiniCssExtractPlugin({
            //define actual folder structure to your style.css (the output)
            //the scss file will be automatically retrieved from your index.js (or whatever the entry point you defined is)
            filename: path.join('css', "style.css"),
        }),
        //serve my own html template and define where it is. Css injection implied.
        generateHtml()
    ],
    //open the dev server on command 'npm start' or 'npm run start:dev'
    devServer: {
        contentBase: path.join('index.handlebars'),
        compress: true,
        port: 3000
    }
};`

Ответы [ 2 ]

0 голосов
/ 02 мая 2019

Короче говоря: webpack заботится о том, какой объект вы даете ему пережевывать.Таким образом, по умолчанию он не позволяет вам выполнять функции внутри объекта module.exports, который вы ему даете.

Что подводит меня к следующему пункту.И ответ:

Создайте свой собственный объект, затем загрузите его в веб-пакет.

Итак, я объявил свой конфиг как const, а затем сгенерировал конечный объект, который веб-пакет может прочитать (тот, у которого естьнесколько экземпляров HtmlWebpackPlugin), а затем я передал это в Webpack и вуаля, окончательный webpack.config:

var path = require('path');
var MiniCssExtractPlugin = require("mini-css-extract-plugin");
var HtmlWebpackPlugin = require('html-webpack-plugin');
var fs = require('file-system');
const templateFiles = fs.readdirSync(path.resolve(__dirname, "./Source/"));
//const devMode = process.env.NODE_ENV !== 'production'
const generateHtml = (config) => {
    templateFiles.forEach((file) => {
        if (file.indexOf(".handlebars") > -1) {

            const name = file.split(".")[0];
            const fileName = 'Source/' + file;
            config.plugins.push(new HtmlWebpackPlugin({
                title: name,
                filename: name + ".html",
                template: fileName
            }));
        }
    });

    return config
};


const publicPath = '/';

const baseConfig = {
    // set this to your entry point - make sure you go in there and request the css file that you need to be built
    entry: {
        index: "./Source/js/index.js"
    },

    // change this to your dist folder - Build in this case.
    output: {
        path: path.resolve(path.join(__dirname, 'Build')),
        filename: path.join('js', "bundle-[name].js"),
        //folder where there actual server will throw files in
        publicPath: publicPath,
    },

    // create a map file for debugging
    devtool: 'source-map',

    module: {
        rules: [
            {
                test: /\.(sa|sc|c)ss$/,
                exclude: /node_modules/,
                use: [{
                    loader: MiniCssExtractPlugin.loader,
                },
                {
                    loader: "css-loader", options: {
                        sourceMap: true
                    }
                }, {
                    loader: "sass-loader", options: {
                        sourceMap: true
                    }
                }]

            },
            {
                test: /\.(png|jpg|gif)$/,
                use: [
                    {
                        loader: 'file-loader',
                        options: {
                            name: '[name].[ext]',
                        },
                    },
                ],
            },
            {
                test: /\.handlebars$/,
                loader: "handlebars-loader"
            }
        ],
    },
    watch: false, // change this to true to keep webpack running

    plugins: [
        new MiniCssExtractPlugin({
            //define actual folder structure to your style.css (the output)
            //the scss file will be automatically retrieved from your index.js (or whatever the entry point you defined is)
            filename: path.join('css', "style.css"),
        }),
        //serve my own html template and define where it is. Css injection implied. 
    ],
    //open the dev server on command 'npm start' or 'npm run start:dev'
    devServer: {
        contentBase: path.join('index.handlebars'),
        compress: true,
        port: 3000
    }
};

console.log(baseConfig)

const config = generateHtml(baseConfig)
//feed new config object to webpack
module.exports = config
0 голосов
/ 02 мая 2019

Ваша generateHtml функция ничего не возвращает.

Попробуйте это.Теперь он должен вернуть массив экземпляра HtmlWebpackPlugin.

const generateHtml = () => {
  return templateFiles
    .filter((file) => file.indexOf(".handlebars") > -1)
    .map((file) => {
      const name = file.split(".")[0];
      const fileName = './Source/' + file;
      return new HtmlWebpackPlugin({
         title: name,
         fileName: name + ".html",
         template: fileName
      });
    })

Кроме того, вы должны распространить возвращенный массив в plugins

plugins: [
  ...generateHtml(),
]
...