>  기사  >  웹 프론트엔드  >  webpack+dev+server 사용법에 대한 자세한 설명

webpack+dev+server 사용법에 대한 자세한 설명

php中世界最好的语言
php中世界最好的语言원래의
2018-06-11 15:50:581647검색

이번에는 webpack+dev+server 사용에 대한 자세한 설명을 가져왔습니다. webpack+dev+server 사용에 대한 자세한 설명에서 주의사항은 무엇인가요?

webpack-dev-server

webpack-dev-server는 webpack-dev-middleware를 사용하여 webpack 패키지를 제공하는 소규모 Node.js Express 서버입니다. 서버의 마이크로 런타임입니다.

다음 구성 파일(webpack.config.js)을 살펴보겠습니다.

var path = require("path");
module.exports = {
 entry:{
 app:["./app/main.js"]
 },
 output:{
 path:path.resolve(__dirname,"build"),
 publicPath:"/assets/",
 filename:"bundle.js"
}
}

여기서 소스 파일을 app 폴더에 넣고 webpack을 사용하여 빌드 폴더 아래의 Bundle.js에 패키징됩니다. .

참고: webpack-dev-server는 독립적인 NPM 패키지이므로 npm install webpack-dev-server를 통해 설치할 수 있습니다.

기본 디렉터리

webpack-dev-server는 현재 디렉터리를 기본 디렉터리로 사용합니다.

webpack-dev-server --content-base build/

위 명령은 명령줄에서 실행되며 빌드 디렉터리를 루트 디렉터리로 사용합니다. webpack- dev-server에서 생성된 패키지는 다음과 같습니다. 실제 디렉토리가 아닌 메모리에 있습니다.

기본 디렉토리에 새 index.html 파일을 만든 다음 브라우저에 http://localhost를 입력합니다. 8080회 방문

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Document</title>
</head>
<body>
 <script src="assets/bundle.js"></script>
</body>
</html>

자동 새로 고침

webpack-dev-server는 페이지를 자동으로 새로 고치는 두 가지 모드를 지원합니다.

  1. iframe 모드(페이지가 iframe에 배치되고 변경 사항이 발생하면 다시 로드됨)

  2. 인라인 모드(webpack-dev-의 클라이언트 항목 추가) 서버를 번들로 전환)

두 모드 모두 핫 모듈 교체를 지원합니다. 핫 모듈 교체의 장점은 페이지를 다시 로드하는 대신 업데이트된 부분만 교체한다는 것입니다.

iframe 모드
이 모드를 사용하면 추가 구성이 필요하지 않습니다. 다음 URL 형식으로 액세스하세요

http://:/webpack-dev -server/

예: http://localhost:8080/webpack-dev-server/ index.html.

인라인 모드

인라인 모드, 우리가 액세스하는 URL은 변경할 필요가 없습니다. 이를 활성화하십시오. 두 가지 모드가 있습니다:

1 명령줄에서 webpack-dev-server를 시작할 때 다음을 수행해야 합니다. 두 가지 작업을 수행합니다:

  1. webpack.config.js의 명령줄

  2. 에 --inline 명령을 추가합니다. devServer 추가:{inline:true}

2 Node로 webpack-dev-server를 시작할 때 .js API를 사용하려면 다음 두 가지 작업도 수행해야 합니다.

  1. webpack-dev-server 구성에 인라인 옵션이 없으므로 webpack-dev-server/client?http://«path를 추가해야 합니다. »:«port»/를 webpack 구성의 진입점에 추가하면

  2. HTML 파일에 추가하세요

 var config = require("./webpack.config.js");
 var webpack = require('webpack');
 var WebpackDevServer = require('webpack-dev-server');
config.entry.app.unshift("webpack-dev-server/client?http://localhost:8080/");
var compiler = webpack(config);
var server = new WebpackDevServer(compiler, {
 contentBase:'build/',
 publicPath: "/assets/"
});
server.listen(8080);

위 코드를 Node.js에서 실행해 보세요.

참고: webpack 구성의 devSever 구성 항목은 명령줄 모드에서만 유효합니다.

(핫 모듈 교체) 핫 모듈 교체

명령줄에서 인라인 모드를 실행하고 핫 모듈 교체를 활성화하세요

여기서 --hot 명령어만 더 추가하면 아래와 같이 됩니다.

webpack-dev-server --content-base build --inline --hot

참고: 명령줄 모드에서는 컴파일된 패키지(번들)의 액세스 위치를 지정하기 위해 webpack.config.js에서 output.publicPath를 구성해야 합니다.

Nodejs API에서 인라인 모드를 실행하고 핫 모듈 교체를 활성화합니다

필수 여기서 다음 세 가지를 수행하십시오:

  1. webpack.config.js의 항목 옵션에 webpack/hot/dev-server를 추가합니다.

  2. webpack.config의 플러그인 옵션에 new webpack.HotModuleReplacementPlugin()을 추가합니다. .js

  3. webpack-dev-server 구성에 추가: hot:true

webpack-dev-server의 구성 옵션

var WebpackDevServer = require("webpack-dev-server");
var webpack = require("webpack");
var compiler = webpack({
 // configuration
});
var server = new WebpackDevServer(compiler, {
 // webpack-dev-server options
 contentBase: "/path/to/directory",
 // Can also be an array, or: contentBase: "http://localhost/",
 hot: true,
 // Enable special support for Hot Module Replacement
 // Page is no longer updated, but a "webpackHotUpdate" message is send to the content
 // Use "webpack/hot/dev-server" as additional module in your entry point
 // Note: this does _not_ add the `HotModuleReplacementPlugin` like the CLI option does. 
 // Set this as true if you want to access dev server from arbitrary url.
 // This is handy if you are using a html5 router.
 historyApiFallback: false,
 // Set this if you want to enable gzip compression for assets
 compress: true,
 // Set this if you want webpack-dev-server to delegate a single path to an arbitrary server.
 // Use "**" to proxy all paths to the specified server.
 // This is useful if you want to get rid of 'http://localhost:8080/' in script[src],
 // and has many other use cases (see https://github.com/webpack/webpack-dev-server/pull/127 ).
 proxy: {
 "**": "http://localhost:9090"
 },
 setup: function(app) {
 // Here you can access the Express app object and add your own custom middleware to it.
 // For example, to define custom handlers for some paths:
 // app.get('/some/path', function(req, res) {
 // res.json({ custom: 'response' });
 // });
 },
 // pass [static options](http://expressjs.com/en/4x/api.html#express.static) to inner express server
 staticOptions: {
 },
 // webpack-dev-middleware options
 quiet: false,
 noInfo: false,
 lazy: true,
 filename: "bundle.js",
 watchOptions: {
 aggregateTimeout: 300,
 poll: 1000
 },
 // It's a required option.
 publicPath: "/assets/",
 headers: { "X-Custom-Header": "yes" },
 stats: { colors: true }
});
server.listen(8080, "localhost", function() {});
// server.close();

이 기사의 사례를 읽은 후 방법을 마스터했다고 생각합니다. PHP 중국어 웹사이트의 기타 관련 기사에 대해 더 흥미로운 내용을 주목해 주세요!

추천 자료:

D3.js는 메모리 순환 저장 맵을 만듭니다

응용 프로그램 모듈화를 구현하기 위해 처음부터 AngularJS 작업

위 내용은 webpack+dev+server 사용법에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.