Error Dynamic require of "fs" is not supported
# 报错代码
const fs = require('fs');
const path = require('path'); // 路径模块
const matter = require('gray-matter');
const chalk = require('chalk')
const log = console.log
function readFileList(excludeFiles = [''], dir = docsRoot, filesList = []) {
const files = fs.readdirSync(dir);
files.forEach((item, index) => {
let filePath = path.join(dir, item);
const stat = fs.statSync(filePath);
if (!(excludeFiles instanceof Array)) {
log(chalk.yellow(`error: 传入的参数不是一个数组。`))
}
// ...以下代码省略
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 报错提示
Error: Dynamic require of "fs" is not supported
1
# 解决办法
require引入改为 import...from...
# 原因
require/exports 是运行时动态加载,import/export 是静态编译
require/exports 输出的是一个值的拷贝,import/export 模块输出的是值的引用
CommonJS 加载的是一个对象(即 module.exports 属性),该对象只有在脚本运行完才会生成。而 ES6 模块不是对象,它的对外接口只是一种静态定义,在代码静态解析阶段就会生成。- 阮一峰
上次更新: 2022/05/12 14:57:53