Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Bug]: Once a compilation error occurs, even if the code is fixed to be normal, the page still cannot recover. #9473

Open
jackiealex opened this issue Feb 26, 2025 · 5 comments
Assignees

Comments

@jackiealex
Copy link

jackiealex commented Feb 26, 2025

System Info

Image

// rspack.config.mjs

import { fileURLToPath } from 'url';
import path from 'node:path';

import { rspack } from '@rspack/core';
import { RsdoctorRspackPlugin } from '@rsdoctor/rspack-plugin';

import ReactRefreshPlugin from '@rspack/plugin-react-refresh';

import HtmlWebpackPlugin from 'html-webpack-plugin';  

import dotenv from 'dotenv'
import { globSync } from 'glob'


const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

console.log(__dirname, 'dirname');

const isDev = process.env.NODE_ENV === 'development'

const envConfig = dotenv.config({
  path: path.resolve(__dirname, `.env.${process.env.NODE_ENV}`),
}).parsed

let publicPath = envConfig.PUBLIC_PREFIX_PATH

const port = envConfig.PORT || 8088

console.log('env file config=', envConfig)
console.log('NODE_ENV=', process.env.NODE_ENV)
console.log('SSO_URL=', envConfig.SSO_URL)
console.log('publicPath=', publicPath)

 

// Find all main.tsx files in the pages directory to use as entry points
const entryPoints = globSync('./src/pages/**/main.tsx', {
  cwd: __dirname,
});

// Create entries object with page name as key and main.tsx file as value
const entries = entryPoints.reduce((acc, entryPath) => {
  // Extract page name from path (e.g., 'home' from './src/pages/home/main.tsx')
  const pageName = entryPath.split('/').slice(-2)[0];
  acc[pageName] = './' + entryPath;
  return acc;
}, {});

console.log(entries, 'entries');

// Find all HTML templates
const htmlTemplates = globSync('./src/pages/**/index.html', {
  cwd: __dirname,
});

/**
 * import RsPack.Config
 */
export default {
  context: __dirname,
  entry: entries,
  mode: isDev ? 'development' : 'production',

  cache: true,

  client: {
    overlay: {
      errors: true,
      warnings: false,
    },
    reconnect: true,
  },

  experiments: {
    css: true,
    incremental: true,
  },
  
  // Add output configuration with chunking strategy
  output: {
    path: __dirname + '/dist',
    filename: isDev ? '[name].js' : '[name].[contenthash].js',
    chunkFilename: isDev ? '[name].chunk.js' : '[name].[contenthash].chunk.js',
    publicPath: publicPath,
  },
  
  // Add optimization for code splitting
  optimization: isDev ? undefined : {
    splitChunks: {
      chunks: 'all',
      cacheGroups: {
        react: {
          test: /[\\/]node_modules[\\/](react|react-dom|scheduler|prop-types)[\\/]/,
          name: 'react',
          chunks: 'all',
          priority: 20
        },
        reactRouter: {
          test: /[\\/]node_modules[\\/]react-router(-dom)?[\\/]/,
          name: 'react-router',
          chunks: 'all',
          priority: 15
        },
        lodash: {
          test: /[\\/]node_modules[\\/]lodash(-es)?[\\/]/,
          name: 'lodash',
          chunks: 'all',
          priority: 10
        },
        zustand: {
          test: /[\\/]node_modules[\\/]zustand[\\/]/,
          name: 'zustand',
          chunks: 'all',
          priority: 5
        },
        vendors: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors',
          chunks: 'all',
          priority: -10
        },
        common: {
          name: 'common',
          minChunks: 2,
          chunks: 'all',
          priority: -20,
        }
      }
    }
  },
 
  module: {
    rules: [
      // js、ts loader
      {
        test: /\.(js|ts)$/,
        exclude: [/[\\/]node_modules[\\/]/],
        use: [
          {
            loader: 'builtin:swc-loader',
            options: {
              sourceMap: true,
              jsc: {
                parser: {
                  syntax: 'typescript',
                },
                externalHelpers: true,
              },
            },
          },
        ],
      },
      // jsx、tsx loader
      {
        test: /\.(jsx|tsx)$/,
        use: [
          {
            loader: 'builtin:swc-loader',
            /**
             * @type {import('@rspack/core').SwcLoaderOptions}
             */
            options: {
              sourceMap: true,
              jsc: {
                parser: {
                  syntax: 'typescript',
                  jsx: true,
                  tsx: true,
                },
                externalHelpers: true,
                transform: {
                  react: {
                    runtime: 'automatic',
                    throwIfNamespace: true,
                    useBuiltins: false,
                  },
                },
              },
            },
            type: "javascript/auto",
          },
        ],
      },
      // image loader
      {
        test: /\.(png|jpe?g|gif|svg|webp)$/i,
        type: 'asset',
        parser: {
          dataUrlCondition: {
            maxSize: 10 * 1024, // 10kb以下的图片转为内联
          },
        },
        generator: {
          filename: 'images/[name].[hash][ext]',
        },
      },
      // less loader
      {
        test: /.less$/,
        loader: 'less-loader',
        type: 'css',
      },
      // {
      //   test: /\.css$/i,
      //   use: [rspack.CssExtractRspackPlugin.loader, 'css-loader'],
      //   type: 'javascript/auto',
      // },
    ],
  },
  
  resolve: {
    extensions: ['.tsx', '.ts', '.jsx', '.js', '.json'],
    alias: {
      '@': path.resolve(__dirname, 'src'),
    },
  },
  
  devServer: {
    port: port,
    historyApiFallback: {
      // Redirect requests to the corresponding HTML files
      rewrites: Object.keys(entries).map(pageName => ({
        from: new RegExp(`^/${pageName}/?$`),
        to: `/${pageName}.html`
      })),
    },
    allowedHosts: 'all',
    open: [`http://localhost:${port}/home`],
  },
  
  plugins: [
    isDev && new ReactRefreshPlugin(),
    isDev && new rspack.HotModuleReplacementPlugin(),

    process.env.Doctor === 'development' &&
    new RsdoctorRspackPlugin({
      // plugin options
    }),

    new rspack.DefinePlugin({
      'process.env': JSON.stringify({
        ...envConfig,
      }),
    }),
    
    // Generate HTML files for each entry point
    ...htmlTemplates.map(template => {
      const pageName = template.split('/').slice(-2)[0];
      return new HtmlWebpackPlugin({
        templateParameters: {
          title: envConfig.TITLE,
        },
        template,
        filename: `${pageName}.html`,
        chunks: [pageName, 'react', 'react-router', 'lodash', 'zustand', 'vendors', 'common', 'runtime'],
        inject: true,
      });
    }),
  ].filter(Boolean),  // Filter out false values from conditional plugins
};

Details

change any tsx file with some error syntax, then compilation error occurs, but when you fix the code to be normal, compilation cant not recover

Image

Reproduce link

No response

Reproduce Steps

change any tsx file with some error syntax, then compilation error occurs, but when you fix the code to be normal, compilation cant not recove

@jackiealex jackiealex added the pending triage The issue/PR is currently untouched. label Feb 26, 2025
@jackiealex
Copy link
Author

jackiealex commented Feb 26, 2025

other problems

  1. code build takes 15s seconds, it is too long, longger than vite
  2. css or less file not compile and injected to the page correctly, which make css resource lost

@chenjiahan chenjiahan added need reproduction and removed pending triage The issue/PR is currently untouched. labels Feb 26, 2025
Copy link
Contributor

Hello @jackiealex, sorry we can't investigate the problem further without reproduction demo, please provide a repro demo by forking rspack-repro, or provide a minimal GitHub repository by yourself. Issues labeled by need reproduction will be closed if no activities in 14 days.

@chenjiahan
Copy link
Member

This has been fixed by #9482.

We will release a new Rspack patch today

@chenjiahan
Copy link
Member

Similar issue: web-infra-dev/rsbuild#4682

@chenjiahan
Copy link
Member

For other problems, feel free to create separate issues for them.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants