Current file path in webpack

后端 未结 3 1897
时光说笑
时光说笑 2020-12-05 05:07

Is there any way to receive current file path, like in requirejs?

define([\'module\'], function (module) {
    console.log(module.uri)
});
相关标签:
3条回答
  • 2020-12-05 05:31

    Yep there is one: __filename.

    But by default webpack doesn't leak path information and you need to set a config flag to get real filename instead of a mock ("/index.js").

    // /home/project/webpack.config.js
    module.exports = {
      context: __dirname,
      node: {
        __filename: true
      }
    }
    

    Than you can use __filename get the current filename relative to the context option:

    // in /home/project/dir/file.js
    console.log(__filename);
    // => logs "dir/file.js"
    

    The filename is only embedded into modules where __filename is used. So you don't have to be affraid that paths are leaked from other modules.

    0 讨论(0)
  • 2020-12-05 05:40

    To get the filename an the dir name I added this to the web pack config

    node : {
       __filename: true,
       __dirname: true,
    },
    

    setting the context to __dirname messed up my web pack config since I have my webpackconfig not placed in root but the paths are setup that way

    0 讨论(0)
  • 2020-12-05 05:44

    Try webpack.DefinePlugin with webpack.DefinePlugin.runtimeValue. It gives real constants, which can be used in ES6 import and require().

    Webpack configuration:

    new webpack.DefinePlugin({
        __NAME: webpack.DefinePlugin.runtimeValue(
            v => {
                const res = v.module.rawRequest.substr(2)
                return JSON.stringify(res); // Strings need to be wrapped in quotes
            }, []
        )
    })
    
    // OR
    
    new webpack.DefinePlugin(
        __NAME: webpack.DefinePlugin.runtimeValue(
            v => {
                const res = v.module.rawRequest.substr(2)
                return `'${res.substr(0, res.lastIndexOf('.'))}'`
            }, []
        )
    })
    

    Source file:

    // require "<filename>.html" from "<filename>.js"
    const html = require(`./${__NAME}.html`)
    
    0 讨论(0)
提交回复
热议问题