简体   繁体   中英

Laravel. Is webpack.mix.php the only way to run Javascript?

I was trying to add a simple character count to a textarea and it took me a day to get it working. I wanted to post what I learned and ask for clarification from any helpful users out there.

Laravel was not running javascript until I uploaded the script into ProjectRoot/resources/js/app.js .

var maxLength = 100;
$('textarea').keyup(function() {
  var length = $(this).val().length;
  var length = maxLength-length;
  $('#chars').text(length);
});

Once the code is there I ran npm run dev (I have installed npm at this piont) and only THEN did the javascript run. The code is transferred into an app.js file in the ProjectRoot/public/js/app.js (which is a massive file where I couldn't find my code) directiory. I assume, and correct me if I'm wrong, this means npm run dev "converts" /"transfers" /"compiles" (what's the right word here?) the javascript to the laravel webmix system. This is where my knowledge and problem solving skills have puttered out.

Articles like this and this make it sound like I can just drop javascript into any xxx.blade.php file. Some other angles that did NOT work:

  • importing .js files in the public/js directiory. No luck.
  • <script src="{{asset('js/count.js')}}"></script> didn't work when I tried it in app.blade.php or the blade file with text area itself.
  • including *@section('script')* didn't work either.

I'm getting the classic Uncaught ReferenceError: $ is not defined in the chrome inspector console, but the countdown works so I I'm just not sure what's going on.

Can I run javascript inline in my xxx.blade.php with Laravel?

in your blade file, where you want to use your script:

@push('js')
<script>
var maxLength = 100;
$('textarea').keyup(function() {
  var length = $(this).val().length;
  var length = maxLength-length;
  $('#chars').text(length);
});
</script>
@endpush

and in your app.blade.php (your main blade where you include all the js/css files)

@stack('js')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM