Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/webpack/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 使用create react app的其他HtmlWebpackPlugin()页面_Reactjs_Webpack - Fatal编程技术网

Reactjs 使用create react app的其他HtmlWebpackPlugin()页面

Reactjs 使用create react app的其他HtmlWebpackPlugin()页面,reactjs,webpack,Reactjs,Webpack,我已从默认项目中弹出,正在尝试创建第二个,maintenance.html页面,Webpack可以像默认情况下使用public/index.html一样插入该页面。我已经阅读了许多问题;以及HtmlWebpackPlugin的文档,其中指出它应该尽可能简单: // Makes some environment variables available in index.html. // The public URL is available as %PUBLIC_URL% in index.htm

我已从默认项目中弹出,正在尝试创建第二个,
maintenance.html
页面,Webpack可以像默认情况下使用
public/index.html
一样插入该页面。我已经阅读了许多问题;以及HtmlWebpackPlugin的文档,其中指出它应该尽可能简单:

// Makes some environment variables available in index.html.
// The public URL is available as %PUBLIC_URL% in index.html, e.g.:
// <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
// In development, this will be an empty string.
new InterpolateHtmlPlugin(envObject),
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin({
  inject: true,
  template: paths.appHtml,
  minify: {
    minifyCSS: true,
  },
}),
以下是
public/index.HTML

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="theme-color" content="#ffffff">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <link id="js-favicon" rel="icon" type="image/png" href="%PUBLIC_URL%/favicon-32x32.png" sizes="32x32">
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
    <link rel="apple-touch-icon" sizes="180x180" href="%PUBLIC_URL%/apple-touch-icon.png">
    <link rel="mask-icon" href="%PUBLIC_URL%/safari-pinned-tab.svg" color="#0081c6">

    <script src="%PUBLIC_URL%/scripts/modernizr.custom.js"></script>
    <title></title>
  </head>
  <body>
    <!-- SVG sprite -->
    <div style="border: 0px; clip: rect(0px 0px 0px 0px); height: 0px; overflow: hidden; padding: 0px; position: absolute; width: 0px;">%SVG_SPRITE%</div>
    <div id="app" style="overflow: hidden;"></div>
  </body>
</html>

%SVG_精灵%

我还尝试将此复制到
public/maintenance.html
,但运气不好。

根据我最后的评论,请在webpack.config.prod.js而不是webpack.config.dev.js中进行更改,因为默认的
build
脚本使用它

更新:

webpack.config.prod.js
中的更改为-

运行
npm run build
后,build文件夹中会有这些文件-

使用webpack编译项目时是否显示此错误?或者它是在运行时出现的?这发生在运行时,当我直接访问页面时。谢谢。那就是网页设置的问题了。可以看更多的代码吗?特别是webpack.config文件?当然-我已经用该文件的全部内容编辑了我的原始问题。请也共享html模板。您好,我有一个单独的dev和prod build webpack配置文件,但这两个文件都不能与其他插件调用一起使用。在dev的例子中,我在运行“纱线开始”并访问维护URL后出现错误。我通过使用CRA创建一个新的空应用程序,重新记录了您的问题。然后我弹出并对webpack.config.prod.js进行了类似的更改,然后
npm run build
按预期创建了这两个文件。这可能是我们需要研究整个回购协议的问题之一。谢谢你坚持我的观点!我会再看一眼,看看这是不是我这一方遗漏了什么。您在开发模式下也能成功地完成这项工作吗?不客气。请注意,我的示例中的
filename
属性没有指向
public
,因为它表示输出文件名。cra中的公用文件夹包含输入模板,因此您不希望在其中写入输出文件。通过省略文件夹名,插件将在指定的输出文件夹中创建文件,在本例中为
build
。谢谢!这最终成为一个配置问题。非常感谢您的详细解释和宝贵时间。
/* THIS FILE HAS BEEN EDITED A BIT FROM https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/config/webpack.config.dev.js */

const autoprefixer = require('autoprefixer');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
const getClientEnvironment = require('./env');
const paths = require('./paths');

// Custom
const cssnano = require('cssnano');
const flexbugs = require('postcss-flexbugs-fixes');
const svgFragments = require('postcss-svg-fragments');

const fs = require('fs');

// Don't show deprecations
process.noDeprecation = true;

// @remove-on-eject-begin
// `path` is not used after eject - see https://github.com/facebookincubator/create-react-app/issues/1174
const path = require('path');
// @remove-on-eject-end

// Webpack uses `publicPath` to determine where the app is being served from.
// In development, we always serve from the root. This makes config easier.
const publicPath = '/';
// `publicUrl` is just like `publicPath`, but we will provide it to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_PATH%/xyz looks better than %PUBLIC_PATH%xyz.
const publicUrl = '';
// Get environment variables to inject into our app.
const env = getClientEnvironment(publicUrl);
// Get environment object passed down to HTML template
const envObject = env.raw;
// Read SVG sprite
const svgSprite = fs.readFileSync(`${paths.appPublic}/images/sprite.svg`, 'utf8');
// Add SVG output to variable object passed to HTML template
envObject.SVG_SPRITE = svgSprite;

// This is the development configuration.
// It is focused on developer experience and fast rebuilds.
// The production configuration is different and lives in a separate file.
module.exports = {
  /// You may want 'eval' instead if you prefer to see the compiled output in DevTools.
  // See the discussion in https://github.com/facebookincubator/create-react-app/issues/343.
  devtool: 'eval',
  // These are the "entry points" to our application.
  // This means they will be the "root" imports that are included in JS bundle.
  // The first two entry points enable "hot" CSS and auto-refreshes for JS.
  entry: [
    // Include an alternative client for WebpackDevServer. A client's job is to
    // connect to WebpackDevServer by a socket and get notified about changes.
    // When you save a file, the client will either apply hot updates (in case
    // of CSS changes), or refresh the page (in case of JS changes). When you
    // make a syntax error, this client will display a syntax error overlay.
    // Note: instead of the default WebpackDevServer client, we use a custom one
    // to bring better experience for Create React App users. You can replace
    // the line below with these two lines if you prefer the stock client:
    // require.resolve('webpack-dev-server/client') + '?/',
    // require.resolve('webpack/hot/dev-server'),
    require.resolve('react-dev-utils/webpackHotDevClient'),
    // Polyfills
    require.resolve('./polyfills'),
    // Finally, this is your app's code:
    paths.appIndexJs,
    // We include the app code last so that if there is a runtime error during
    // initialization, it doesn't blow up the WebpackDevServer client, and
    // changing JS code would still trigger a refresh.
  ],
  output: {
    // Next line is not used in dev but WebpackDevServer crashes without it:
    path: paths.appBuild,
    // Add /* filename */ comments to generated require()s in the output.
    pathinfo: true,
    // This does not produce a real file. It's just the virtual path that is
    // served by WebpackDevServer in development. This is the JS bundle
    // containing code from all our entry points, and the Webpack runtime.
    filename: 'static/js/bundle.js',
    // This is the URL that app is served from. We use "/" in development.
    publicPath: publicPath,
  },
  externals: {
    gsap: 'TweenMax',
  },
  resolve: {
    // This allows you to set a fallback for where Webpack should look for modules.
    // We read `NODE_PATH` environment variable in `paths.js` and pass paths here.
    // We placed these paths second because we want `node_modules` to "win"
    // if there are any conflicts. This matches Node resolution mechanism.
    // https://github.com/facebookincubator/create-react-app/issues/253
    modules: ['node_modules'].concat(paths.nodePaths),
    // These are the reasonable defaults supported by the Node ecosystem.
    // We also include JSX as a common component filename extension to support
    // some tools, although we do not recommend using it, see:
    // https://github.com/facebookincubator/create-react-app/issues/290
    extensions: ['.js', '.json', '.jsx'],
    alias: {
      react: path.resolve('./node_modules/react'),
      // Support React Native Web
      // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
      'react-native': 'react-native-web',
    },
  },
  // @remove-on-eject-begin
  // Resolve loaders (webpack plugins for CSS, images, transpilation) from the
  // directory of `react-scripts` itself rather than the project directory.
  resolveLoader: {
    modules: [
      // Lerna hoists everything, so we need to look in our app directory
      paths.appNodeModules,
    ],
  },
  module: {
    rules: [
      // Disable require.ensure as it's not a standard language feature.
      { parser: { requireEnsure: false } },
      {
        test: /\.(js|jsx)$/,
        enforce: 'pre',
        use: [
          {
            // @remove-on-eject-end
            loader: 'eslint-loader',
          },
        ],
        include: paths.appSrc,
      },
      // ** ADDING/UPDATING LOADERS **
      // The "url" loader handles all assets unless explicitly excluded.
      // The `exclude` list *must* be updated with every change to loader extensions.
      // When adding a new loader, you must add its `test`
      // as a new entry in the `exclude` list for "url" loader.

      // "file" loader makes sure those assets get served by WebpackDevServer.
      // When you `import` an asset, you get its (virtual) filename.
      // In production, they would get copied to the `build` folder.
      {
        test: /\.(ico|jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2)(\?.*)?$/,
        loader: 'file-loader',
        options: {
          name: 'static/media/[name].[hash:8].[ext]',
        },
      },
      // "url" loader works like "file" loader except that it embeds assets
      // smaller than specified limit in bytes as data URLs to avoid requests.
      // A missing `test` is equivalent to a match.
      {
        test: /\.(mp4|webm|wav|mp3|m4a|aac|oga)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: 'static/media/[name].[hash:8].[ext]',
        },
      },
      // Process JS with Babel.
      {
        test: /\.(js|jsx)$/,
        include: paths.appSrc,
        loader: 'babel-loader',
        options: {
          // @remove-on-eject-end
          // This is a feature of `babel-loader` for webpack (not Babel itself).
          // It enables caching results in ./node_modules/.cache/babel-loader/
          // directory for faster rebuilds.
          cacheDirectory: true,
        },
      },
      {
        test: /\.less$/,
        use: [
          {
            loader: 'style-loader',
          },
          {
            loader: 'css-loader',
            options: {
              sourceMap: true,
            }
          },
          {
            loader: 'postcss-loader',
            options: {
              sourceMap: true,
              ident: 'postcss', // https://webpack.js.org/guides/migrating/#complex-options
              plugins: () => [
                autoprefixer({
                  browsers: [
                    '>2%',
                    'last 2 versions',
                    'not ie < 11',
                  ],
                  cascade: false,
                }),
                cssnano({
                  discardUnused: false,
                  zindex: false,
                  reduceIdents: false,
                  mergeIdents: false,
                }),
                flexbugs(),
                svgFragments(),
              ],
            },
          },
          {
            loader: 'less-loader',
            options: {
              sourceMap: true,
            }
          },
        ],
      },
    ],
  },
  plugins: [
    // Makes some environment variables available in index.html.
    // The public URL is available as %PUBLIC_URL% in index.html, e.g.:
    // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    // In development, this will be an empty string.
    new InterpolateHtmlPlugin(envObject),
    // Generates an `index.html` file with the <script> injected.
    new HtmlWebpackPlugin({
      inject: true,
      template: paths.appHtml,
      minify: {
        minifyCSS: true,
      },
    }),
    // Makes some environment variables available to the JS code, for example:
    // if (process.env.NODE_ENV === 'development') { ... }. See `./env.js`.
    new webpack.DefinePlugin(env.stringified),
    // This is necessary to emit hot updates (currently CSS only):
    new webpack.HotModuleReplacementPlugin(),
    // Watcher doesn't work well if you mistype casing in a path so we use
    // a plugin that prints an error when you attempt to do this.
    // See https://github.com/facebookincubator/create-react-app/issues/240
    new CaseSensitivePathsPlugin(),
    // If you require a missing module and then `npm install` it, you still have
    // to restart the development server for Webpack to discover it. This plugin
    // makes the discovery automatic so you don't have to restart.
    // See https://github.com/facebookincubator/create-react-app/issues/186
    new WatchMissingNodeModulesPlugin(paths.appNodeModules),
  ],
  // Some libraries import Node modules but don't use them in the browser.
  // Tell Webpack to provide empty mocks for them so importing them works.
  node: {
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
  },
  // Turn off performance hints during development because we don't do any
  // splitting or minification in interest of speed. These warnings become
  // cumbersome.
  performance: {
    hints: false,
  },
};
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="theme-color" content="#ffffff">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <link id="js-favicon" rel="icon" type="image/png" href="%PUBLIC_URL%/favicon-32x32.png" sizes="32x32">
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
    <link rel="apple-touch-icon" sizes="180x180" href="%PUBLIC_URL%/apple-touch-icon.png">
    <link rel="mask-icon" href="%PUBLIC_URL%/safari-pinned-tab.svg" color="#0081c6">

    <script src="%PUBLIC_URL%/scripts/modernizr.custom.js"></script>
    <title></title>
  </head>
  <body>
    <!-- SVG sprite -->
    <div style="border: 0px; clip: rect(0px 0px 0px 0px); height: 0px; overflow: hidden; padding: 0px; position: absolute; width: 0px;">%SVG_SPRITE%</div>
    <div id="app" style="overflow: hidden;"></div>
  </body>
</html>