[React Webpack]: модуль не найден: ошибка: не удается разрешить 'src / views / UserList' в 'C: \ Users \ ....' - PullRequest
0 голосов
/ 13 июля 2020

У меня есть приложение create-response-app, работающее на 100%, я хочу интегрировать webpack4 для развертывания моего приложения, но после настройки webpack, когда я «npm dev run», я получаю эти ошибки в каждой строке ленивого импорта: Module not обнаружено: Ошибка: не удается разрешить src / views / UserList в 'C: ....'

My webpack.config. js:

// webpack.config.js
const path = require( 'path' );
const HtmlWebPackPlugin = require( 'html-webpack-plugin' );
const webpack=require('webpack');

module.exports = {
    context: __dirname,
    entry: {
        bundle: './src/index.js',
        
      },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'main.js',
   },
   devServer: {
    historyApiFallback: true
    },
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /node_modules/,
                use: ["babel-loader"],
            },
            {
                test: /\.((c|sa|sc)ss)$/i,
                use: ['style-loader', 'css-loader']
            },
            {
                test: /\.(png|j?g|svg|gif)?$/,
                use: 'file-loader',
                include: path.resolve(__dirname, 'src')
             }
        ]
    },
    plugins: [
        
        new HtmlWebPackPlugin({
           template: path.resolve( __dirname, 'public/index.html' ),
           filename: 'index.html'
        }),
        new webpack.DefinePlugin({
            'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
          })
       
     ],
    
    
};

Мои маршруты. js:

/* eslint-disable react/no-multi-comp */
/* eslint-disable react/display-name */
import React, { lazy } from 'react';
import { Redirect } from 'react-router-dom';
import AuthLayout from './layouts/Auth';
import ErrorLayout from './layouts/Error';
import DashboardLayout from './layouts/Dashboard';
import DashboardView from './views/Dashboard';

export default [
  {
    path: '/',
    exact: true,
    component: () => <Redirect to="/dashboard" />
  },
  {
    path: '/auth',
    component: AuthLayout,
    routes: [
      {
        path: '/auth/login',
        exact: true,
        component: lazy(() => import('src/views/Login'))
      },
      {
        component: () => <Redirect to="/errors/error-404" />
      }
    ]
  },
  {
    path: '/errors',
    component: ErrorLayout,
    routes: [
      {
        path: '/errors/error-403',
        exact: true,
        component: lazy(() => import('src/views/Error403'))
      },
      {
        path: '/errors/error-404',
        exact: true,
        component: lazy(() => import('src/views/Error404'))
      },
      {
        path: '/errors/error-500',
        exact: true,
        component: lazy(() => import('src/views/Error500'))
      },
      {
        component: () => <Redirect to="/errors/error-404" />
      }
    ]
  },
  {
    route: '*',
    component: DashboardLayout,
    routes: [
      {
        path: '/dashboard',
        exact: true,
        component: DashboardView
      },
      {
        path: '/users',
        exact: true,
        component: lazy(() => import('src/views/UserList'))
      },
      {
        path: '/brands',
        exact: true,
        component: lazy(() => import('src/views/BrandList'))
      },
      {
        path: '/brands/new',
        exact: true,
        component: lazy(() => import('src/views/BrandForm/index'))
      },
      {
        path: '/brands/:id',
        exact: true,
        component: lazy(() => import('src/views/BrandDetails'))
      },
      {
        path: '/users/new',
        exact: true,
        component: lazy(() => import('src/views/AddUser'))
      },
      {
        path: '/users/:id',
        exact: true,
        component: lazy(() => import('src/views/UserDetails'))
      },
      {
        path: '/users/:id/:tab',
        exact: true,
        component: lazy(() => import('src/views/UserDetails'))
      },
      {
        path: '/users/:id/:tab/:itemId',
        exact: true,
        component: lazy(() => import('src/views/ItemDetails'))
      },
      {
        path: '/service-partners/providers',
        exact: true,
        component: lazy(() => import('src/views/ProviderList'))
      },
      {
        path: '/service-partners/providers/:id',
        exact: true,
        component: lazy(() => import('src/views/ProviderDetails'))
      },
      {
        path: '/service-partners/services',
        exact: true,
        component: lazy(() => import('src/views/ServiceList'))
      },
      {
        path: '/service-partners/services/:id',
        exact: true,
        component: lazy(() => import('src/views/ServiceDetails'))
      },
      {
        path: '/service-partners/categories',
        exact: true,
        component: lazy(() => import('src/views/ServiceCategoryList'))
      },
      {
        path: '/feeds',
        exact: true,
        component: lazy(() => import('src/views/PersonalFeedList'))
      },
      {
        path: '/feeds/:id',
        exact: true,
        component: lazy(() => import('src/views/PersonalFeedDetails'))
      },
      {
        component: () => <Redirect to="/errors/error-404" />
      }
    ]
  }
];

Структура приложения:

public/
  index.html

src/
  views/
  components/
  index.js
  routes.js

Любые решения, пожалуйста ..

1 Ответ

0 голосов
/ 13 июля 2020

По умолчанию webpack ищет только node_modules, если вы не указываете ему относительный / абсолютный путь, поэтому вам нужно добавить это в свой webpack.config.js, чтобы он также выполнял поиск в каталоге проекта root:

module.exports = {
  //...
  resolve: {
    modules: ['.', 'node_modules']
  }
};

Подробнее здесь . Обратите внимание, что порядок здесь имеет значение, сначала выполняется поиск в каталоге проекта root, затем в node_modules, вы можете его изменить.

...