用于生成 HtmlWebpackPlugin 实例的 Webpack 函数 - 未定义

Webpack function to generate HtmlWebpackPlugin Instances - undefined

我正在尝试将 webpack 配置为根据源文件夹中的 .handlebars 个文件生成 HtmlWebpackPlugin 个实例。

这里的问题是,即使函数内部的所有内容都正确返回(名称、文件目录等),当我尝试调用 webpack 的插件部分中的函数时,我什么也得不到。毫无意义,我的意思是我没有收到任何错误,但是当服务器启动时(开发服务器),我在页面上看到 'Cannot get'。

我很确定我正在做(或想错了)这里,但为什么它不按应有的方式为我生成实例?

webpack 配置:

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
    }
};`

您的 generateHtml 函数没有 returning 任何东西。

试试这个。现在应该 return 一个 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

中展开 returned 数组
plugins: [
  ...generateHtml(),
]

长话短说:webpack 关心你给它咀嚼什么样的对象。所以,默认情况下它不会让你在你给它的 module.exports 对象中执行函数。

这让我想到了下一点。答案是:

制作您自己的对象,然后将其提供给 webpack。

因此,我将我的配置声明为 const,然后生成了一个 webpack 可以读取的最终对象(具有多个 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