webpack中的当前文件路径

Ser*_*pin 20 webpack

有没有办法接收当前的文件路径,比如requirejs?

define(['module'], function (module) {
    console.log(module.uri)
});
Run Code Online (Sandbox Code Playgroud)

Tob*_* K. 39

是的,有一个:__filename.

但默认情况下,webpack不会泄漏路径信息,您需要设置配置标志以获取真实文件名而不是mock("/index.js").

// /home/project/webpack.config.js
module.exports = {
  context: __dirname,
  node: {
    __filename: true
  }
}
Run Code Online (Sandbox Code Playgroud)

您可以使用__filename获取相对于context选项的当前文件名:

// in /home/project/dir/file.js
console.log(__filename);
// => logs "dir/file.js"
Run Code Online (Sandbox Code Playgroud)

文件名仅嵌入到使用的模块中__filename.因此,您不必担心路径会从其他模块中泄露出来.

  • 在2017年仍然相关:当目标是'umd`时,我无法让它工作,所以如果你正在寻找一个答案,让`__dirname`和`__filename`与webpack一起使用'umd`版本,这个答案可能不会帮到你. (2认同)

P-A*_*P-A 5

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

node : {
   __filename: true,
   __dirname: true,
},
Run Code Online (Sandbox Code Playgroud)

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


ily*_*lya 5

尝试webpack.DefinePlugin使用webpack.DefinePlugin.runtimeValue. 它给出实数常量,可以在 ES6import和require().

网络包配置:

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('.'))}'`
        }, []
    )
})
Run Code Online (Sandbox Code Playgroud)

源文件:

// require "<filename>.html" from "<filename>.js"
const html = require(`./${__NAME}.html`)
Run Code Online (Sandbox Code Playgroud)

  • 这很棒!该功能尚未记录,但已添加到 https://github.com/webpack/webpack/pull/6793 (2认同)