简体   繁体   中英

Error when running a Webpack bundled Nodejs app

I have a very simple application available at 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." output.

When you run the Webpack created bundle with "node dist/bundle.js" you get the error:

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. Something with the regex method of defining the url pattern is causing this to break.

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.

The Router get method expects the first argument to be a string or a URLPattern. If the first argument is NOT an instanceof UrlPattern, it creates a new UrlPattern with the first argument. 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). Since the first argument to the UrlPattern constructor is neither a string or a RegEx, an error is thrown.

Possible Solution:

Figure out how to configure WebPack's minify process so that the UrlPattern is recognized as an instance of a UrlPattern.

Any ideas?

Changing the import fixes the problem:

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

No changes to the Webpack configuration are necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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