How do I get a module path? I'm creating a module in Drupal 8 and I need to define a relative path to mymodule to pass it on a JavaScript file like this.

$scope.getPlatformIcon = function (_platform) {
     var modulePath = "/modules/mymodule"
     switch (_platform) {
         case "youtube":
         case "twitter":
         case "instagram":
         case "facebook":
             return modulePath+"/img/"+_platform+".png";
     }
     return false;
};


In Drupal 7 I could use the following.

var modulePath = Drupal.settings.mymodule.basePath;


For the Drupal 8 root directory, I could use the following.

drupalSettings.path.baseUrl


I didn't find how to get the module path.

How can I do it with Drupal 8?
To answer the original question (how do I get a module path), and not taking into account the javascript attachment part here is OO friendly solution (without showing the dependency injection itself):

$module_handler = \Drupal::service('module_handler');
$module_path = $module_handler-&gt;getModule('my_module')-&gt;getPath();


This will give you back the following (of course also depends on how your directory structure looks like)

"modules/custom/my_module"


drupal_get_path is indeed faster to write. However, it calls the same service above statically which makes your code unable to unit test (also not to mention the dependencies of your class are not visible).
Long story short: if you choose to make things Quick&amp;Dirty go for drupal_get_path any other cases use the right service yourself with a proper dependency injection.