lipp
lipp

Reputation: 5926

How can I keep "require" working for dynamic expressions

I want to bundle a Node.js script, which somewhere calls require(expression). After bundling the script with webpack, require fails. This is a super simplified example:

// main.js
const x = require(process.argv[2])
console.log(x)

I would like to either have a "normal" require for this case or tell webpack to include a specific file which I know will be required in the future (after bundling). To stick with this example, I know the value of process.argv[2] ahead of bundling.

Note: The code doing the expression based require is a dependency, so I cannot tweak require code.

This is my webpack.config.js

module.exports = {
  entry: './test.js',
  output: {
    filename: 'test.js'
  },
  target: 'node'
}

Upvotes: 3

Views: 205

Answers (1)

redstarwilly
redstarwilly

Reputation: 11

The require path is relative to the file it is used in. So you'll need to figure out the path from where require is executing to the file it's loading from the parameter. Then prepend the relative part to the parameter.

Upvotes: 1

Related Questions