@_pearofducks/webpack-plugin-serve 中文文档教程

发布于 6年前 浏览 35 项目主页 更新于 3年前

webpack-plugin-serve

测试封面size

webpack-plugin-serve

插件中的 Webpack 开发服务器。

请务必浏览我们的食谱,并在阅读完下面的文档。

如果您觉得这个项目有用,请考虑捐赠。

Requirements

webpack-plugin-serve 是一个 evergreen ???? 模块。

此模块需要 Active LTS Node 版本(v8.0.0+ 或 v10.0.0+)。 此模块中的客户端脚本需要支持async/await的浏览器。 用户还可以选择通过适当配置的 Babel webpack 加载器来编译客户端脚本,以便在旧版浏览器中使用。

Feature Parity

在许多方面,webpack-plugin-serve 从众多替代品中脱颖而出。 与现有解决方案的功能对等是重中之重。 如果您在替代方案中期望的某个功能不能直接使用,则可能很容易通过中间件实现。 随意打开一个问题以获得指导。

对于那些对直接比较感兴趣的人,请参阅功能网格以了解 webpack-plugin-serve 之间功能比较的细分和替代品。

Install

使用 npm:

npm install webpack-nano webpack-plugin-serve --save-dev

注意:我们建议使用 webpack-nano,这是一个非常小巧、非常干净的 webpack CLI。

Usage

创建一个 webpack.config.js 文件:

const { WebpackPluginServe: Serve } = require('webpack-plugin-serve');
const options = { ... };

module.exports = {
    // an example entry definition
    entry: [
        'app.js',
        'webpack-plugin-serve/client' // ← important: this is required, where the magic happens in the browser
    ]
  ...
  plugins: [
    new Serve(options)
  ],
  watch: true  // ← important: webpack and the server will continue to run in watch mode
};

然后运行 ​​webpack: 输入

$ npx wp

Options

client

Object
默认值:null

专门为客户端脚本设置选项。 在大多数情况下不需要修改此选项。

Properties

client.address

类型:String

如果设置,则允许覆盖 WebSocket 地址,该地址默认对应于服务器地址。 此选项的值应采用有效的 {host}:{port} 格式。 例如 localhost:433

client.retry

类型:Boolean

如果 true,指示客户端在连接中断时尝试重新连接所有 WebSockets,通常是由于服务器被中断停止和/或重新启动。 注意:这在浏览器控制台中可能非常垃圾,因为当 WebSocket 连接失败时,无法抑制来自浏览器的错误消息。

compress

类型:布尔值
默认值:false

如果true,则启用压缩中间件,它为文件提供 GZip 压缩。

historyFallback

类型:<代码>布尔值 | 对象
默认值:false

如果 true,通过 启用 History API Fallback代码>connect-history-api-fallback。 用户还可以将 options 对象传递给此属性。 有关详细信息,请参阅 connect-history-api-fallback

这个设置在使用 HTML5 History API 时会很方便; index.html 页面可能必须提供以代替服务器的任何 404 响应,特别是在开发单页应用程序时。

hmr

类型:布尔值
默认值:true

如果 true,将启用 热模块替换,它在应用程序仍在运行时动态地交换、添加或删除捆绑包中的模块,而无需重新加载整个页面。

host

类型:<代码>字符串 | 承诺
默认值::: 用于 IPv6,127.0.0.1 用于 IPv4

设置服务器应侦听的主机。 用户可以选择将其设置为 Promise,或在服务器需要等待主机的情况下返回 PromiseFunction解决。

注意:默认 URI 是 http://[::]:{port}。 如需更多信息,请阅读常见问题解答

http2

类型:boolean | http2 选项 | 安全 http2 选项

如果设置,此选项将指示服务器启用 HTTP2。 此选项的属性应对应于 HTTP2 选项HTTP2 SSL 选项

https

类型:对象
默认值:null

如果设置,此选项将指示服务器通过 HTTPS 启用 SSL。 此选项的属性应对应于 HTTPS 选项

liveReload

类型:布尔值
默认值:false

如果true,将指示客户端在每次构建后执行完整页面重新加载。

注意:此选项会覆盖为 hmr 选项属性设置的任何值。

log

类型:String
默认值:{ level: 'info' }
有效的 level 值:'trace' | '调试' | '信息' | '警告' | 'error'

设置消息应出现在控制台中的级别。 例如:如果设置了 warn,则 warnerror 级别的每条消息都将可见。 这个模块不会产生太多的日志输出,所以你可能不必摆弄这个。

timestamp: true 属性/值也可用于在每个日志行前加上 HH:mm:ss 格式的时间戳。

middleware

类型:函数
默认值:(app, builtins) => {}

允许用户实现自定义中间件,并操纵内置中间件的执行顺序。 此方法还可能返回一个 Promise 以暂停进一步的中间件评估,直到 Promise 解决。 这个属性应该只由对 Express/Koa 风格中间件有扎实了解的用户设置,并且那些了解操纵内置中间件顺序的后果的用户。

Example

// webpack.config.js
module.exports = {
  plugins: [
    new WebpackPluginServe({
      middleware: (app, builtins) =>
        app.use(async (ctx, next) => {
          ctx.body = 'Hello world';
          await next();
        })
    })
  ]
};

当前支持的内置中间件在 builtins 参数上可用:

compress → 转发到 koa压缩
four0four → 处理导致 404 状态的请求
historyFallback → 转发到 connect-history-api-fallback
proxy → 转发到 http-proxy-middleware
static → 转发到 koa-static
websocket → 提供 WebSocket 支持的自定义中间件

open

类型:boolean | 对象
默认值:false

如果true,将默认浏览器打开到设置的hostport。 用户还可以选择传递包含 opn 模块选项的 Object ,用于此功能。

port

类型:<代码>数字 | 承诺
默认值:55555

设置服务器应侦听的端口。 用户可以选择将其设置为 Promise,或者在服务器需要等待端口的情况下返回 PromiseFunction解决。

progress

类型:<代码>布尔值 | 字符串
默认值:true

如果truthy,模块将添加一个ProgressPlugin 实例到 webpack 编译器,并在浏览器页面上显示一个进度指示器。

如果设置了 'minimal' 的值,进度指示器将呈现为窗口顶部的彩色小条。 当默认花哨的进度指示器干扰页面中的元素时,这会很有用。

static

类型:<代码>字符串 | 数组(字符串)
默认值:compiler.context

设置提供静态文件的目录。 捆绑包将从 output 配置设置中提供。

status

类型:布尔值
默认值:true

默认情况下,webpack-plugin-serve 将在构建导致错误和/或警告时显示状态覆盖。 要禁用此功能,请在选项中设置 status: false

status overlay

单击最小化按钮(黄点)时,覆盖将缩小到页面右下角的单个小框,并使用相同的绿色、红色和黄色显示状态信标,表示构建成功、错误和错误。警告,分别。

status beacons

Proxying

通过 middleware 选项支持使用 webpack-plugin-serve 进行代理。 但是,虽然这个插件模块不包含任何用于代理的花哨选项处理,但它确实包括对 http-proxy-middleware< 的访问/a> 模块默认情况下,其余的对于 http-proxy-middleware 的用户来说应该很熟悉。

// webpack.config.js
module.exports = {
  ...,
  plugins: [
    new WebpackPluginServe({
      middleware: (app, builtins) => {
        app.use(builtins.proxy('/api', { target: 'http://10.10.10.1:1337' }));
      }
    })
  ]
};

注意:此处的 app.use(...) 调用与 Express 用户习惯于使用 http-proxy-middleware 看到的略有不同。 这是由于模块与 Koa 的交互方式存在细微差异,后者在该插件的底层使用。

Meta

贡献

许可证(Mozilla 公共许可证)

webpack-plugin-serve

testscoversize

webpack-plugin-serve

A Webpack development server in a plugin.

Be sure to browse our recipes and peruse the FAQ after reading the documentation below.

Please consider donating if you find this project useful.

Requirements

webpack-plugin-serve is an evergreen ???? module.

This module requires an Active LTS Node version (v8.0.0+ or v10.0.0+). The client scripts in this module require browsers which support async/await. Users may also choose to compile the client script via an appropriately configured Babel webpack loader for use in older browsers.

Feature Parity

In many ways, webpack-plugin-serve stands out from the alternatives. Feature parity with existing solutions is a high priority. If a feature you've come to expect in an alternative isn't directly available, it's likely easy to implement via middleware. Feel free to open an issue for direction.

For those interested in direct comparisons, please see the Feature Grid for a breakdown of feature comparisons between webpack-plugin-serve and the alternatives.

Install

Using npm:

npm install webpack-nano webpack-plugin-serve --save-dev

Note: We recommend using webpack-nano, a very tiny, very clean webpack CLI.

Usage

Create a webpack.config.js file:

const { WebpackPluginServe: Serve } = require('webpack-plugin-serve');
const options = { ... };

module.exports = {
    // an example entry definition
    entry: [
        'app.js',
        'webpack-plugin-serve/client' // ← important: this is required, where the magic happens in the browser
    ]
  ...
  plugins: [
    new Serve(options)
  ],
  watch: true  // ← important: webpack and the server will continue to run in watch mode
};

And run webpack:

$ npx wp

Options

client

Type: Object
Default: null

Sets options specifically for the client script. In most situations this option doesn't need to be modified.

Properties

client.address

Type: String

If set, allows for overriding the WebSocket address, which corresponds to the server address by default. Values for this option should be in a valid {host}:{port} format. e.g. localhost:433.

client.retry

Type: Boolean

If true, instructs the client to attempt to reconnect all WebSockets when their connects are interrupted, usually as a result of the server being stopped and/or restarted. Note: This can be very spammy in the browser console, as there is no way to suppress error messages from the browser when a WebSocket fails to connect.

compress

Type: Boolean
Default: false

If true, enables compression middleware which serves files with GZip compression.

historyFallback

Type: Boolean | Object
Default: false

If true, enables History API Fallback via connect-history-api-fallback. Users may also pass an options Object to this property. Please see connect-history-api-fallback for details.

This setting can be handy when using the HTML5 History API; index.html page will likely have to be served in place of any 404 responses from the server, specially when developing Single Page Applications.

hmr

Type: boolean
Default: true

If true, will enable Hot Module Replacement which exchanges, adds, or removes modules from a bundle dynamically while the application still running, without the need of a full page reload.

host

Type: String | Promise
Default: :: for IPv6, 127.0.0.1 for IPv4

Sets the host the server should listen from. Users may choose to set this to a Promise, or a Function which returns a Promise for situations in which the server needs to wait for a host to resolve.

Note: The default URI is http://[::]:{port}. For more info, please read the FAQ.

http2

Type: boolean | http2 options | secure http2 options

If set, this option will instruct the server to enable HTTP2. Properties for this option should correspond to HTTP2 options or HTTP2 SSL options.

https

Type: Object
Default: null

If set, this option will instruct the server to enable SSL via HTTPS. Properties for this option should correspond to HTTPS options.

liveReload

Type: boolean
Default: false

If true, will instruct the client to perform a full page reload after each build.

Note: This option overrides any value set for the hmr option property.

log

Type: String
Default: { level: 'info' }
Valid level Values: 'trace' | 'debug' | 'info' | 'warn' | 'error'

Sets a level for which messages should appear in the console. For example: if warn is set, every message at the warn and error levels will be visible. This module doesn't produce much log output, so you probably won't have to fiddle with this.

A timestamp: true property/value may also be used to preface each log line with an HH:mm:ss format timestamp.

middleware

Type: Function
Default: (app, builtins) => {}

Allows users to implement custom middleware, and manipulate the order in which built-in middleware is executed. This method may also return a Promise to pause further middleware evaluation until the Promise resolves. This property should only be set by users with solid knowledge of Express/Koa style middleware and those which understand the consequences of manipulating the order of built-in middleware.

Example

// webpack.config.js
module.exports = {
  plugins: [
    new WebpackPluginServe({
      middleware: (app, builtins) =>
        app.use(async (ctx, next) => {
          ctx.body = 'Hello world';
          await next();
        })
    })
  ]
};

Currently supported built-in middleware that are available on the builtins parameter:

compress → forwards to koa-compress
four0four → handles requests that result in a 404 status
historyFallback → forwards to connect-history-api-fallback
proxy → forwards to http-proxy-middleware
static → forwards to koa-static
websocket → Custom middleware that provides WebSocket support

open

Type: boolean | Object
Default: false

If true, opens the default browser to the set host and port. Users may also choose to pass an Object containing options for the opn module, which is used for this feature.

port

Type: Number | Promise
Default: 55555

Sets the port on which the server should listen. Users may choose to set this to a Promise, or a Function which returns a Promise for situations in which the server needs to wait for a port to resolve.

progress

Type: boolean | String
Default: true

If truthy, the module will add a ProgressPlugin instance to the webpack compiler, and display a progress indicator on the page within the browser.

If a value of 'minimal' is set, the progress indicator will render as a small, colored bar at the top of the window. This can be useful when the default fancy progress indicator interferes with elements in the page.

static

Type: String | Array(String)
Default: compiler.context

Sets the directory(s) from which static files will be served. Bundles will be served from the output config setting.

status

Type: boolean
Default: true

By default, webpack-plugin-serve will display a status overlay when a build results in errors and/or warnings. To disable this feature, set status: false in the options.

status overlay

When the minimize button (yellow dot) is clicked, the overlay will shrink to a single small box in the lower right corner of the page and display a status beacon using the same green, red, and yellow colors for build success, errors, and warnings, respectively.

status beacons

Proxying

Proxying with webpack-plugin-serve is supported via the middleware option. But while this plugin module doesn't contain any fancy options processing for proxying, it does include access to the http-proxy-middleware module by default, and the rest should look familiar to users of http-proxy-middleware.

// webpack.config.js
module.exports = {
  ...,
  plugins: [
    new WebpackPluginServe({
      middleware: (app, builtins) => {
        app.use(builtins.proxy('/api', { target: 'http://10.10.10.1:1337' }));
      }
    })
  ]
};

Note: The app.use(...) call here is slightly different than what Express users are used to seeing with http-proxy-middleware. This is due to subtle differences in how the module interacts with Koa, which is used under the hood in this plugin.

Meta

CONTRIBUTING

LICENSE (Mozilla Public License)

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文