Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Trouble with __dirname #39

Closed
neelance opened this issue Jul 28, 2016 · 3 comments
Closed

Trouble with __dirname #39

neelance opened this issue Jul 28, 2016 · 3 comments

Comments

@neelance
Copy link

My tests have to read (and optionally write) some files relative to the test's .js file. For getting the correct path I used __dirname before switching to mocha-webpack. Now I'm having a hard time making __dirname work. I tried the node.__dirname options in the webpack config, but with no success. Do you have any idea on how to solve this? Mocha-webpack works great otherwise, great job!

@zinserjan
Copy link
Owner

Seems that there is no way to get this behavior with webpack without doing something special. Webpack replaces the __dirname and __filename with constant strings.

Let's do the same. I modified webpack's NodeStuffPlugin plugin to get the desired effect.

NodePathReplacePlugin.js

/**
 * Modified NodeStuffPlugin to replace __filename and __dirname with absolute path
 * @see https://github.com/webpack/webpack/blob/ca8b693c2c17bd06778476381fae23b3b21c0475/lib/NodeStuffPlugin.js
 */
function NodePathReplacePlugin() {}
module.exports = NodePathReplacePlugin;
NodePathReplacePlugin.prototype.apply = function(compiler) {

    function setModuleConstant(expressionName, fn) {
        compiler.parser.plugin("expression " + expressionName, function() {
            this.state.current.addVariable(expressionName, JSON.stringify(fn(this.state.module)));
            return true;
        });
    }

    setModuleConstant("__filename", function(module) {
        return module.resource;
    });

    setModuleConstant("__dirname", function(module) {
        return module.context;
    });

};

Just require it in your webpack config and add it the plugins sections
webpack-config.js

var NodePathReplacePlugin = require('./NodePathReplacePlugin');

module.exports = {
....
  plugins: [
    new NodePathReplacePlugin()
  ]
....
}

@neelance
Copy link
Author

Cool, thanks!

@0xR
Copy link

0xR commented Sep 4, 2016

This works indeed!

Can this be part of mocha-webpack itself? That way I don't have to add this plugin I don't quite understand to my codebase.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants