RSA加密,在create-react-app创建的项目下出现的bug解决.

469 阅读1分钟

前言:RSA 加密,前端引入包插件包 JSEncrypt ,但是在react项目下,有时候会出现异常..react默认的配置问题. 此文不讲解完整的webpack配置修改/合并教程,文章网上很多的.现在比较推荐使用【craco】进行webpack配置的修改.

craco配置文档地址:craco.js.org/docs/config…

1.bug异常复现

image.png

//控制台打印信息
Failed to compile.

Module not found: Error: Can't resolve './JSEncrypt' in 'D:\_ReactProject\消防2\node_modules\jsencrypt\lib'
Did you mean 'JSEncrypt.js'?
BREAKING CHANGE: The request './JSEncrypt' failed to resolve only because it was resolved as fully specified
(probably because the origin is strict EcmaScript Module, e. g. a module with javascript mimetype, a '*.mjs' file, or a '*.js' file where the package.json contains '"type": "module"').
The extension in the request is mandatory for it to be fully specified.
Add the extension to the request.
ERROR in ./node_modules/jsencrypt/lib/index.js 1:0-40
Module not found: Error: Can't resolve './JSEncrypt' in 'D:\_ReactProject\消防2\node_modules\jsencrypt\lib'
Did you mean 'JSEncrypt.js'?
BREAKING CHANGE: The request './JSEncrypt' failed to resolve only because it was resolved as fully specified
(probably because the origin is strict EcmaScript Module, e. g. a module with javascript mimetype, a '*.mjs' file, or a '*.js' file where the package.json contains '"type": "module"').
The extension in the request is mandatory for it to be fully specified.
Add the extension to the request.

异常的关键点在于.无法读取路径为 ./JSEncrypt 的文件.

2.解决异常

在craco.config.js中进行配置.

image.png

//craco.config.js
const path = require("path")
// 循环引用检测插件,但当前未使用它
// const CircularDependencyPlugin = require('circular-dependency-plugin');
module.exports = {
  webpack: {
      //...其它无关本bug的配置
      module: {
        rules: [
          //核心配置
          {
            test: /\.(t|j|mj)s$/,
            include: path.resolve(
              __dirname,
              './node_modules/jsencrypt'
            ),
            resolve: {
              fullySpecified: false,
            },
          }
        ]
      }
    //...其它无关本bug的配置
    },
  },
};

说明:该配置的意义在于,单独为'./node_modules/jsencrypt'【文件夹】配置上路径解析方式,让它在解析.ts .js .mjs文件时,不需要写完整的路径名,会自动尝试为文件增加后缀查找.

  • 完 -