>  기사  >  웹 프론트엔드  >  webpack-dev-server_javascript 스킬의 간단한 사용법에 대한 자세한 설명

webpack-dev-server_javascript 스킬의 간단한 사용법에 대한 자세한 설명

不言
不言원래의
2018-04-03 09:36:421085검색

이 글에서는 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"
}
}

여기에 소스 파일을 배치합니다.

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

기본 디렉터리

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-sever의 클라이언트 항목을 번들에 추가)

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

iframe 모드
이 모드를 사용하려면 추가 구성이 필요하지 않으며 다음과 같이 하면 모든 URL 형식으로 액세스할 수 있습니다

http://«host >>:/webpack-dev-server/

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

인라인 모드

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

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

  1. Add --inline 명령줄에 명령

  2. webpack.config.js에 devServer:{inline:true} 추가

2 Node.js API로 webpack-dev-server를 시작할 때 이 작업을 수행할 때 두 가지 작업도 수행해야 합니다. :

  1. webpack-dev-server 구성에 인라인 옵션이 없으므로 항목 항목에 webpack-dev-server/client?http://:/를 추가해야 합니다. 웹팩 구성의 포인트입니다.

  2. html 파일에 d141004d810ae36912d7298eeb68b32d2cacc6d41bbb37262a98f745aa00fbf0를 추가하세요

 var config = require("./webpack.config.js");
 var webpack = require(&#39;webpack&#39;);
 var WebpackDevServer = require(&#39;webpack-dev-server&#39;);

config.entry.app.unshift("webpack-dev-server/client?http://localhost:8080/");

var compiler = webpack(config);
var server = new WebpackDevServer(compiler, {
 contentBase:&#39;build/&#39;,
 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.js의 플러그인 옵션을 추가하세요. new webpack.HotModuleReplacementPlugin()

  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 &#39;http://localhost:8080/&#39; 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(&#39;/some/path&#39;, function(req, res) {
 // res.json({ custom: &#39;response&#39; });
 // });
 },

 // 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&#39;s a required option.
 publicPath: "/assets/",
 headers: { "X-Custom-Header": "yes" },
 stats: { colors: true }
});
server.listen(8080, "localhost", function() {});
// server.close();

구성 옵션: http: // webpack.github.io/docs/webpack-dev-server.html

관련 권장 사항:

webpack-dev-server에 대한 원격 모드를 설정하는 방법

webpack-dev-server는 http-proxy를 사용하여 다음을 수행합니다. 크로스 도메인 문제에 대한 자세한 설명

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

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