0

Can some one shed any light on this weird issue i've been having.

I have a project of the following shape:

index.js

src/
    static/
        favicon.ico
        styles.css
    server.js
    routes.js
    app.jsx
    //[...]

dist/
    /static
        favicon.ico
        styles.css
    server.js

The /src dir gets compiled (via webpack) and uglified out into a /dist dir. The index.js in the root project directory is just a simple switch that requires /dist/server.js if NODE_ENV=production, and reqiures /src/server.js if in development.

The issue i'm having is that __dirname and __filename behave as expected when running in development --- correctly reporting the directory each executed file is in. However, when running in production, the only directory getting reported is the root directory where index.js is. dist/server.js does not seem to recognise that it's inside a /dist folder, it seems to now think it's inside the project root. Weird!!

What's happening here? Why does the minified dist/server.js think it's nested within ./index.js, but the non minified src/server.js correctly recognises its within the src/ dir?

Is this webpack/uglify transforming things it shouldn't, or is this just the nature of minified code running in production? I'm struggling to find a work around, which is making setting dist/static/ as the correct static dir in production rather difficult.

Scotty
  • 2,635
  • 6
  • 30
  • 39
  • Not 100% sure but I bet it's due to the way stuff in the minified js is defined/executed. The code is no longer part of that file and instead run "outside", which causes it to appear as if it'd be in the root. – Mario Jun 07 '16 at 10:04
  • Is there any way to fix this? – Scotty Jun 07 '16 at 12:43
  • 1
    This might actually be a duplicate of [this question](http://stackoverflow.com/questions/36090842/webpack-can-not-use-dirname), which also contains a possible solution. – Mario Jun 07 '16 at 12:47

1 Answers1

2

Adding the following to the webpack conf fixes the issue. It appears as if webpack mocks __dirname by default resulting in just a /. True compiles __dirname to a string of the context path, and false leaves __dirname how it is in node.

  node: {
    __dirname: false  
  },

Cheers to Mario in the comments above for pointing me in the right direction!

Scotty
  • 2,635
  • 6
  • 30
  • 39