Search code examples
javascriptwebpackrequiredynamic-import

Webpack require unmanaged script


I have a problem with dynamic require js files after webpack bundling.

Environment:

webpack, ts-loader, typescript.

src/index.ts:

require(path.resolve(__dirname, './test.js'));

dist/test.js:

console.log('I should be printed after require @ index');

I don't know why but webpack think that there is no file:

1) Warning while running webpack -p

WARNING in ./src/index.ts
5:0-43 Critical dependency: the request of a dependency is an expression
@ ./src/index.ts

2) Error while running script:

Error: Cannot find module "C:\Users\user\path\to\dist\test.js".

3) My webpack config is:

const nodeExternals = require('webpack-node-externals');

module.exports = {
  entry: {
    index: "./src/index.ts"
  },
  output: {
    filename: "[name].js"
  },
  target: "node",
  externals: [ nodeExternals() ],
  node: {
    "__dirname": false
  },
  resolve: {
    extensions: [".ts", ".tsx", ".js"]
  },
  module: {
    rules: [
        { test: /\.tsx?$/, loader: "ts-loader" }
    ]
  }
}

Expected:

NodeJS just dynamically require path while index.js script execution.

Please help to setup that properly.

Thanks!


Solution

  • Problem solved using __non_webpack_require__ function.