简体   繁体   中英

How to exclude Express view engines from Webpack bundle

I'm bundling my CLI app using Webpack v4. One of the dependencies is Express, and this causes a warning:

WARNING in ./node_modules/express/lib/view.js 81:13-25
Critical dependency: the request of a dependency is an expression
 @ ./node_modules/express/lib/application.js
 @ ./node_modules/express/lib/express.js
 @ ./node_modules/express/index.js

That comes from this line within Express:

/**
 * Initialize a new `View` with the given `name`.
 *
 * Options:
 *
 *   - `defaultEngine` the default template engine name
 *   - `engines` template engine require() cache
 *   - `root` root path for view lookup
 *
 * @param {string} name
 * @param {object} options
 * @public
 */

function View(name, options) {
  var opts = options || {};

  this.defaultEngine = opts.defaultEngine;
  this.ext = extname(name);

  // ...

  if (!opts.engines[this.ext]) {
    // load engine
    var mod = this.ext.substr(1)
    debug('require "%s"', mod)

    // default engine export
    var fn = require(mod).__express // <-- this require is the problem

There's quite a few questions asking about how to fix this by not bundling express at all, or not bundling anything from node_modules.

For me that would defeat the point (I'm trying to shrink my deployed file footprint), so I want to fix this whilst keeping express inside my bundle. In my case I don't use view engines at all, and this require exists solely to load view engines on demand, so I really just want the warning to go away.

If I'm confident that this require will never be called, how can I tell webpack to ignore it completely?

What you could maybe try is alter you webpack config module rules so that view unit uses the null-loader

This will of course make View return null but if you never touch views it might be ok.

example.

rules: [
 {
   test: require.resolve("express/view"),
   use: 'null-loader',
  },
],

Looking at application

this.set('view', View); hopefully View been null here doesn't cause issues.

The only other place View is then mentioned in application is then in render that you say your not using. So fingers crossed this won't cause any side effects.

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