nodejs 서버에 라이브 새로고침을 추가하려면 어떻게 해야 합니까?
이것이 서버 nodej를 실행하는 방법입니다.프런트 엔드 개발에서 코드를 변경할 때 서버를 라이브 새로고침해야 합니다.
"start": "node server.js"
첫 번째:
npm install -g nodemon
다음으로 스크립트 행을 패키지에 추가합니다.json
"live": "nodemon server.js"
이제 npm 라이브는 라이브 새로고침이 됩니다.
자세한 것은, https://github.com/remy/nodemon 를 참조해 주세요.
라이브 페이지 새로고침도 필요한 경우 업데이트
npm install -g livereload
livereload . -w 1000 -d
자세한 것은, https://github.com/napcs/node-livereload 를 참조해 주세요.
서버 재부팅과 브라우저 업데이트는 별개입니다.서버 감시에는 노데몬을 사용합니다.Nodemon은 모든 유형의 파일에서 변경 사항이 발생할 때 확인할 수 있습니다.그러나 nodemon은 브라우저 페이지를 새로 고칠 수 없습니다.이를 위해 브라우저 동기화를 사용합니다.
저는 둘 다 꿀꺽꿀꺽 써요.
패키지의 의존성입니다.동작시키기 위한 json:
"devDependencies": {
"browser-sync": "^2.24.5",
"gulp": "^3.9.1",
"gulp-nodemon": "^2.2.1"
}
서버 파일(내 서버는 ./bin/www, 내 서버는 server.js, app.js 또는 다른 곳에 있을 수 있음)에서 express 서버는 포트 3001을 수신합니다.
var port = normalizePort(process.env.PORT || '3001');
var server = http.createServer(app);
server.listen(port);
다음은 노데몬과 브라우저 동기화를 한 번에 실행하는 것입니다.gulpfile.js의 전체 내용
var gulp = require('gulp');
var nodemon = require('gulp-nodemon');
var browserSync = require('browser-sync').create();
gulp.task('gulp_nodemon', function() {
nodemon({
script: './bin/www', //this is where my express server is
ext: 'js html css', //nodemon watches *.js, *.html and *.css files
env: { 'NODE_ENV': 'development' }
});
});
gulp.task('sync', function() {
browserSync.init({
port: 3002, //this can be any port, it will show our app
proxy: 'http://localhost:3001/', //this is the port where express server works
ui: { port: 3003 }, //UI, can be any port
reloadDelay: 1000 //Important, otherwise syncing will not work
});
gulp.watch(['./**/*.js', './**/*.html', './**/*.css']).on("change", browserSync.reload);
});
gulp.task('default', ['gulp_nodemon', 'sync']);
터미널에서 gulp을 실행하면 서버 감시를 시작하고 파일 변경 시 브라우저를 새로 고칩니다.
express 서버에서 포트 3001을 지정하지만 브라우저 동기화로 쓰기 때문에 앱은 포트 3002에서 작동합니다. 3001이 프록시로 사용됩니다.
전면 및 백엔드의 변경 내용은 'livereload', 'connect-livereload' 및 'nodemon' 패키지로 브라우저에 라이브 새로고침할 수 있습니다.이렇게 하면 굴프가 필요 없어요.패키지의 조합 방법은 다음과 같습니다.
livereload
는 높은 합니다.connect-livereload
는 이 포트 몽키에 하여 모든 에 패치를 합니다.nodemon
backend
Express에서 라이브 새로고침 설정
하고 있는 해, 「Express」의 사이에 합니다.nodemon
- - "재시작":
const livereload = require("livereload");
const connectLivereload = require("connect-livereload");
// open livereload high port and start to watch public directory for changes
const liveReloadServer = livereload.createServer();
liveReloadServer.watch(path.join(__dirname, 'public'));
// ping browser on Express boot, once browser has reconnected and handshaken
liveReloadServer.server.once("connection", () => {
setTimeout(() => {
liveReloadServer.refresh("/");
}, 100);
});
const app = express();
// monkey patch every served HTML so they know of changes
app.use(connectLivereload());
노데몬으로 익스프레스 시작
전용 「nodeemon」을합니다.npm run watch
여기서 중요한 것은 라이브 새로고침으로 이미 감시되고 있는 퍼블릭디렉토리를 무시하는 것입니다.퍼그나 콧수염과 같이 기본 확장자가 아닌 파일을 감시하도록 구성할 수도 있습니다.
"scripts": {
"start": "node ./bin/www",
"watch": "nodemon --ext js,pug --ignore public"
},
자세한 설명은 "Express, LiveReload 및 Nodemon을 사용하여 브라우저 전면 및 백엔드 변경 새로 고침"을 참조하십시오.
npm install browser-refresh -g
메인 js를 추가합니다.
if (process.send) {
process.send('online');
}
예를들면
app.listen(port, function() {
console.log('Listening on port %d', port);
if (process.send) {
process.send('online');
}
});
본문 닫기 태그 전에 인덱스 페이지를 추가합니다.
<script src="{process.env.BROWSER_REFRESH_URL}"></script>
노드 서버 대신 터미널 서버에서 서버를 시작합니다.
browser-refresh server.js
설정 예:
livereload.dload (이것이 당신의 서버입니다.dload는 물론 라이브 새로고침과 관련된 부분만 사용하므로 개발 서버를 교체할 필요가 없습니다.)
const path = require('path');
const fs = require('fs');
const livereload = require('livereload');
const lrserver = livereload.createServer();
const compiled = path.join( __dirname, "dist");
lrserver.watch( compiled );
const connect = require('connect');
const stat = require('serve-static');
const server = connect();
server.use( stat( compiled ));
server.listen( 3033 );
console.log( 'Dev server on localhost:3033' );
상에서2개의 on the localhost "2" " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " ":35729
가 「」에 .:3033
.
는 ""를 합니다.dist
디렉토리에는 컴파일된 파일(http, css, html)이 격납되어 있습니다.새로고침해야 하는 모든 HTML 페이지에 이 스니펫을 추가해야 합니다.
<script>
document.write('<script src="http://' + (location.host || 'localhost').split(':')[0] +
':35729/livereload.js?snipver=1"></' + 'script>');
</script>
js/css/html 코드를 transfile/compile/preprocess하지 않는 경우(즉, 제공되는 파일을 직접 편집하는 경우) 소스 디렉토리를 관찰하면 완료됩니다.그렇지 않으면 소스 디렉토리의 변경을 감시하고 라이브 새로고침에 의해 감시되는 dist 디렉토리로 컴파일하는 태스크가 필요합니다.
내 소포의 관련 부품들.json:
"scripts": {
"build": "npm run build:js && npm run build:css",
"prewatch": "node livereload.js &",
"watch": "node ./node_modules/watch-run/bin/watch -p './src/**' npm run build",
},
"devDependencies": {
"connect": "^3.6.2",
"livereload": "^0.6.2",
"serve-static": "^1.12.3",
"watch-run": "^1.2.5"
}
$ npm run watch
the) + (더)build:*
★★★★★★★★★★★★★★★★」
라이브 새로고침이라는npm 패키지를 사용합니다.
클라이언트 측과 서버 측 모두 완벽하게 작동하도록 노드몬과 함께 사용합니다.
npm install livereload nodemon --save
--save-dev.알아, 알아!
브라우저 확장을 추가합니다.Safari, Firefox 및 Google Chrome에서 사용할 수 있습니다.여기로 데려와.
「」에 .package.json
.
"scripts": {
"start": "nodemon server.js && livereload"
}
server.js
문입입입니다
<고객명>server.js
다음을 추가합니다.
const livereload = require('livereload');
const reload = livereload.createServer();
reload.watch(__dirname + "/server.js");
server.js
라이브 새로고침으로 보고 싶은 파일입니다.파일 대신 임의의 디렉토리를 추가할 수도 있습니다.
reload.watch(__dirname + "/public");
: 미널: :npm start
브라우저에서 확장 아이콘을 클릭하여 연결합니다.
라이브 새로고침과 노데몬을 터미널별로 사용할 수도 있습니다.
"scripts": {
"start": "nodemon server.js",
"livereload": "livereload"
}
npm start
npm livereload
npm livereload -p PORT_NUMBER
port " " " " " " "
업데이트: 한 번 저장해도 작동하지 않을 수 있습니다.Ctrl+S를 몇 번 더 새로고침하여 변경합니다.브라우저 캐싱 문제인지 패키지 문제인지 모르겠습니다.
ifgrunt
하면 npm 패키지 npm이 grunt-contrib-watch
이치노
, 또 다른 것, '보다 낫다'를 한 번 요?grunt-express-server
함께 일할 수 있는 사람.
Node.js 19를 사용하여 파일 변경을 감시할 수 있습니다.--watch
선택.파일이 변경되면 프로세스가 자동으로 재시작되어 새로운 변경이 반영됩니다.
"start": "node --watch server.js"
노데몬을 써도 돼요.
프로젝트의 파일을 감시하고, 변경 시 서버를 재기동합니다.
글로벌하게 인스톨 할 수 있습니다.
npm install -g nodemon
프로젝트 디렉토리에서 실행
cd ./my-project
nodemon
프로젝트의 개발 종속성에 추가하여 npm 스크립트에서 사용할 수도 있습니다.
npm install --save-dev nodemon
그런 다음 간단한 스크립트를 추가합니다.package.json
:
"scripts": {
"start": "node server.js",
"dev": "nodemon"
}
그러면 다음 명령을 실행할 수 있습니다.
npm run dev
언급URL : https://stackoverflow.com/questions/45622125/how-can-i-add-live-reload-to-my-nodejs-server
'programing' 카테고리의 다른 글
Wordpress에서 Gutenberg 블록 카테고리를 나열, 정렬 또는 조작하는 방법 (0) | 2023.02.25 |
---|---|
오라클에서 SELECT 쿼리를 사용하여 빈 열/빈 열을 생성하는 방법은 무엇입니까? (0) | 2023.02.25 |
문자열의 Gson 배열에서 Json Array로 (0) | 2023.02.25 |
WordPress에서 사용자 정의 양식을 만들려면 어떻게 해야 합니까? (0) | 2023.02.25 |
ng-change of select in angularjs에서 서비스 방법을 호출하는 방법 (0) | 2023.02.25 |