首页 > 解决方案 > 使用 preloader-render 时无法启动 npm

问题描述

我正在运行 webpack,并且正在使用prerender-loader来呈现语义静态 HTML,而不是大部分为空的 HTML 页面。

我可以npm run build,我在输出中看到了所需的 HTML。

但是,当我尝试时npm start,我收到此错误:

    ERROR in ./src/index.html (./node_modules/prerender-loader/dist/prerender-loader.js?string!./src/index.html) 
    Module build failed (from ./node_modules/prerender-loader/dist/prerender-loader.js): 
    Error: Error:  Module not found. attempted require("url")

我没有找到很多关于这个问题的资源。此链接提供建议,但没有明确的答案。

我的webpack.config.js


    /* eslint-env node */
    const htmlPlugin = require('html-webpack-plugin');
    const miniCssExtractPlugin = require('mini-css-extract-plugin');
    const optimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');

    /* eslint-env node */
    const htmlPlugin = require('html-webpack-plugin');
    const miniCssExtractPlugin = require('mini-css-extract-plugin');
    const optimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');

    module.exports = {
        entry: './src/main.js',
        output: {
            filename: 'bundle.js',
            path: `${__dirname}/build`
        },
        optimization: {
            minimizer: [
                new optimizeCSSAssetsPlugin({}),
            ]
        },
        plugins: [
            new htmlPlugin({
                template: '!!prerender-loader?string!./src/index.html', 
            }),
            new miniCssExtractPlugin({ filename: 'main.css' })
        ],
        module: {
            rules: [
                {
                    test: /.html$/,
                    use: {
                        loader: 'html-loader'
                    }
                },
                {
                    test: /\.css$/,
                    use:  [
                        { 
                            loader: 'style-loader' 
                        }, 
                        miniCssExtractPlugin.loader, 
                        { 
                            loader: 'css-loader' 
                        }, 
                        { 
                            loader: 'postcss-loader'
                        }
                    ]
                },
                {
                    test: /\.(jpg|png|svg)$/,
                    use: {
                        loader: 'url-loader',
                        options: {
                            limit: 5000
                        }
                    }
                }
            ]
        }
    };

谢谢你的帮助。

标签: javascriptnode.jswebpack

解决方案


如果有人仍然有这个问题,一个快速的解决方案是prerender-loader在不构建时排除:

const isProduction = process.env.NODE_ENV == "production"

module.exports = {
    plugins: [
        new htmlPlugin({
            template: isProduction ? 
                '!!prerender-loader?string!./src/index.html' : 
                './src/index.html',
        }),
        new miniCssExtractPlugin({ filename: 'main.css' })
    ],
}

如果需要,此模式允许使用不同的模板进行开发和生产。


推荐阅读