簡體   English   中英

Typescript + react 17 + webpack 5. 使用 react HashRouter 進行代碼拆分不起作用

[英]Typescript + react 17 + webpack 5. Code splitting with react HashRouter not working

試圖創建一個具有新依賴項的項目,但我遇到了構建問題。

包.json:

{
  "name": "my-files",
  "version": "1.0.0",
  "description": "App",
  "main": "main.js",
  "scripts": {
    "format": "prettier --write ./src/**/*",
    "serve": "webpack serve --mode development",
    "build:dev": "webpack --mode development",
    "build": "webpack --mode production --config=webpack.config.js",

  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all",
      "IE 11"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "repository": {
    "type": "git",
    "url": ""
  },
  "author": "",
  "license": "MIT",
  "dependencies": {
    "axios": "^0.21.1",
    "path": "^0.12.7",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-hot-loader": "^4.13.0",
    "react-loadable": "^5.5.0",
    "react-router-dom": "^5.2.0"
  },
  "devDependencies": {
    "@babel/core": "^7.14.3",
    "@babel/plugin-proposal-class-properties": "^7.14.5",
    "@babel/plugin-syntax-dynamic-import": "^7.8.3",
    "@babel/plugin-transform-classes": "^7.14.5",
    "@babel/plugin-transform-runtime": "^7.14.5",
    "@babel/preset-env": "^7.14.4",
    "@babel/preset-react": "^7.13.13",
    "@babel/preset-typescript": "^7.14.5",
    "@babel/runtime": "^7.14.6",
    "@types/react": "^17.0.9",
    "@types/react-dom": "^17.0.6",
    "@types/react-router-dom": "^5.1.7",
    "@typescript-eslint/eslint-plugin": "^4.26.0",
    "@typescript-eslint/parser": "^4.26.0",
    "awesome-typescript-loader": "^5.2.1",
    "babel-loader": "^8.2.2",
    "clean-webpack-plugin": "^4.0.0-alpha.0",
    "copy-webpack-plugin": "^9.0.0",
    "core-js": "^3.15.2",
    "css-loader": "^5.2.6",
    "css-minimizer-webpack-plugin": "^3.0.2",
    "eslint": "^7.28.0",
    "eslint-config-airbnb": "^18.2.1",
    "eslint-config-prettier": "^8.3.0",
    "eslint-plugin-import": "^2.23.4",
    "eslint-plugin-jsx-a11y": "^6.4.1",
    "eslint-plugin-prettier": "^3.4.0",
    "eslint-plugin-react": "^7.24.0",
    "eslint-plugin-react-hooks": "^4.2.0",
    "file-loader": "^6.2.0",
    "fork-ts-checker-webpack-plugin": "^6.2.12",
    "html-loader": "^2.1.2",
    "html-webpack-plugin": "^5.3.1",
    "less": "^4.1.1",
    "less-loader": "^10.0.1",
    "mini-css-extract-plugin": "^1.6.0",
    "prettier": "~2.3.1",
    "style-loader": "^2.0.0",
    "ts-loader": "^9.2.2",
    "typescript": "^4.3.2",
    "webpack": "^5.38.1",
    "webpack-cli": "^4.7.0",
    "webpack-dev-server": "^3.11.2"
  }
}

webpack.config.js:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const { TsConfigPathsPlugin } = require('awesome-typescript-loader');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
// const TSLintPlugin = require('tslint-webpack-plugin');
// const ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = (() => {
  const config = {
    entry: './src/route.tsx',
    target: 'web',
    output: {
      path: path.resolve(__dirname, 'dist'),
      // filename: 'main.js',
      // chunkFilename: '[name].chunk.js',
    },
    resolve: {
      // modules: [path.resolve(__dirname, './src'), 'node_modules'],
      extensions: ['.js', '.jsx', '.json', '.ts', '.tsx'],
      plugins: [new TsConfigPathsPlugin()],
      alias: {
        components: path.resolve(__dirname, './src/components'),
        services: path.resolve(__dirname, 'src/services'),
        utils: path.resolve(__dirname, './src/utils'),
        web: path.resolve(__dirname, './src/web'),
      },
    },
    module: {
      rules: [
        {
          test: /\.(ts|js)x?$/,
          include: [/node_modules(\\|\/)(@elf|@webcomponents|lit-|nanoid)/, path.resolve(__dirname, 'src')],
          loader: 'babel-loader',
        },
        {
          test: /\.less$/,
          use: [MiniCssExtractPlugin.loader, 'css-loader', 'less-loader'],
        },
        // {
        //   test:  /\.(scss|css)$/,
        //   use: [MiniCssExtractPlugin.loader, 'css-loader'],
        // },
      //   {
      //     test: /\.html$/i,
      //     use: 'html-loader',
      //   },
      //   {
      //     test: /\.(png|jpg|woff|ttf)$/,
      //     use: [
      //       {
      //         loader: 'file-loader',
      //         options: {
      //           name: '[name].[ext]',
      //           outputPath: 'assets/',
      //           publicPath: 'assets/',
      //         },
      //       },
      //     ],
      //   },
      ]
    },
    plugins: [
      new CleanWebpackPlugin({
        cleanStaleWebpackAssets: false,
      }),
      new HtmlWebpackPlugin({
        template: path.resolve(__dirname, 'src', 'index.html'),
        cache: false,
      }),
      // new MiniCssExtractPlugin({
      //   filename: '[name].[contenthash].css',
      //   chunkFilename: '[id].[contenthash].css',
      // }),  
      new CopyWebpackPlugin({ 
        patterns: [
          { from: path.resolve(__dirname, 'src', 'assets'), to: path.resolve(__dirname, 'dist', 'assets') },
          { from: 'app.json', to: 'app.json' }
        ]
      }),
      new ForkTsCheckerWebpackPlugin({
        typescript: {
          diagnosticOptions: {
            semantic: true,
            syntactic: true,
          },
          mode: 'write-references',
        },
      }),  
      // new TSLintPlugin({
      //   files: ['./src/**/*.ts']
      // }),
      new MiniCssExtractPlugin(),
    ],
    devServer: {
      port: 3000,
      watchContentBase: true
    },
  };
  
  return config;
})();

.babelrc:

{
    "presets": [
        "@babel/preset-env",
        "@babel/preset-react",
        "@babel/preset-typescript"
    ],
    "plugins": [
        "@babel/plugin-syntax-dynamic-import",
        "@babel/plugin-transform-runtime",
        "@babel/plugin-proposal-class-properties",
        "@babel/plugin-transform-classes"
    ]
}

路由.jsx

import './index.less';

import React, { Suspense } from 'react';
import ReactDOM from 'react-dom';
import { HashRouter, Route, Switch } from 'react-router-dom';


  const App = React.lazy(() => import('./components/app/app')) as any;

  const AppComponentRender = () => {
    return <App />;
  };

  ReactDOM.render(
    <HashRouter>
      <Suspense fallback={<span>Loading...</span>}>
        <Switch>
          <Route exact path="/" render={AppComponentRender} />
          <Route render={AppComponentRender} />
        </Switch>
      </Suspense>
    </HashRouter>,
    document.getElementById('root'),
  );

應用程序.tsx

export default class App extends React.PureComponent {
  constructor(props: any) {
    super(props);
    this.state = {};
  }

  render() {
    return (
    <div>
      SUPER TEEEEEEESSSSSSSSSEEEEEETTTT
    </div>);
  };
}

當我嘗試“紗線構建”這個項目時,我收到以下錯誤:

區

錯誤


對於yarn build:dev ,它有效。

不確定我的回答是否能解決您的問題,但嘗試不會傷害您;) 在 mode='production' 上,Webpack 默認配置與 mode='development' 不同。

例如, optimization.splitChunks的默認值是不同的。

請嘗試在您的 Webpack 配置中使用此設置,希望它能幫助您解決類似問題:

{
  ...
  optimization: {
    splitChunks: {
        chunks: 'all',
        cacheGroups: {
            defaultVendors: {
                test: /[\\/]node_modules[\\/]/,
                name: 'vendor'
            },
            default: {
                name: 'main'
            },
        },
    }
}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM