介绍
Visual Studio Code是一个轻量级的Web集成开发环境on Linux,Mac and Windows,特别是作为前端人员来了,
多了一个可供选择的生产力工具IDE,调试js代码简单方便了很多,笔者搭建Visual Studio Code也碰到了不少坑,特记录下过程;
环境准备:
首先安装nodejs运行环境:
windows下跟mac下安装简单,官网下载安装包安装就可以,linux下ubuntu以及centos都可以用apt等高级命令安装,参见博客 Linux之旅-ubuntu下搭建nodejs环境
安装完成后记得添加环境变量,如我的:
windows下打开powershell或cmd ,输入
node -v
就能查看当前安装的nodejs版本,如提示node 不是内部或外部程序时,记得更改环境变量并重启操作系统;
然后安装nodejs下的http-server
npm install -g http-server
安装成功后输入
http-server
当返回如下页面时表示安装成功,并监听8080端口
打开visual studio code,跟目录下新建app.js(表示项目的启动文件),代码如下
var PORT = 8082; //表示监听端口 var DIR = 'app'; //用于存放html的目录 var http = require('http'); var url=require('url'); var fs=require('fs'); var mine=require('./mine').types; var path=require('path'); var server = http.createServer(function (request, response) { var pathname = url.parse(request.url).pathname; if (pathname.charAt(pathname.length - 1) == "/") { //如果访问目录 pathname += "index.html"; //指定为默认网页 } var realPath = path.join(DIR, pathname); //console.log(realPath); var ext = path.extname(realPath); ext = ext ? ext.slice(1) : 'unkonwer'; fs.exists(realPath, function (exists) { if (!exists) { response.writeHead(404, { 'Content-Type': 'text/plain' }); response.write("This request URL " + pathname + " was not found on this server."); response.end(); } else { fs.readFile(realPath, "binary", function (err, file) { if (err) { response.writeHead(500, { 'Content-Type': 'text/plain' }); response.end(err); } else { var contentType = mine[ext] || "text/plain"; response.writeHead(200, { 'Content-Type': contentType }); response.write(file, "binary"); response.end(); } }); } }); }); server.listen(PORT); console.log("Server runing at port: " + PORT + ".");
创建mime.js文件,表示解析的文件:
exports.types = { "css": "text/css", "gif": "image/gif", "html": "text/html", "ico": "image/x-icon", "jpeg": "image/jpeg", "jpg": "image/jpeg", "js": "text/javascript", "json": "application/json", "pdf": "application/pdf", "png": "image/png", "svg": "image/svg+xml", "swf": "application/x-shockwave-flash", "tiff": "image/tiff", "txt": "text/plain", "wav": "audio/x-wav", "wma": "audio/x-ms-wma", "wmv": "video/x-ms-wmv", "xml": "text/xml" };
新建项目文件夹app(对应app.js里的DIR目录),在该文件夹里编辑对应的html以及js,
然后去visual studio code的debug tab下,配置nodejs环境,点击visual studio code会创建launch.json文件于.vscode下,
完整的目录结构如下:
然后就可以F5调试监听了,是不是感觉特别简单,我也觉得,不得不说microsoft的IDE客户端环境做的确实好,本地化完善,比如宇宙第一IDE visual studio,还有针对小团队或开源项目团队的免费社区版,不过只能用于windows下.....!