Реагируйте на ленивую загрузку ChunklLoadError на производственную сборку веб-пакета - PullRequest
0 голосов
/ 10 марта 2020

Я использую отложенную загрузку React для динамической загрузки моих компонентов и некоторых значков antd. Он отлично работает в среде разработки. Но у меня есть некоторая ошибка ChunkLoadError на моей странице, когда он пытается загрузить компоненты. Тем не менее, он работает нормально, когда я удаляю все отложенные загрузки.

Вот пример кода:

const ProtectedRoute = lazy(() => import('./ProtectedRoute'));
const Login = lazy(() => import('../examples/AnimatedLoginForm'));
const Home = lazy(() => import('./Home'));
const Account = lazy(() => import('./Account'));

const Router = () => {
  return (
    <BrowserRouter>
      <MainLayout>
        <Suspense fallback={<Spinner />}>
          <Switch>
            <Route exact path="/login" component={Login} />
            <ProtectedRoute exact path="/" component={Test} />
            <ProtectedRoute path="/form" component={Home} />
            <ProtectedRoute path="/settings" component={Settings} />
            <ProtectedRoute path="/account" component={Account} />
          </Switch>
        </Suspense>
      </MainLayout>
    </BrowserRouter>
  );
};

И вот мой webpack.config. js:

const path = require('path');
const webpack = require('webpack');
const dotenv = require('dotenv');
const fs = require('fs');
const AntdDayjsWebpackPlugin = require('antd-dayjs-webpack-plugin');

module.exports = ({ ENVIRONMENT }) => {
  // Get the root path (assuming your webpack config is in the root of your project!)
  const currentPath = path.join(__dirname);

  // Create the fallback path (the production .env)
  const basePath = `${currentPath}/.env`;

  // We're concatenating the environment name to our filename to specify the correct env file!
  const envPath = `${basePath}.${ENVIRONMENT}`;

  // Check if the file exists, otherwise fall back to the production .env
  const finalPath = fs.existsSync(envPath) ? envPath : basePath;

  // Set the path parameter in the dotenv config
  const fileEnv = dotenv.config({ path: finalPath }).parsed;

  // Reduce it to a nice object, the same as before (but with the variables from the file)
  const envKeys = fileEnv
    ? Object.keys(fileEnv).reduce((prev, next) => {
        const state = prev;

        state[`process.env.${next}`] = JSON.stringify(fileEnv[next]);
        return state;
      }, {})
    : {};

  return {
    entry: { app: './src/index.jsx' },
    module: {
      rules: [
        {
          test: /\.(js|jsx)$/,
          exclude: /(node_modules|bower_components)/,
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env'],
            plugins: [
              [
                'import',
                { libraryName: 'antd', libraryDirectory: 'es', style: true }
              ]
            ]
          }
        },
        {
          // CSS imports
          test: /\.css$/,
          use: ['style-loader', 'css-loader']
        },
        {
          test: /\.less$/,
          use: [
            { loader: 'style-loader' },
            { loader: 'css-loader' },
            {
              loader: 'less-loader',
              options: {
                modifyVars: {},
                javascriptEnabled: true
              }
            }
          ]
        },
        {
          test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
          use: [
            {
              loader: 'babel-loader'
            },
            {
              loader: '@svgr/webpack',
              options: {
                babel: false,
                icon: true
              }
            }
          ]
        },
        {
          // Images imports
          test: /\.(png|jpg|gif)$/,
          use: ['file-loader']
        },
        {
          // Fonts imports
          test: /\.(woff|woff2|eot|ttf|otf)$/,
          use: ['file-loader']
        }
      ]
    },
    resolve: { extensions: ['*', '.js', '.jsx'] },
    output: {
      path: path.resolve(__dirname, 'dist'),
      publicPath: '/dist/',
      filename: '[name].bundle.js'
    },
    devServer: {
      contentBase: path.join(__dirname, 'public/'),
      port: 3000,
      publicPath: 'http://localhost:3000/dist/',
      historyApiFallback: true,
      hotOnly: true
    },
    plugins: [
      new webpack.HotModuleReplacementPlugin(),
      new webpack.DefinePlugin(envKeys),
      new AntdDayjsWebpackPlugin()
    ]
  };
};

И мой .babelr c

{
  "presets": [
    "@babel/env",
    "@babel/preset-react"
  ],
  "plugins": [
    "syntax-dynamic-import"
  ]
}

Я много чего перепробовал, ничего не помогло, помогите пожалуйста.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...