【问题标题】:Current file path in webpackwebpack 中的当前文件路径
【发布时间】:2014-08-28 16:40:08
【问题描述】:

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

define(['module'], function (module) {
    console.log(module.uri)
});

【问题讨论】:

    标签: webpack


    【解决方案1】:

    是的,有一个:__filename

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

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

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

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

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

    【讨论】:

    • 在 2017 年仍然相关:当目标是 umd 时,我无法让它工作,所以如果你正在寻找关于让 __dirname__filename 与 webpack 一起工作的答案umd 构建,这个答案可能对你没有帮助。
    • 这对性能有任何影响或任何其他已知的副作用吗?这样做有缺点吗?
    • 只是添加。您需要在每次更新其配置时重新启动 webpack 服务器以使更新生效。
    【解决方案2】:

    为了获取文件名和目录名,我将其添加到 web pack 配置中

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

    将上下文设置为 __dirname 搞砸了我的 webpack 配置,因为我的 webpackconfig 没有放在 root 中,但路径是这样设置的

    【讨论】:

      【解决方案3】:

      试试webpack.DefinePluginwebpack.DefinePlugin.runtimeValue。 它给出了实常数,可以在 ES6 importrequire() 中使用。

      Webpack 配置:

      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('.'))}'`
              }, []
          )
      })
      

      源文件:

      // require "<filename>.html" from "<filename>.js"
      const html = require(`./${__NAME}.html`)
      

      【讨论】:

      • 这太棒了!该功能尚未记录,但已添加到 github.com/webpack/webpack/pull/6793
      • 我不明白这个 sn-p 与问题有何关系。请阐明更多的光。谢谢。
      • 让我们拥有report-1.0.0.js 和report-1.0.0.html。现在您可以使用 require(./${__NAME}.html) 将 html 包含到脚本中
      猜你喜欢
      • 1970-01-01
      • 2019-08-16
      • 2021-11-02
      • 1970-01-01
      • 1970-01-01
      • 2010-11-20
      • 1970-01-01
      • 1970-01-01
      • 2019-02-01
      相关资源
      最近更新 更多