next.config.js에서 변경 사항을 찾았습니다. 서버를 다시 시작하여 변경 사항이 적용되는지 확인하십시오.

8251 단어 nextjsnodewebdevreact
훨씬 더 나은 경험을 위해 original blog에서 이것을 읽으십시오.

event - compiled successfully in 9.2s (227 modules)
wait  - compiling /...
event - compiled successfully in 782 ms (307 modules)

> Found a change in next.config.js. Restart the server to see the changes in effect.


낯익은? next.js 개발자라면 next.config.js 변경 시 터미널에서 이 메시지를 접했을 가능성이 큽니다.

그렇다면 이 블로그 포스트는 무엇입니까?

나는 내가 탐험을 시작하기 위해 방금 Next.js source code에 뛰어들어 구현을 보았다는 것을 next.js가 어떻게 알 수 있는지 궁금했습니다.

구현은 매우 간단합니다. 비슷한 것을 빌드해 보겠습니다. 디렉토리 내부에 next.config.jswatch.js를 생성하는 것으로 시작하겠습니다.

Next.js는 watchFile 을 사용하여 파일 변경 사항을 수신하며 fs.watchFile의 인터페이스는 다음과 같습니다.

fs.watchFile(filename[, options], listener)

Watches for changes on filename. The callback listener will be called each time the file is accessed. The listener gets two arguments the current stat object and the previous stat, these are of the type Stats
fs.Stats object provides information about a file. You can refer to the entire interface here. We will be using the size property which returns the size of the file in bytes helping us to identify if the file was modified or not.



더미 구성 파일을 생성해 보겠습니다.

const config = {
  name: 'Deepankar',
  age: 20,
};


그런 다음 크기 통계를 기반으로 리스너 함수를 호출하는 감시자 구현입니다. 0보다 큰 검사는 파일이 삭제되지 않았는지 확인합니다.

const { watchFile } = require('fs');
const configFile = `next.config.js`;

watchFile(`${process.cwd()}/${configFile}`, (cur, prev) => {
  if (cur.size > 0 || prev.size > 0) {
    console.log(
      `\n> Found a change in ${configFile}. Restart the server to see the changes in effect.`
    );
  }
});


이제 실행node watch.js하고 파일을 수정하고 짜잔!



그래서 예, 그것은 매우 간단했지만 일이 뒤에서 어떻게 작동하는지 이해하는 것을 좋아합니다. next.js source code 의 그 부분입니다.

if (command === 'dev') {
  const { CONFIG_FILES } = require('../shared/lib/constants')
  const { watchFile } = require('fs')

  for (const CONFIG_FILE of CONFIG_FILES) {
    watchFile(`${process.cwd()}/${CONFIG_FILE}`, (cur: any, prev: any) => {
      if (cur.size > 0 || prev.size > 0) {
        console.log(
          `\n> Found a change in ${CONFIG_FILE}. Restart the server to see the changes in effect.`
        )
      }
    })
  }
}


Next.js는 ES6/CJS 풍미를 사용하는지 여부에 따라 기본적으로 CONFIG_FILES['next.config.js', 'next.config.mjs']를 반복합니다. 나머지 코드는 정확히 우리가 한 방식입니다.

그게 다야! 내가 이 블로그를 쓰는 것을 좋아했던 만큼 여러분도 이 블로그를 흥미롭게 보셨기를 바랍니다. 이러한 "Next.js 심층 분석"블로그가 곧 추가될 예정이므로 계속 지켜봐 주시고 업데이트를 위해 저를 팔로우하세요.

좋은 웹페이지 즐겨찾기