Node + Express, 랑겔한스님 grunt 사용 방법입니다. 참고 하세요
강의 잼있게 보고 있습니다. 시간이 맞지 않아서 재방송으로 보고 있습니다. 이번에 하실때 서버 재업할때 grunt를 사용하시면 편하실것 같아서 grunt사용 방법 간단히 올립니다.
grunt를 command line에서 사용하기 위해 grunt command line tool을 설치 해줍니다.
npm install -g grunt-cli
설치가 끝난후 grunt를 해당 로컬 디렉토리에 설치 해줍니다.
npm install grunt
grunt를 로컬에 설치를 해주시고
grunt
fatal error: Unable to find Gruntfile
Gruntfile이 없다는 애러 메세지를 확인 할 수 있습니다.
Gruntfile.js 파일을 만들어 주시고 아래의 코드를 적습니다..
module.exports = function(grunt) {
grunt.registerTask("default", function(){
grunt.log.writeln("Hello World");
})
}
Command line 에서 grunt를 실행하시면
grunt
Running "default" task
Hello World
Done, without errors.
아래와 같은 결과를 얻을 수 있습니다.
Gruntfile.js를 아래와 같이 수정을 합니다.
module.exports = function(grunt) {
grunt.initConfig({
person:{
firstName: "Kevin"
}
})
grunt.registerTask("default", function(name){
grunt.log.writeln("Hello " + grunt.config.get("person").firstName);
})
}
grunt를 다시 실행을 해주시면
grunt
Running "default" task
Hello Kevin
Done, without errors.
위와 같은 결과 값을 보시게 됩니다.
initConfig은 실행되어질 Task들의 Configuration을 정해주는 역활을 합니다.
configuration은 json 형태의 파일로도 따로 만드셔서 읽어 들일수 있습니다.
Gruntfile.js파일을 아래와 같이 수정 합니다.
module.exports = function(grunt) {
grunt.initConfig(grunt.file.readJSON("config.json"))
grunt.registerTask("default", function(name){
grunt.log.writeln("Hello " + grunt.config.get("person").firstName);
})
}
config.json파일을 새로 만드시고 아래와 같이 입력 합니다.
{
"person": {
"firstName":"Kevin"
}
}
그리고 command line에서 grunt를 실행 해주시면
grunt
Running "default" task
Hello Kevin
Done, without errors.
위와 같은 결과 값을 확인 하실수 있습니다.
Part 2. Grunt Watch
npm install grunt-contrib-watch --save를 설치 하여 watch기능을 쓸 수 있도록 합니다.
Gruntfile.js 파일을 아래와 같이 수정 합니다.
module.exports = function(grunt){
// watch기능을 사용하시기 전에 grunt-contrib-watch 모듈을 로드 해주셔야 합니다.
grunt.loadNpmTasks("grunt-contrib-watch");
grunt.registerTask("pat", function(){
grunt.log.writeln("Keep going, you are great!");
})
}
그리고 command line에서 grunt watch를 실행 시켜 줍니다.
grunt watch
Running "watch" task
Waiting...
Verifying property watch exists in config...ERROR
>> Unable to process task.
Warning: Required config property "watch" missing.
Running "watch" task
Waiting...
Verifying property watch exists in config...ERROR
>> Unable to process task.
Warning: Required config property "watch" missing.
와 같은 애러 메세지가 무한 반복으로 나오는것을 확인 하실수 있으 실겁니다.
Cntr + c 로 머추십니다.
위와 같은 애러가 나오는 이유는 grunt가 watch 할 부분을 찾을 수가 없기 때문에 계속 찾을려고 하기때문에 이와 같은 애러가 뜹니다.
Gruntfile.js 파일을 아래와 같이 수정 합니다. 그리고 watch 할 journal.txt파일을 새로 만들어 줍니다.
module.exports = function(grunt){
grunt.initConfig({
watch:{
files:["journal.txt"],
tasks:["pat"]
}
})
// watch기능을 사용하시기 전에 grunt-contrib-watch 모듈을 로드 해주셔야 합니다.
grunt.loadNpmTasks("grunt-contrib-watch");
grunt.registerTask("pat", function(){
grunt.log.writeln("Keep going, you are great!");
})
}
command line에서 grunt watch를 실행 시켜 줍니다.
grunt watch
Running "watch" task
Waiting...
위와 같은 화면을 보시게 될 것입니다. grunt가 journal.txt 파일이 수정되는지 여부를 계속 주시 하고 있다는 말입니다.
journal.txt 파일을 수정해 봅니다. 수정을 하신뒤 파일을 save 합니다.
Running "watch" task
Waiting...
>> File "journal.txt" changed.
Running "pat" task
Keep going, you are great!
Done, without errors.
Completed in 0.466s at Tue Jul 07 2015 23:06:40 GMT-0500 (CDT) - Waiting...
위와 같은 결과 물을 보시게 될 것이고 grunt는 계속 켜져 있을 것입니다. journal.txt파일이 수정 될때 마다 위와 같은 메세지를 계속 보여 줄 것 입니다.
Part 3
그럼 실제로 express와 nodejs 서버를 grunt에 적용 해보겠습니다.
먼저 express를 로컬에 설치를 해주십니다.
npm install express --save
(grunt-contrib-watch 와 grunt 는 로컬에 설치가 되있어야 하고 grunt-cil는 global에 설치가 되어 있어야 합니다.)
server.js 파일을 만들어 주시고 아래와 같이 코드를 적습니다.
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res) {
res.sendfile('./index.html');
});
app.listen(8080);
console.log('Magic happens on 8080');
그리고 command line에서 서버를 실행시킵니다.
node server
Magic happens on 8080
위와 같은 결과를 확인 하실수 있습니다.
public 디렉토리를 만드신후 index.html 파일을 public 폴더 안에 새롭게 만드십니다. 코드는 아래와 같이 수정 합니다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1> Hello World</h1>
</body>
</html>
브라우저에서 localhost:8080을 확인 하시면 hello world를 확인 하실수 있으십니다.
grunt-nodemon을 설치 합니다.
npm install grunt-nodemon --save
Gruntfile.js를 아래와 같이 수정 합니다.
그리고 grunt를 command line에서 실행 시켜 줍니다.
grunt
Running "nodemon:dev" (nodemon) task
[nodemon] v1.3.7
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node server.js`
Magic happens on 8080
server.js를 수정 합니다.
[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
Server on 8080
grunt를 실행시킨 터미널을 보시면 위와 같이 server.js파일에 수정이 일어나서 서버를 다시 실행 시키는 것을 확인 하실수 있습니다.
두개 이상의 task를 같은 시간에 실행 시키기 위해서 grunt-concurrent를 설치해 줍니다.
npm install grunt-concurrent --save
그리고 public 디렉토리 안에 js 디렉토리를 만듭니다. 그리고 test.js 파일을 새로 만드십니다. 이번에 할 일은
public/js/안에 있는 모든 자바스크립트들을 watch 하고 server.js또한 변화가 있는지 계속 watch 하고 이들중에 변화가 있다면 server.js를 grunt가 자동으로 서버를 껏다가 켜줄 것입니다.
Gruntfile.js를 아래와 같이 수정 합니다
module.exports = function(grunt) {
grunt.initConfig({
// configure nodemon
nodemon: {
dev: {
script: 'server.js'
}
},
watch: {
js: {
files: ['public/js/**/*.js'],
}
},
concurrent: {
options: {
logConcurrentOutput: true
},
tasks: ['nodemon', 'watch']
}
});
// load nodemon
grunt.loadNpmTasks('grunt-nodemon');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-concurrent');
// register the nodemon task when we run grunt
grunt.registerTask('default', ['concurrent']);
};
command line에서 grunt를 실행 합니다.
grunt
Running "concurrent:tasks" (concurrent) task
Running "watch" task
Waiting...
Running "nodemon:dev" (nodemon) task
[nodemon] v1.3.7
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node server.js`
Server on 8080
위와 같이 grunt를 실행 시키면 서버도 같이 시작 됩니다.
public/js/test.js파일을 수정 하겠습니다.
console.log("hello world !");
아무 소스코드를 적으시고 저장 합니다. 그리고 grunt가 실행되어있는 터미널을 확인 하시면 아래와 같이 수정되었음을 알리고 서버를 다시 시작 합니다.
[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
Server on 8080
>> File "public/js/test.js" changed.
소스파일을 함께 올립니다.
https://drive.google.com/file/d/0B8FisuvAYPTfMWY4QldtcGZJMFE/view?usp=sharing
소스파일 압축을 푸시고
grunt-cil는 꼭 global에 설치를 하신뒤 (npm install grunt-cli -g)
npm install으로 package.json에 정의된 라이브러리 설치 하시고
grunt (command line에서)를 실행 하시면 됩니다.
더운데 모두들 새로운것을 배우시느라 수고가 많으 십니다. grunt 사용방법이 node + express강의에 조금 이나마 도움이 되었으면 합니다.