How to include js file from 'resources' folder (Laravel 5.5)

梦想与她 提交于 2019-12-11 05:08:03

问题


i used next code to include my js file

Meta::addJs('admin_js', '/resources/assets/admin_js/admin_app.js');

File exists but in console i see status 404.

If i move file to 'public' folder - all ok. But i want that this file be stored in 'resources' directory


回答1:


  1. you have to move js files to public or store into storage and make symlinks.
  2. or you need to create symlinks the resources directory to a public directory(which is not recommended).

  3. you need to use the most recommended and effective method of Laravel of using Laravel mix. Please use the link below to read about laravel mix a solution.

https://laravel.com/docs/5.6/mix

It will allow you to place your js assets into resources directory and make compressed js file in public which will be used by the setup.




回答2:


i don't know if i am late but when i needed to load js file from directories and sub directories in my view file, i did this and it worked perfectly for me. BTW i use laravel 5.7.

first of all i wrote a function that searched for any file in any given directory with this .

/**
 * Search for file and return full path.
 *
 * @param  string  $pattern
 * @return array
 */
function rglob($pattern, $flags = 0) {
    $files = glob($pattern, $flags);
    foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir) {
        $files = array_merge($files, rglob($dir.'/'.basename($pattern), $flags));
    }
    return $files;
}

the above will return a full path for each ".js" file in my "resources/view" directory. Then i made a call to the above function to copy the content of each js to a single js file (new.js) which i created in my public/js using the below function.

/**
 * Load js file from each view subdirectory into public js.
 *
 * @return void
 */
function load_js_function(){
    //call to the previous function that returns all js files in view directory
    $files = rglob(resource_path('views').'/*/*.js');
    foreach($files as $file) {
        copy($file, base_path('public/js/new.js'));
    }
}

After this i made call to the load_js_function() in my master blade layout(where i load all my css,js etc) immediately after loading the public/js/new.js, you can see below.

  <script src="{!! asset('js/new.js') !!}"></script>
  <!-- load all js from each module -->
  {{ load_js_function() }}

These solution updates the file in public as you update the content of the original file. Vote up if it works for you and comment if you have an issue implementing this, i will be glad to shed more light. cheers



来源:https://stackoverflow.com/questions/49408259/how-to-include-js-file-from-resources-folder-laravel-5-5

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!