Relative paths with fetch in Javascript

前端 未结 2 942
一生所求
一生所求 2020-12-03 03:00

I was surprised by an experience with relative paths in Javascript today. I’ve boiled down the situation to the following:

Suppose you have a directory structure lik

2条回答
  •  无人及你
    2020-12-03 03:10

    This is not exactly a recommendation since it relies on a number of things that aren't guaranteed to work everywhere or to continue to work into the future, however it works for me in the places I need it to and it might help you.

    const getRunningScript = () => {
        return decodeURI(new Error().stack.match(/([^ \n\(@])*([a-z]*:\/\/\/?)*?[a-z0-9\/\\]*\.js/ig)[0])
    }
    
    fetch(getRunningScript() + "/../config.json")
      .then(req => req.json())
      .then(config => {
        // code
      })

提交回复
热议问题