简体   繁体   English

__dirname 在带有 webpack 捆绑的节点 js 中不起作用

[英]__dirname is not working in node js with webpack bundling

My current directory is我当前的目录是

D:\bkp\Programming\TestWorks\nodejs\testApp

but when i am using __dirname and trying to show a file with express server it gives me this error但是当我使用__dirname并尝试使用快速服务器显示文件时,它给了我这个错误

Error: ENOENT: no such file or directory, stat 'D:\views\index.html'

my code for that is我的代码是

res.sendFile(__dirname + 'views/index.html');

when i am bundling it with webpack and run the bundle file then this happens.当我将它与 webpack 捆绑并运行捆绑文件时,就会发生这种情况。 Otherwise if i just run the normal app.js file it works fine.否则,如果我只运行普通的 app.js 文件,它就可以正常工作。 Help would be appreciated.帮助将不胜感激。

This is because webpack can handle __dirname (and other node specific things) in different ways.这是因为 webpack 可以以不同的方式处理 __dirname(和其他节点特定的东西)。 If you want it to behave like normal, use this in your webpack config:如果您希望它像正常一样运行,请在您的 webpack 配置中使用它:

{
    node: {
        __dirname: false
    }
}

See: https://webpack.js.org/configuration/node/请参阅: https : //webpack.js.org/configuration/node/

The __dirname is set to / by webpack, that's why you end up with /views/index.html which is the root of your file system, that happens to be D:\\ in your case. __dirname__dirname设置为/ ,这就是为什么你最终得到/views/index.html这是你的文件系统的根目录,在你的情况下恰好是D:\\ You can set node.dirname to false in your webpack config to not inject it and defer it to runtime.您可以在 webpack 配置中将node.dirname设置为false以不注入它并将其推迟到运行时。 Keep in mind that __dirname will refer to the location of the script you're executing, that means the location of the bundle, not the original source.请记住, __dirname将引用您正在执行的脚本的位置,这意味着包的位置,而不是原始源。

node: {
  __dirname: false
}

"webpack": "^5.24.4" the default value depends on the target configuration property: "webpack": "^5.24.4"默认值取决于target配置属性:

target: 'web' => __dirname = '/' target: 'web' => __dirname = '/'

target: 'node' => __dirname = 'the full path of the output directory' target: 'node' => __dirname = 'the full path of the output directory'

It can be adjusted using node configuration property, see https://webpack.js.org/configuration/node/#node__dirname可以使用node配置属性进行调整,参见https://webpack.js.org/configuration/node/#node__dirname

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM