简体   繁体   English

运行 Webpack 捆绑的 Nodejs 应用程序时出错

[英]Error when running a Webpack bundled Nodejs app

I have a very simple application available at https://github.com/sbwrege2z/webpack-test .我在https://github.com/sbwrege2z/webpack-test有一个非常简单的应用程序。

Here's the code for the main application:这是主应用程序的代码:

const UrlPattern = require('url-pattern');
const serviceWorkerRouter = require('service-worker-router');

const router = new serviceWorkerRouter.Router();

// THIS METHOD OF ROUTING DOES NOT CAUSE A PROBLEM:
router.get('/api/*', null);

// CAUSES BUNDLE TO BREAK:
router.get(new UrlPattern(/^\/api\/(.*)$/), null);

console.log('Hello world!');

When you run this file with "node src/index.js" you get the expected "Hello world."当您使用“node src/index.js”运行此文件时,您会得到预期的“Hello world”。 output.输出。

When you run the Webpack created bundle with "node dist/bundle.js" you get the error:当您使用“node dist/bundle.js”运行 Webpack 创建的捆绑包时,您会收到错误消息:

TypeError: argument must be a regex or a string

If you comment out the line with the "new UrlPattern(...)" the bundle will run without any issues.如果您使用“new UrlPattern(...)”注释掉该行,则捆绑包将毫无问题地运行。 Something with the regex method of defining the url pattern is causing this to break.使用定义 url 模式的正则表达式方法导致此错误。

Does anyone know why this might be happening?有谁知道为什么会发生这种情况?


Update更新

I know what is causing the problem.我知道是什么导致了问题。 I just haven't come up with a solution yet.我只是还没有想出解决方案。

The UrlPattern constructor expects a string or RegEx as the first argument. UrlPattern 构造函数需要一个字符串或 RegEx 作为第一个参数。

The Router get method expects the first argument to be a string or a URLPattern. Router get 方法要求第一个参数是字符串或 URLPattern。 If the first argument is NOT an instanceof UrlPattern, it creates a new UrlPattern with the first argument.如果第一个参数不是 UrlPattern 的实例,它会使用第一个参数创建一个新的 UrlPattern。 I'm sure the assumption is that it's a string or RegEx, but it doesn't check.我确信假设它是一个字符串或正则表达式,但它不检查。

During minification something happens to that the Router does not recognize the first parameter passed to the get method as a UrlPattern, so it tries to create a new UrlPattern with the first argument (which is a UrlPattern).在缩小过程中,Router 无法将传递给 get 方法的第一个参数识别为 UrlPattern,因此它尝试使用第一个参数(即 UrlPattern)创建一个新的 UrlPattern。 Since the first argument to the UrlPattern constructor is neither a string or a RegEx, an error is thrown.由于 UrlPattern 构造函数的第一个参数既不是字符串也不是 RegEx,因此会引发错误。

Possible Solution:可能的解决方案:

Figure out how to configure WebPack's minify process so that the UrlPattern is recognized as an instance of a UrlPattern.弄清楚如何配置 WebPack 的缩小过程,以便将 UrlPattern 识别为 UrlPattern 的实例。

Any ideas?有任何想法吗?

Changing the import fixes the problem:更改导入可以解决问题:

const UrlPattern = require('service-worker-router').UrlPattern;

No changes to the Webpack configuration are necessary.无需更改 Webpack 配置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM