如何在React JS应用程序中加载manifest.json

问题描述 投票:0回答:3

我有一个使用 Webpack(而不是 CRA)设置的 React 应用程序。我试图通过添加与index.html 并行的manifest.json 文件来使其渐进。运行应用程序时,我遇到以下错误。

GET http://localhost:8090/manifest.json 404 (Not Found)

此外,如果我在运行

dist
命令后查看
build
文件夹,则没有
manifest.json
文件复制到
dist
。我尝试过使用 webpack 的
file-loader
插件,但它也不起作用。以下是
webpack.config.js
片段:

module: {
    rules: [
        { test: /\.(js)$/, exclude: /node_modules/, use: 'babel-loader' },
        { test: /\.css$/, use: ['style-loader', 'css-loader'] },
        //{ test: /\.html$/, use: ['html-loader'] },
        { test: /\.(svg|png|jpg|jpeg|gif)$/, use: { loader: 'file-loader', options: { name: '[name].[ext]', outputPath: 'assets/img' } } },
        { test: /\.(json)$/, use: { loader: 'file-loader', options: { name: '[name].[ext]', outputPath: './' } } }
    ]
},

下面是

index.html
片段:

<head>
   <link rel="manifest" href="./manifest.json" />
</head>

我做错了什么?

javascript html reactjs webpack
3个回答
4
投票

您可以执行以下步骤来加载

manifest.json

  • manifest.json
    放入项目根目录下的
    static
    文件夹中。
  • 在你的
    index.html
    <link rel="manifest" href="/manifest.json">

要了解您的文件是否已加载,请检查 Chrome DevTools,在 Application => Manifest 中


1
投票

如果上面的答案不适合您(就像我的情况一样),请尝试 app-manifest-webpack-plugin
当您运行 npm run build

yarn run build
时,它会为您构建
manifest.json
文件。
它还具有多种配置,使其非常灵活。


0
投票

尝试使用此插件自动生成清单文件。 插件:webpack-pwa-manifest

示例代码:

const WebpackPwaManifest = require('webpack-pwa-manifest');

new WebpackPwaManifest({
  name: 'My App',
  short_name: 'App',
  description: 'My awesome app',
  background_color: '#ffffff',
  theme_color: '#000000',
  publicPath: '/',
  icons: [
    {
      src: path.resolve('web/public/logo192.png'),
      sizes: [ 192],
    },
  ],
}),

注意:: publicPath: '/', 非常重要。这解决了我的 404 问题。

这是演示清单文件,将生成并存储在您的目标文件夹中,其中按照您的 webpack 配置文件存储 index.html。

记得使用
新的 HtmlWebpackPlugin({ 模板:path.resolve(appDirectory, 'web/public/index.html'), 注入:真实, }),

这将直接加载您的清单文件到index.html文件中。

© www.soinside.com 2019 - 2024. All rights reserved.