Visual Studio代码 – Node.js – 找不到名字'__dirname'

只是为了说明,我不是一个专业的编码员,但是当我发现10年前我在高中就读了“网页devise”之后,我就一直为我的老板build立一个网站。 那时静态网站很好,而且CSS刚刚开始显示它的潜力,但我离题了。

我正在使用Visual Studio Code的Node.js项目,并有一个奇怪的例外。 代码工作正常,但我想这只是好奇心。 无论如何,这是我的代码。

app.js

var express = require('express'), app = express(), bodyParser = require('body-parser'), multer = require('multer'), controller = require('./controllers'); //Sets the view engine to jade. app.set('views', __dirname + '/frontend'); app.set('view engine', 'jade'); //sets up the development enviroment if (app.get('env') === 'development') { app.locals.pretty = true; app.use(express.static(__dirname + '/build/public')) var build = require(__dirname + '/build.js'); app.use('css/*', function(req, res, next){ build.style(); next(); }); } //Sets up the public directory to serve static files - This will be depricated quite soon... //app.use(express.static(__dirname + '/public')); //Initalizes site-wide local variables //app.set('title', 'Halvorson Homes'); //Sets up body-parser to be able to read RESTful requests app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: true})); app.use(multer({dest: 'tmp'}).fields()); //Load Controllers app.use( '/' , controller); //makes the app listen on port 3000 app.listen(3000, function() { console.log('Listening on port 3000...'); }) 

我的文件夹结构大致如下

  • 控制器
    • index.js
    • designs.js
  • 楷模
    • designs.js
  • 前端
    • 共同
      • layout.jade
      • header.jade
      • footer.jade
      • client.js
      • style.less
    • 指数
      • index.jade
      • client.js
      • style.less
    • devise
      • index.jade
      • client.js
      • style.less
  • build立
    • TMP
    • SRV
  • app.js
  • build.js
  • 的package.json

根据VS Code的内置debugging器,第8,14和15行有例外。他们是我在整个项目中唯一使用__dirname的地方。 这对我来说很烦人,因为我太完美了。 是节点,VS代码还是其他的?

你得到的警告是从eslint扩展 。 虽然它在Node.JS中可能有效,但它会警告你关于__dirname因为它在所有JavaScript环境(如浏览器)中都是无效的。

要压制这个警告,你需要直接在你的项目的根目录下创build一个.eslintrc文件,并且指出这个代码将会像下面这样在节点上运行:

 { "env": { "node": true } } 

你可以在.eslint看到.eslint文件用来configurationeslint的实际vscode代码库https://github.com/Microsoft/vscode/blob/master/.eslintrc

晚会到了,但刚刚有同样的问题。 对我来说,修补程序是添加节点types,以便VSCode识别它们:

转到terminal视图,然后input以下内容: npm install @types/node --save-dev

然后点击Cmd + Shift + P (至less对于Mac)来调出VSCode命令search对话框,然后selectReload Window

当它重新出现的时候,这个错误和任何其他与Node.JS东西无关的东西都应该被删除。