hitchhiker
hitchhiker

Reputation: 1319

Why webpack incorrectly resolve a local path to Javascript file as root path?

I'm using webpack 4.20.0 npm package. One of the dependencies of my dependencies in the npm package mimer. mimer has a file mime.types located in node_modules/mimer/lib/data/mime.types. The package also has a file node_modules/mimer/lib/exec.js which contains the following line:

list: (typeof process !== 'undefined' && process.cwd) ? require('./data/parser')(__dirname + '/data/mime.types') : $_MIMER_DATA_LIST

webpack succeeds to compile my code and I get a bundle but when I run the bundle with node.js I get this error:

Error: ENOENT: no such file or directory, open '//data/mime.types'

I think it occurs as a result of webpack incorrectly providing __dirname value by resolving __dirname as root. Is there a way to solve such an issue in webpack?

This is my webpack config:

const path = require('path')
const webpack = require('webpack')


module.exports = {
  mode: 'development',
  target: 'node',
  context: path.resolve(__dirname),
  entry: path.resolve(__dirname, 'src', 'index.js'),
  resolve: {
    modules: [path.resolve(__dirname, './src'), 'node_modules'],
    extensions: ['.js', '.jsx', '.json'],
  },
  output: {
    filename: 'bundle.js',
    publicPath: path.resolve(__dirname, 'assets'),
    path: path.resolve(__dirname)
  },
  devtool: 'source-map',
  plugins: [
    new webpack.IgnorePlugin(/^(hiredis|transifex)$/)
  ],
  module: {
    rules: [
      {
        test: /\.js?$/,
        use: {
          loader: 'babel-loader',
          options: {
            rootMode: 'upward'
          }
        },
        include: [
          path.resolve(__dirname, 'src')
        ]
      }
    ]
  }
}

Upvotes: 1

Views: 1314

Answers (1)

Aritra Chakraborty
Aritra Chakraborty

Reputation: 12542

So basically webpack returns __dirname to be /. So you basically have to tell webpack to resolve __dirname.

add:

node: {
    __dirname: true
}

same thing with __filename as well.

Upvotes: 3

Related Questions