8Bi*_*oda 35 typescript fs-extra vite
我正在使用 Vite 和 vanilla-ts 创建一个项目,有一次我必须使用包readdir
中的方法fs-extra
,但它创建了一个错误process is not defined
,有人建议我将此代码放在我的vite-config.ts
文件中:
import { defineConfig } from 'vite'
export default defineConfig({
define: {
'process.env': {}
}
})
Run Code Online (Sandbox Code Playgroud)
这修复了最初的错误,但创建了一个新的错误global is not defined
,其中包含更多研究并添加'global': {}
了define
,就像之前修复了错误但创建了另一个错误一样Cannot read properties of undefined (reading 'substr')
使用的代码:
import { readdirSync } from 'fs-extra';
const folders = readdirSync('./', { withFileTypes: true })
.filter(dir => dir.isDirectory);
Run Code Online (Sandbox Code Playgroud)
投票版本:^2.9.5
FS-Extra版本:^9.0.13
Yai*_*pro 65
问题是因为vite 没有global
像webpack 那样定义字段window
。一些库依赖它,因为 webpack 比 vite 更古老。
只需在导入任何库之前在最开始处插入:
\n// init.js\nwindow.global ||= window;\n
Run Code Online (Sandbox Code Playgroud)\n在任何导入之前拥有上述代码的一个好方法是写入新文件,我们称之为init.js
,然后首先导入它。
// in index.js or main.js file\n\nimport "./init"\n// import your app and libraries after... \nimport App from \'./App\'\nimport ...\n
Run Code Online (Sandbox Code Playgroud)\n\xe2\x9c\x85 一切顺利!
\n关于其他答案说要设置define
Vite 配置
\n\n警告
\n
\n因为它是作为简单的文本替换实现的,而无需\n任何语法分析,所以我们建议仅对常量使用定义。
\n例如,process.env.FOO 和APP_VERSION非常适合。但是\n进程或全局不应放入此选项中。变量可以被填充或填充。
来自Vite官方文档
\nDom*_*ski 25
另一个解决方案:
export default defineConfig({
define: {
global: {},
},
})
Run Code Online (Sandbox Code Playgroud)
但要小心:例如,process.env.FOO 和APP_VERSION就很适合。但进程或全局不应该放入此选项中。变量可以被填充或填充。
来源: https: //vitejs.dev/config/shared-options.html#define
小智 7
天啊,谢谢你,Patrick H\xc3\xbcbl-Neschkudla!
\n\n\n对我有用的是定义全局:\'window\',这样,库\n依赖于global.something起作用(例如lodash使用global.isFinite()\n这引发了错误)\xe2\x80\x93 Patrick H\ xc3\xbcbl-Neschkudla 2022 年 9 月 13 日 at\n8:27
\n
我在这个问题上苦苦挣扎了2个小时,终于从你那里找到了解决方案。
\n对我来说,问题是,AWS Authenticator 需要使用需要在 vite 配置上定义“global”的 Buffer 包,而我还有 Phaser 包,它在其主 Phaser.js 代码中声明了 global.somethingsomething。
\n使用 vite 配置中定义的“global”,编译 Phaser 时运行“npm run build”失败,表示在声明“global: blah blah”的部分存在意外标记。
\n当我不在 vite 配置中定义“global”时,“npm run build”不会失败,但 AWS Authenticator 将无法工作并抛出 console.error,说“global”不是定义在缓冲区中。
\n环境
\ndefine: {global: \'window\'}\n
Run Code Online (Sandbox Code Playgroud)\n在 vite.config 中解决了这个问题。
\n参考https://gist.github.com/FbN/0e651105937c8000f10fefdf9ec9af3d,我意识到:
export default defineConfig({
optimizeDeps: {
esbuildOptions: {
define: {
global: 'globalThis'
}
}
}
})
Run Code Online (Sandbox Code Playgroud)
bas*_*rat -8
您很可能将 Vite 用于前端项目。fs-extra(文件访问)/全局(nodejs 全局)不存在于浏览器(前端)中。
使用后端项目并导出 API,然后您可以从 Vite/前端使用该 API 在服务器上进行文件系统更改。
归档时间: |
|
查看次数: |
46006 次 |
最近记录: |