合规国际互联网加速 OSASE为企业客户提供高速稳定SD-WAN国际加速解决方案。 广告
# Webpack 开箱即用,Wrangler允许您开发支持模块的现代ES6应用程序。这是因为webpack的[神奇之处](https://webpack.js.org/)。本文档描述了Wrangler如何使用webpack来构建您的Workers,以及如何带来自己的配置。 **重要说明:为了让Wrangler使用webpack捆绑您的工作程序脚本,必须`type = "webpack"`在中设置`wrangler.toml`,没有其他类型将使用webpack构建您的脚本。** 如果您在这里是因为看到有关指定的警告`webpack_config`,请单击[此处](https://developers.cloudflare.com/workers/tooling/wrangler/webpack/#backwards-compatibility) ## 明智的违约 这是Wrangler用于构建工作程序的默认Webpack配置: ~~~js module.exports = { "target": "webworker", "entry": "./index.js" // inferred from "main" in package.json }; ~~~ 我们的默认配置设置`target`为`webworker`。从[webpack文档](https://webpack.js.org/concepts/targets/): > 由于可以为服务器和浏览器编写JavaScript,因此webpack提供了多个部署目标,您可以在webpack配置中设置这些目标。 Cloudflare Workers是为匹配[Service Worker API](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API)而构建的,因此我们将其设置`target`为`webworker`。 该`entry`字段直接来自`main`您的字段`package.json`。要了解有关webpack`entry`属性的更多信息,请单击[此处](https://webpack.js.org/concepts/entry-points/)。 ## 自己配置 您可以通过`webpack_config`在中设置来告诉Wrangler使用自定义Webpack配置文件`wrangler.toml`。您需要确保`target`始终如此`webworker`。 ### 例 `webpack.config.js` ~~~js module.exports = { "target": "webworker", "entry": "./index.js", "mode": "production" } ~~~ `wrangler.toml` ~~~toml type = "webpack" name = "my-worker" account_id = "12345678901234567890" workers_dev = true webpack_config = "webpack.config.js" ~~~ ### 多环境示例 `wrangler.toml` ~~~toml type = "webpack" name = "my-worker-dev" account_id = "12345678901234567890" workers_dev = true webpack_config = "webpack.development.js" [env.staging] name = "my-worker-staging" webpack_config = "webpack.production.js" [env.production] name = "my-worker-production" webpack_config = "webpack.production.js" ~~~ `webpack.development.js` ~~~js module.exports = { "target": "webworker", "devtool": "cheap-module-source-map", // avoid 'eval': Workers environment doesn't allow it "entry": "./index.js", "mode": "development" } ~~~ `webpack.production.js` ~~~js module.exports = { "target": "webworker", "entry": "./index.js", "mode": "production" } ~~~ ## 调整全局 有时您想带自己的现有全局API实现。你可以这样做[垫补](https://webpack.js.org/guides/shimming/#shimming-globals)在它的位置作为一个插件的WebPack第三方模块。 例如,`URL`要用npm软件包`url-polyfill`(或您选择的第三方软件包)替换运行时全局类,以将该软件包`npm i`本地安装并添加到工作人员的package.json中,然后将插件条目添加到webpack配置中。 ### Webpack插件示例 `webpack.config.js` ~~~js + const webpack = require('webpack'); module.exports = { "target": "webworker", "entry": "./index.js", "mode": "production", + plugins: [ + new webpack.ProvidePlugin({ + URL: 'url-polyfill', + }), + ], } ~~~ ## 向后兼容 如果使用1.6.0之前的Wrangler版本,则工作程序项目将仅使用`webpack.config.js`项目根目录中的任何内容。这并不总是很明显,因此我们计划要求您`webpack_config`在自己的名称中指定`wrangler.toml`是否要使用它。如果您看到此警告并想要使用`webpack.config.js`,只需将其添加`webpack_config = "webpack.config.js"`到wrangler.toml。 如果您正在使用工人站点,并想要指定自己的Webpack配置,则始终需要指定此配置。默认情况下,Wrangler不会假定`webpack.config.js`项目根目录中的旨在用于构建Worker。