web-infra-dev / rsbuild

The Rspack-based build tool. It's fast, out-of-the-box and extensible.
https://rsbuild.dev/
MIT License
1.57k stars 123 forks source link

[Bug]: require.context issue #3486

Open yc0123450 opened 4 weeks ago

yc0123450 commented 4 weeks ago

Version

System:
    OS: Windows 11 10.0.22631
    CPU: (18) x64 Intel(R) Core(TM) Ultra 5 125H
    Memory: 7.73 GB / 23.47 GB
  Browsers:
    Edge: Chromium (127.0.2651.74)
    Internet Explorer: 11.0.22621.3527
  npmPackages:
    @rsbuild/core: ^1.0.4 => 1.0.4
    @rsbuild/plugin-sass: ^1.0.1 => 1.0.1
    @rsbuild/plugin-vue2: ^1.0.1 => 1.0.1

Details

我的项目中使用了require.context动态加载一些模块,然后默认导出给别的地方引用使用,本地运行没有问题,打包上线后报错如下图。就算改成使用import.meta.webpackContext也一样报错。动态加载的文件都会默认导出一个类似xxxModel对象,然后动态加载后全部导出,在其他地方引入对应xxxModel使用。 企业微信截图_17263149866851


// src\models\index.js

const files = require.context('./modules', false, /\.js$/)

const modules = files.keys().reduce((modules, path) => {
    const value = files(path)?.default
    const name = path.replace(/^\.\/(.*)\.\w+$/, '$1')
    const clazz = value.name
    if (modules[clazz] === undefined) {
        modules[clazz] = value
    } else {
        console.error(`Model 模块类名: ${clazz} 已在 ${name} 文件中存在`)
    }
    return modules
}, {})
module.exports = modules

// 使用方式
import { xxxModel } from '@/models'

Reproduce link

https://gitee.com/ychaoweb/test-demo

Reproduce Steps

npm i yarn -g

yarn

yarn build

yarn preview 使用yarn进行的包管理,打包后预览就能看到报错了

github-actions[bot] commented 4 weeks ago

Hello @yc0123450. Please provide a reproduction repository or online demo. For background, see Why reproductions are required. Thanks ❤️

yc0123450 commented 3 weeks ago

@chenjiahan 已经补充仓库demo地址,因为项目比较复杂,精简后没有本地运行测试,只是测试了打包后用yarn preview进行预览,控制台就能看到报错内容,打包预计2分钟。完整项目就和我描述的一样,本地运行正常,就是打包后报错。

9aoy commented 3 weeks ago

This error is caused by the class name being compressed, To solve this problem you can set mangle.keep_fnames false.

(Why not keep_classnames? Because according to the browserslist you configured, class was converted into function during swc transform.)

    output: {
        minify: {
            jsOptions: {
                minimizerOptions: {
                    mangle: {
                        keep_fnames: true
                    }
                }
            }
        },
    },

source code:

class VectorLineModel {
    constructor() {
      console.log('init VectorLineModel')
    }
    getHighwayCodeList() {
        console.log('VectorLineModel')
    }
}

export default VectorLineModel

transformed: img_v3_02er_c787ed6b-fbc8-4949-950a-ddcc7ec4d7cg

compressed: img_v3_02er_9d112c86-f5f0-46b4-af8b-9582719b8b2g

yc0123450 commented 3 weeks ago

@9aoy thanks,set mangle.keep_fnames is true,Can solve my problem。It's just that the packaging volume has increased by 100+kb, but it doesn't affect its use。