Skip to content

Using dynamic require on node targets WITHOUT resolve or bundle the target module #4175

Closed

Description

@vandalouze

Do you want to request a feature or report a bug?
Bug

What is the current behavior?
I want to dynamically require a module, how node will do it, at runtime.
Use cases:

  • require a project configuration (cwd + "projectConfig.js")
  • require the entry point of a server build
  • require client assets manifest from client build
    etc.

If the current behavior is a bug, please provide the steps to reproduce.

let myDynamicServerEntryPoint = '/this/is/an/absolute/path/i-need-this.js';
require(myDynamicServerEntryPoint);

target is set to node in webpack config.

This ends up that webpack try to bundle all files which could be the dependencies (forget the name of this - but I'm sure you know what I mean). If the require have just a variable as param logically it just tries to bundle every file... however that's not the point.

  • put the target file in externals config key does not work because dynamic requires are not tested there
  • ContextReplacementPlugin does not help here, I don't want to rewrite the module request, I want to AVOID it entirely.
  • IgnorePlugin etc. will never reached, it's a dynamic import

What is the expected behavior?
Make it possible to just avoid webpack to touch a particular require statement and NOT try to resolve it. This is of course only usable for node builds.

PS
I don't want to use any require.ensure, System.import etc. - forget the name of all 5.
There must be a sync way to require a file on node side, without promises.

Possible solutions:
I don't think it's a good idea for a sixth require method but just to mention, there should be possible something like const server = nodeRequire(entryPath)
What could be possible:
A plugin which receive the require parameter as string maybe? However this seems like like crap solution, too.

Any other ideas?

Activity

  1. sokra commented on Feb 3, 2017

    @sokra
    Member

    const server = __non_webpack_require__(entryPath)

  2. hackape commented on Feb 21, 2017

    @hackape

    I'd like to report a situation I encountered related to this.

    I had code depending on [email protected] package, which has code that targets both browser-env and node-env sitting side-by-side in a if ... else ... in one file socket.io-client/lib/io.js.

    webpack@v2 seems to have trouble to avoid touching the require in node-env part. It throws:
    Module not found: Error: Can't resolve 'fs' in './node_modules/socket.io-client/bin'

    I just got aware of this when upgrading from webpack@v1. Curiously, v1 never reported this error at bundling this file.

  3. hackape commented on Feb 21, 2017

    @hackape

    I just digged into the built result of webpack@v1, it dumps the unwanted node-env-targeted if block entirely!

  4. olivoil commented on Apr 1, 2017

    @olivoil

    @sokra is there another solution if the require call is in a 3rd party node module, and you can't change it to __non_webpack_require__ ?

    In my case, my code requires a node module, which in turn makes a dynamic call to require a file that is user-generated, and present on disk outside of the webpack bundle. When bundling the node module, it rewrite its dynamic require call from:

    try {
      mod = require(path.join(dir, file)); // where `dir` and `file` are dynamic values
    }
    catch (err) {
      reject(err);
    }
    

    to

    try {
       mod = !(function webpackMissingModule() { var e = new Error("Cannot find module \".\""); e.code = 'MODULE_NOT_FOUND'; throw e; }());
    }
    catch (err) {
       return reject(err);
    }
    
  5. ldstein commented on Aug 17, 2017

    @ldstein

    I'm using Webpack to create deployment builds for NodeJS environments and also came across the need to handle dynamic requires outside of Webpack.

    I wanted our codebase to work both pre-webpack and post-webpack, hence I didn't want to introduce __non_webpack_require__ into our codebase.

    Our hack:

    function requireDynamically(path)
    {
        path = path.split('\\').join('/'); // Normalize windows slashes
        return eval(`require('${path}');`); // Ensure Webpack does not analyze the require statement
    }
    
    const path = require('path');
    const fs = require('fs');
    
    const files = fs.readdirSync(__dirname);
    const moduleName = path.join(__dirname, files[0]);
    const foo = requireDynamically(moduleName);  // Will be skipped by Webpack
    
    
  6. RoboPhred commented on Nov 8, 2017

    @RoboPhred

    A simpler way to pull this off without resorting to eval is:

    const requireFunc = typeof __webpack_require__ === "function" ? __non_webpack_require__ : require;
    const foo = requireFunc(moduleName);
    

    In the bundled output, this will become

    const requireFunc = true ? require : require;
    const foo = requireFunc(moduleName);
    

    This will work, as webpack uses __webpack_require__, and leaves require as the original node function.

    (Note: Currently this will not work if the typeof targets __non_webpack_require__. See #5939)

  7. webpack-bot commented on Aug 31, 2018

    @webpack-bot
    Contributor

    This issue had no activity for at least half a year.

    It's subject to automatic issue closing if there is no activity in the next 15 days.

  8. added
    status: stale
    on Aug 31, 2018
  9. mholtzhausen commented on Sep 4, 2018

    @mholtzhausen

    I'm sure this could be written better - but my prototype solution is:

    const dRequire = url => {
        let module = {}
        ;((content, module) => eval(content))(fs.readFileSync(url, { encoding: 'utf8' }), module)
        return module.exports
    }
    

    One can then use this function instead of regular require

    dRequire('/bla/somefile.js')

    Don't yell at me for eval, if you're going to dynamically add a file to your source, you had better be sure it contains safe stuff

  10. removed
    status: stale
    on Sep 4, 2018
  11. bohendo commented on Sep 19, 2018

    @bohendo

    So I'm assuming that the lack of a response to @olivoil means webpack is not supposed to be able to handle situations where our code imports a 3rd party module which uses dynamic require statements.

    There's a noParse module option that prevents WebPack from parsing certain files.. but it explicitly says we shouldn't noParse modules that require or import. Well, if we ignore this suggestion then we might have ourselves a work around.

    For example, if you want to webpack code that depends on web3.js, you've probably had trouble with scrypt. A hacky solution:

    const path = require('path');
    const CopyWebpackPlugin = require('copy-webpack-plugin')
    
    module.exports = {
      target: 'node',
      mode: "development",
    
      entry: ['./src/entry.js'],
      output: {
        path: path.join(__dirname, 'dist'),
        filename: 'bundle.js',
      },
    
      // These are required by random web3.js dependencies but are not needed, ignore them
      externals: ['electron', 'pg-native'],
    
      module: {
        // This will leave all require statements in this file untouched
        // Luckily, the scrypt index file only imports node externals (os and crypto)
        // and the one problematic file. If it imported anything else, this wouldn't work
        noParse: [/scrypt\/index.js$/],
      },
    
      plugins: [
        // We'll manually copy the problematic file to the location where it's expected
        // Now, when transporting the bundle we also need to keep track of this other file
        new CopyWebpackPlugin([
          {
            from: '../../node_modules/scrypt/build/Release/scrypt.node',
            to: './build/Release/scrypt.node',
          },
        ]),
      ],
    };

    This hacky solution only works because we get lucky & don't import anything else important in the file that imports the problematic file. So by ignoring it entirely, the problematic require is left untouched & the other requires can stand on their own.

    Please tell me I'm overthinking this & that there's a simpler way. This seems like such a common situation & I don't understand why WebPack can't handle it more cleanly..

    I have another situation where a 3rd party module does these silly dynamic requirements in a file that also requires other important stuff so this hack doesn't work. Seems like my only options are to

    1. Not use this 3rd party module
    2. Modify 3rd party code in node_modules
    3. Abandon webpack

    Since 1 isn't an option and 2 is unthinkable, it looks like I'm stuck with option 3..

  12. mjewell commented on Jan 1, 2019

    @mjewell

    Not the greatest solution, but I was having this same problem using knex migrations in lambdas. This solution seems better than most although still not great.

    In your webpack module.rules:

    {
      // regex for the files that are problematic
      test: /knex\/lib\/migrate\/sources/,
      loader: 'string-replace-loader',
      options: {
        // match a require function call where the argument isn't a string
        // also capture the first character of the args so we can ignore it later
        search: 'require[(]([^\'"])',
        // replace the 'require(' with a '__non_webpack_require__(', meaning it will require the files at runtime
        // $1 grabs the first capture group from the regex, the one character we matched and don't want to lose
        replace: '__non_webpack_require__($1',
        flags: 'g'
      }
    }

    also you will need to install string-replace-loader: https://github.com/Va1/string-replace-loader

  13. 2 remaining items

  14. josiahruddell commented on Feb 6, 2019

    @josiahruddell

    I was able to work around the issue by using webpack's noParse module configuration. I posted the solution on stack overflow.

  15. nzvtrk commented on May 28, 2019

    @nzvtrk

    i found the same problem with async imports on win32.

    Wrong code:

      const Feature = await import(
        /* webpackInclude: /features\/[^\/]+\/src\/index\.js/, webpackChunkName: "feature-[request]" */
        `../../features/${featurePath}/src/index.js`
      );
    

    After change slashes in webpackInclude regexp, everything is ok.

    webpackInclude: /features\\[^\/]+\\src\\index\.js/

  16. alex-vukov commented on Feb 12, 2020

    @alex-vukov

    I hope the following hack is helpful for somebody. I tried to achieve the same from a UMD library. My scenario is the following. I have a main React web application bundled with Webpack and a microfrontend UMD library (also in React and bundled with Rollup) which should load in one of the views of the main app from a remote url. Both projects use a lot of the same libraries (react, react-dom, react-bootstrap, etc.) so I didn't want to bundle them in two places. I wanted the library to dynamically import its dependencies if they exist in the bundle of the main application. After 3-4 days of trying all kinds of webpack and rollup configurations (externals etc.) I had to resort to the following ugliness. In the main application I created a function called "remoteImport" and when the UMD module loads I pass the function to the component inside it as a prop. The function looks like this:

        const remoteImport = module => {
            const str = `./node_modules/${module}`;
            // __webpack_require__.c is the cache of already imported node_modules exposed by webpack
            const installedModules = __webpack_require__.c;
                for(const moduleId of Object.keys(installedModules)) {
                    if(moduleId.indexOf(str) > -1) {
                        return __webpack_require__(moduleId);
                    }
                }
             return null;
        };
    

    Then the UMD library can call remoteImport("react") for example and if it is found in the webpack bundle it will be returned.

  17. Domiii commented on Sep 20, 2020

    @Domiii

    Currently @mjewell 's workaround seems to be the best, while certainly still having a lot of issues.

    As it stands, Webpack just does not support regular dynamic require. It just bugs out, unless you manually replace require with __non_webpack_require, which is a nonsensical requirement in Node (however makes sense traditionally when Webpack was only targeting the brower).

    However, a fix would be great. When will it be possible...

    • to override the require behavior dynamically?
    • or at least provide some way of resolving require calls with dynamic arguments?
    • or at least have __webpack_require__ be respectful of externals, which (just like many other features) are just entirely ignored as soon as we encounter a dynamic require.

    -> If we can fix this, that would also take care of the cryptic Critical dependency: the request of a dependency is an expression problem (which is a webpack warning seen for dynamic require calls).

    Improved Workaround

    For anyone still struggling I took @mjewell's workaround and added some logging.

    The biggest downside: Will stop working if your code contains any string that contains the literal require(.

    Code:

    /**
     * Gets the line at given offset in s, as well as `nLines` lines below and above.
     */
    function getLinesAroundOffset(s, offset, nLines = 1, maxChars = 50) {
      let start = offset - 1;
      for (let i = 0; i < nLines; ++i) {
        const newIdx = s.lastIndexOf('\n', start) - 1;
        if (Math.abs(start - newIdx) > 200) {
          // probably compressed code
          start -= maxChars;
          break;
        }
        if (newIdx >= 0) {
          start = newIdx;
        }
      }
      let end = offset + 1;
      for (let i = 0; i <= nLines; ++i) {
        const newIdx = s.indexOf('\n', end) + 1;
        if (Math.abs(end - newIdx) > 200) {
          // probably compressed code
          end += maxChars;
          break;
        }
        if (newIdx >= 0) {
          end = newIdx;
        }
      }
    
      return s.substring(start, end);
    }
    
    /**
     * @see https://github.com/webpack/webpack/issues/4175#issuecomment-695767880
     */
    const dynamicRequireRule = {
      test: /\.js$/,
      loader: 'string-replace-loader',
      enforce: 'pre',
      options: {
        // match a require function call where the argument isn't a string literal
        search: /require\(\s*(?![\'"])/,
        // replace the 'require(' with a '__non_webpack_require__(', meaning it will require the files at runtime
        // $1 grabs the first capture group from the regex, the one character we matched and don't want to lose
        // replace: '__non_webpack_require__($1',
        // see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter
        replace: (match, offset, s) => {
          // debugger;
          const requireLines = getLinesAroundOffset(s, offset, 1);
    
          // eslint-disable-next-line no-console
          console.warn(`Fixing dynamic require:\n`, /* match */requireLines, '\n\n');
          return `__non_webpack_require__(`;
        },
    
        flags: 'g'
      }
    };
    
    // ...
    
        module: {
          rules: [
            dynamicRequireRule
          ]
        }
  18. webpack-bot commented on Jan 16, 2021

    @webpack-bot
    Contributor

    This issue had no activity for at least three months.

    It's subject to automatic issue closing if there is no activity in the next 15 days.

  19. added
    status: stale
    on Jan 16, 2021
  20. webpack-bot commented on Jan 31, 2021

    @webpack-bot
    Contributor

    Issue was closed because of inactivity.

    If you think this is still a valid issue, please file a new issue with additional information.

  21. alexander-akait commented on Feb 1, 2021

    @alexander-akait
    Member

    webpack@5 supports magic comments for require #11316, so you can avoid using __non_webpack_require__, example:

    webpack.config.js

    module.exports = {
        mode: 'development',
        entry: './node.js',
        module: {
            parser: {
                javascript: {
                    // Enable magic comments, disable by default for perf reasons
                    commonjsMagicComments: true
                }
            }
        },
    };

    node.js

    const foo = require(/* webpackIgnore: true */ 'foo');

    So, I think it can be closed, sorry for delay and feel free to feedback

  22. yonahochieng commented on Apr 16, 2021

    @yonahochieng

    I'm using Webpack to create deployment builds for NodeJS environments and also came across the need to handle dynamic requires outside of Webpack.

    I wanted our codebase to work both pre-webpack and post-webpack, hence I didn't want to introduce __non_webpack_require__ into our codebase.

    Our hack:

    function requireDynamically(path)
    {
        path = path.split('\\').join('/'); // Normalize windows slashes
        return eval(`require('${path}');`); // Ensure Webpack does not analyze the require statement
    }
    
    const path = require('path');
    const fs = require('fs');
    
    const files = fs.readdirSync(__dirname);
    const moduleName = path.join(__dirname, files[0]);
    const foo = requireDynamically(moduleName);  // Will be skipped by Webpack
    

    Thank you ... saved me big time

  23. adjenks commented on Apr 16, 2021

    @adjenks

    I know many of you think it's fine to eval() if you know what's going into it, but it's always good to reiterate the point that you shouldn't eval anything that can be user generated. If this were determined by a url, a simple url change could trigger a script injection like so:
    requireDynamically('some-package.js\');alert("Script injected!");\/\/')

  24. hle-aashish commented on May 20, 2021

    @hle-aashish

    For anyone, using some third-party modules that use dynamic require like migration package and looking for a solution, you can use the following plugin.

    https://framagit.org/Glandos/webpack-ignore-dynamic-require

    // webpack.config.js
    const IgnoreDynamicRequire = require('webpack-ignore-dynamic-require');
    
    module.exports = {
      // ...
      plugins: [
        new IgnoreDynamicRequire()
      ]
    }
    
    
  25. scamden commented on May 21, 2021

    @scamden
    Contributor

    function requireDynamically(path)
    {
    path = path.split('\').join('/'); // Normalize windows slashes
    return eval(require('${path}');); // Ensure Webpack does not analyze the require statement
    }

    would be better written this way

    // Ensure Webpack does not analyze the require statement
    const requireDynamically = eval('require');

    This way you're guaranteed not to eval any dynamic content and only have to execute the eval once on module load. (In fact i think we can leave out the windows slash normalization potentially as well.. edited to reflect that)

    The magic comment didn't work for me in weback 5 to avoid the warning about dynamic dependencies so I resort to my first ever use of eval.. cue tears..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    status: stale

    Type

    No type

    Fields

    Priority

    None yet

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions