我正在尝试读取目录中的文件,但无法读取,因为__dirname是未定义的。
nuxt.config.js
export default {
router: {
middleware: ['database']
},
build: {
extend: function (config, __ctx) {
config.node = {
fs: "empty",
module: "empty",
net: "empty",
};
},
},
}如何确定__dirname?
发布于 2019-11-21 08:50:34
据我所知,Webpack总是将__dirname设置为'/‘。但可能不在服务器端。也许这个引用将帮助您解决问题:https://codeburst.io/use-webpack-with-dirname-correctly-4cad3b265a92
您并没有说出您想要完成的任务,但是我将为最常见的问题之一写下一个解决方案,这通常会导致人们尝试使用__dirname常量。也许它也会对你有帮助;)
每当我试图在Nuxt中使用__dirname时,这都是因为我必须为服务器端进程中缺少的require.context功能找到解决办法。使用require和__dirname解决一些问题通常会引起更多的问题。如果在Nuxt服务器端进程中与缺少的require.context做斗争,最好的解决方案是使用插件。它们可以使用require.context函数,在服务器端和客户端都可以使用。
总的来说,我认为您应该尝试使用webpack的上下文功能查找您的文件,并避免使用__dirname。
const files = require.context('~/', true, /\/your-file-name\/.*\.ts$/)
files.keys().map(key => {
// This is an example how to access your file's default export.
// You will probably have to amend it to make any use of it ;)
const file = files(key).default
})https://stackoverflow.com/questions/58141169
复制相似问题