'webpack: how do you resolve a file into the directory where the import is defined?

I am using webpack to get specific files available in an aws lambda runtime, for this webpack is configured to include certain imported files in the build directory. I can make this happen by using the webpack >5 asset/reource functionality. What i want to do however is have the files that i import be put in the same directory as where i define the import.

for example when i have a situation like below:

- folder 
-- folderX
---- handler.js

and inside handler.js i import

import 'wsdl/WebService.wsdl'

then i want this file to be output in the same folder as handler like below

- build
-- folderX
---- handler.js
---- wsdl
------ WebService.wsdl

this way i can read the file in the lambda runtime.

so ive been doing this.

output: {
    filename: '[name].js',
    libraryTarget: 'commonjs2',
    path: resolve(__dirname, 'build'),
    pathinfo: false,
    assetModuleFilename: '[path]/[base]'
  },
  mode: isProd ? 'production' : 'development',
  module: {
    rules: [
      { test: /\.ts$/, loader: 'ts-loader', options: {transpileOnly: true} },
      {
        test: /\.(wsdl|xml)$/,
        type: 'asset/resource',
      }
    ],
  },

which results in

- build
-- folderX
---- handler.js
-- wsdl
---- WebService.wsdl

i need the wsdl folder to be inside the same folder as the handler however. Is there any way to achieve this by using another name similar to [base] or [path]?



Solution 1:[1]

ok i found the answer on my own there is a lot of custom configuration availbale in the output.assetModuleFilename option, so what i ended up using was the following function.

const resolveWsdlInCurrentRuntime: Configuration['output']['assetModuleFilename'] = (pathData) => {
    return join(dirname(pathData.runtime.toString()), '[path]', '[base]');
}
  output: {
    filename: '[name].js',
    libraryTarget: 'commonjs2',
    path: resolve(__dirname, 'build'),
    pathinfo: false,
    assetModuleFilename: resolveWsdlInCurrentRuntime,
  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 HenriDev