> Hello World !!!

     

@syaku

Gruntjs html include - 파일 삽입하기 : Front-end Build System

Gruntjs html include - 파일 삽입하기 : Front-end Build System

html 에는 include와 같은 편리한 기능이 없다. 그래서 모든 페이지에 동일한 코드를 입력할 수 밖에 없는 다. 이런 불편한 부분을 grunt 를 이용하여 공통적인 (header, footer) 소스를 자동으로 삽입될수 있게 빌딩시스템을 구성하였다.

소스 파일 본문에 include 키워드가 있으면 호출 대상 파일을 읽어 내용을 include 키워드와 치환하여 최종 파일을 만드는 작업이다. 또한 watch 를 이용하여 소스파일이 변경될 경우 자동으로 빌드되면서 브라우저 페이지를 자동으로 새로고침하는 작업도 포함하고 있다.

소스를 삽입하는 방식은 두가지로 나뉠수 있는 데.

하나는 위와 같이 모든 소스 파일이 공통적인 소스를 불러와 삽입되는 경우고 또 하나는 특정 템플릿(공통소스)이 한개 있으면 모든 소스 파일이 해당 템플릿 속에 삽입되어 각 소스 파일이 생성되는 경우인데 이번 작업은 첫번째에 해당하는 작업이다.



결과물

source.html

<!-- #include header.html -->
good

header.html

header

result

header
good

Install

npm install-D  grunt-contrib-watch grut-contrib-connect grunt-replace

grunt-replace 이용하여 소스 파일의 include 키워드를 찾고 grunt.file.read 를 이용하여 파일 내용을 읽을 것이다.

Setting

</> 파일구조

/dist
/src
    /apps
        /todayNotify
            index.html
    /include
        header.html
Gruntfile.js
package.js

</> index.html

<!DOCTYPE html>
<html lang="ko">
  <head>
    <title></title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
  </head>
  <body>
     <!-- 헤더 파일을 호출한다.-->
    <!-- #include ##includePath/header.html -->
  </body>
</html>

grunt-replace 에서 내장된 변수를 이용하여 현재 작업되고 있는 경로 정보를 얻을 수 있다.

https://github.com/outaTiME/grunt-replace

__SOURCE_FILE__:

Replace match with the source file.

__SOURCE_PATH__:

Replace match with the path of source file.

__SOURCE_FILENAME__:

Replace match with the filename of source file.

__TARGET_FILE__:

Replace match with the target file.

__TARGET_PATH__:

Replace match with the path of target file.

__TARGET_FILENAME__:

Replace match with the filename of target file.

</> Gruntfile.js

module.exports = function (grunt) {
  grunt.initConfig({
    replace: {
      html: {
        options: {
            prefix: '##', // 변수 사용시 키워드
            
            // 자주 사용되는 값을 변수에 담는 다.
          variables: {
            'includePath': path.join(__dirname, 'src/apps/include')
          },
          patterns: [
            {
              match: /<!-- #include (.*) -->/ig, // <!-- #include 어떠한문자든허용 --> 인 키워드를 찾는 다.
              replacement: function (found) {
                var filename = found.replace(/<!-- #include (.*) -->/ig, '$1') // include 대상 파일명을 얻는 다.
                if (grunt.file.exists(filename)) {
                  return grunt.file.read(filename)
                }
                console.log('file not found. (' + filename + ')')
                return '<!-- file not found. (' + filename + ') -->'
              }
            }
          ]
        },
        files: [
          {
            expand: true,
            cwd: 'src/',
            src: ['**/*.index.html'],
            dest: 'dist/'
          }
        ]
      }
    },

    watch: {
        // dist 파일이 변경되면 리로드를 호출한다.
      server: {
        files: 'dist/**/*',
        options: {
          livereload: true
        }
      },
      // src 하위 폴더의 html 파일이 변경되는 replace:html 작업을 수행한다.
      html: {
        files: 'src/**/*.html',
        tasks: [ 'replace:html' ]
      }
    },

    connect: {
      server: {
        options: {
          livereload: true,
          base: 'dist',
          port: 9009
        }
      }
    }
  })

  grunt.loadNpmTasks('grunt-contrib-watch')
  grunt.loadNpmTasks('grunt-contrib-connect')
  grunt.loadNpmTasks('grunt-replace')
  grunt.registerTask('default', ['connect:server', 'watch'])
}

replace 설정에서 키워드를 주석으로 사용한 이유는 소스 파일을 브라우저에서 노출되지 않게 하기 위함이다.

그리고 files 라는 설정이 있는 데 이것은 grunt 공통된 설정이라 잘 익혀둬야 한다.

참고: http://gruntjs.com/configuring-tasks

files: [
  {
    expand: false,
    src: ['src/**/*.index.html'],
    dest: 'dist/'
  }
]

// 빌드후 생성된 파일 결과
./dist/src/apps/todayNotify/index.html 

expand 을 사용하지 않을 경우 소스 파일 경로를 그대로 유지한다.

files: [
  {
    expand: true,
    src: ['src/**/*.index.html'],
    dest: 'dist/'
  }
]

// 빌드후 생성된 파일 결과
./dist/index.html 

expand 을 사용한 경우 dest 설정된 경로에 복사된다.

files: [
  {
    expand: true,
    cwd: 'src/',
    src: ['**/*.index.html'],
    dest: 'dist/'
  }
]

// 빌드후 생성된 파일 결과
./dist/apps/todayNotify/index.html

expand 사용하고 cwd 를 설정하였다. cwd 는 사용하면 빌드될때 아래와 같이 사용된다.

src -> cwd + src
dset -> dest + src

상황에 맞게 설정을 사용하면 된다.

keyword

Front-end build-system gruntjs grunt livereload html include grunt-contrib-watch grunt-contrib-connect



posted syaku blog

Syaku Blog by Seok Kyun. Choi. 최석균.

http://syaku.tistory.com