webpack在路径改变时从错误的URL加载

Webpack loads from the wrong URL when the path changes

我正在编写一个 React 应用程序,当我导航到 localhost:3000 时一切正常,但是当我尝试转到 localhost:3000/foo/page 时,我收到一条错误消息,告诉我 [=22] =]/foo/bundle.js无法加载。

对我来说,这看起来像是 Webpack 在错误的地方寻找 bundle.js 的问题,但我不确定。如何让应用始终查看 localhost:3000 以获得 bundle.js?

这是我的一些 webpack 配置。

var TARGET = process.env.npm_lifecycle_event;
var ROOT_PATH = path.resolve(__dirname);
var APP_PATH = path.resolve(ROOT_PATH, 'app');
var BUILD_PATH = path.resolve(ROOT_PATH, 'dist');

process.env.BABEL_ENV = TARGET;
var common = {
    entry: APP_PATH,

    output: {
        path: BUILD_PATH,
        filename: 'bundle.js'
    },

    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                loaders: ['babel'],
                include: APP_PATH
            },
            {
                test: /\.svg$/,
                loader: 'url-loader?limit=8192',
                include: APP_PATH
            },
            {
                test: /\.png$/,
                loader: 'url-loader?limit=8192',
                include: APP_PATH
            },
            {
                test: /\.ico$/,
                loader: 'url-loader?limit=8192',
                include: APP_PATH
            }
        ]
    },

    plugins: [
        new HtmlWebpackPlugin({
            title: 'foobar',
            template: path.resolve(APP_PATH, 'index.html'),
            favicon: path.resolve(APP_PATH, 'images', 'favicon.ico')
        })
    ]
};

if (TARGET === 'start' || !TARGET) {
    module.exports = merge(common, {
        devtool: 'eval-source-map',
        module: {
            loaders: [
                {
                    test: /\.scss$/,
                    loaders: ['style', 'css', 'sass'],
                    include: APP_PATH
                }
            ]
        },
        devServer: {
            historyApiFallback: true,
            hot: true,
            inline: true,
            port: 3000,
            progress: true
        },
        plugins: [
            new webpack.HotModuleReplacementPlugin()
        ]
    });
}

output.publicPath: '/' 添加到您的 webpack 配置中。

output: {
  path: BUILD_PATH,
  publicPath: '/',
  filename: 'bundle.js'
}

HtmlWebpackPlugin 最有可能生成的文件具有:

<script src="bundle.js"></script>

设置output.publicPath: '/'将使它:

<script src="/bundle.js"></script>

来自 Webpack Config 页:

output.publicPath

The publicPath specifies the public URL address of the output files when referenced in a browser. For loaders that embed or tags or reference assets like images, publicPath is used as the href or url() to the file when it’s different then their location on disk (as specified by path). This can be helpful when you want to host some or all output files on a different domain or on a CDN. The Webpack Dev Server also takes a hint from publicPath using it to determine where to serve the output files from. As with path you can use the [hash] substitution for a better caching profile.