首页 > 解决方案 > webpack-dev-server 没有重新编译输出文件

问题描述

这是我的 webpack 文件,没什么特别的

const path = require('path')

module.exports = {
    entry: './src/index.js',
    output: {
        path: path.resolve(__dirname, 'public/scripts'),
        publicPath: '/public/scripts/',
        filename: 'bundle.js'
    },
    module: {
        rules: [{
            test: /\.js$/,
            exclude: /node_modules/,
            use: {
                loader: 'babel-loader',
                options: {
                    presets: ['env']
                }
            }
        }]
    },
    devServer: {
        contentBase: path.resolve(__dirname, 'public'),
        watchContentBase : true, 
        publicPath: '/scripts/'
    }
}

但是,当我运行“npm run webpack-dev-server”时,我得到了正常的 node.js 输出,但在进行新更改时网站不会更新。我删除了 bundle.js 文件,当我再次运行它时,我收到一条错误消息,提示“找不到 bundle.js”。我发现在运行此命令时根本没有重新编译 bundle.js。

如果这有什么不同,我在窗户上。任何帮助,将不胜感激。

编辑:下面是我的文件夹结构。

这是我的文件夹结构

标签: javascriptnode.jswebpackbabel-loader

解决方案


您需要为 devServer 使用 watchContentBase 选项:

watchContentBase:true

还建议为模块 replecement 设置 hot:true 和 open:true - 这样当您运行开发服务器时,它会自动在默认浏览器中打开您的站点。您可以在此处找到有关 devServer 选项的更多信息 - https://webpack.js.org/configuration/dev-server/#devserverwatchoptions-

编辑

因此,经过长时间的聊天对话,结果如下:

仍然要“实时重新加载”您应该使用的页面

watchContentBase
但是在这种情况下还有其他问题 - devServer 中的 publicPath 和 outputPath 不一样,然后 index.html 应该引用 /public/scripts 下的 bundle.js

新的 webpack.config.js:



    const path = require('path')
    
    module.exports = {
        entry: './src/index.js',
        output: {
            path: path.resolve(__dirname, '/public/scripts'),
            publicPath: '/public/scripts',
            filename: 'bundle.js'
        },
        module: {
            rules: [{
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['env']
                    }
                }
            }]
        },
        devServer: {
            contentBase: path.resolve(__dirname, 'public'),
            watchContentBase : true, 
            publicPath: '/public/scripts'
        }
    }

Index.html 中 bundle 的新 src: /public/scripts/bundle.js


推荐阅读