I am new to Laravel and following Laracast tutorials for Laravel 5.4
I read about Laravel mix and how we can compile our assets using Webpack Laravel Mix tool. So I tried adding a JavaScript Package
1- Installed AlertifyJS using npm.
2- Added require('alertifyjs')
in resources\assets\js\bootstrap.js
3- Executed npm run dev
. Assets were compiled to public\js\app.js
, where I can see alertifyjs code by finding alertify keyword.
I used alertify code like below in resources\assets\js\app.js:
`$(document).ready(function(){
$('.run').on('click' , function(event){
alertify.alert("This is an alert dialog.", function(){
alertify.message('OK');
});
});
});`
View File:
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading text-center"><h2>THIS WILL BE THE HOME PAGE<h2></div>
<div class="panel-body text-center">
Home Page Content Goes Here!
</div>
<button class="run">Show Alert</button>
</div>
</div>
</div>
</div>
@endsection
Problem: When I click on button Show Alert ,
alertify is not defined errors is logged to console. Am I missing something while compiling assets?
You need to require alertify in your app.js
, where you're actually using it. Webpack keeps each file as a module, just puts them together in one file (the bundle). But you're expecting it to be available globally, which is not a good idea and modules that do depend on globals (like jQuery plugins) are referred to as legacy modules in the official webpack docs. Have a look at Shimming for more details on such legacy modules.
Anyway, that is not the case for you, but just keep in mind that modules you install with npm should always be required in the file you're actually using them. Modules have their own scope, it's not just putting the files together when you require them. If this concept of modules is new to you or you'd like to understand it better you should read Node.js Modules, because this is heavily used in JavaScript.
Your resources\assets\js\app.js
needs to be changed to:
const alertify = require('alertifyjs');
$(document).ready(function(){
$('.run').on('click' , function(event){
alertify.alert("This is an alert dialog.", function(){
alertify.message('OK');
});
});
});
来源:https://stackoverflow.com/questions/42584961/installing-js-packages-using-npm-and-compiling-with-webpack-laravel-mix