Reputation: 2578
I'm using Laravel-mix and Webpack to combine and control scripts for a site.
I'm my main app.js
I have these lines:
var jQuery = require( 'jquery' );
require( './vendor/polyfill-library.min.js' );
require( './vendor/polyfill-init.js' ); // which is using jQuery
In polyfill-init.js
I'm doing this: jQuery( document ).ready( ...
. That results in this error:
Uncaught ReferenceError: jQuery is not defined
I also get this error if I try and mix it together using Laravel-mix, by adding this to my webpack.mix.js:
mix.js( [
'resources/js/app.js',
'resources/js/vendor/polyfill-library.min.js',
'resources/js/vendor/polyfill-init.js',
], 'assets/js/app.js')
I assume the error is because Webpack keeps the required/imported scripts in seperate namespaces/environments, so no conflicts occur. And that's all fine and dandy, - but I don't know how to combine two required/imported scripts, so they're using the same namespace/environment.
... If I copy all the code into app.js
(instead of requiring it), then it works, but it's not pretty. Not pretty at all.
I looked at Webpack's documentation to see if there's a way to define a dependency for an imported/a required script, but either it's not there; or I'm not getting it.
I also looked at the 7 billion ways that this post suggest that I'd do it, - but I'm trying to figure out how Webpack/Laravel-mix want me to do it.
So my question is... Are there a way that I can do something like this:
var jQuery = require( 'jquery' );
require( './vendor/polyfill-library.min.js' );
require( './vendor/polyfill-init.js' ); // which is using jQuery
... and let Webpack know, that polyfill-init
can use jQuery
?
Upvotes: 3
Views: 182
Reputation: 357
You can use provideplugin:
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
})
]
Upvotes: 4
Reputation: 2841
U should externalize JQuery from the webpack.
index.html
<script
src="https://code.jquery.com/jquery-3.1.0.js"
integrity="sha256-slogkvB1K3VOkzAI8QITxV3VzpOnkeNVsKvtkYLMjfk="
crossorigin="anonymous">
</script>
webpack.config.js
module.exports = {
//...
externals: {
jquery: 'jQuery'
}
};
polyfill-init.js
import $ from 'jquery';
Refer more details here https://webpack.js.org/configuration/externals/
Upvotes: 0
Reputation: 538
Try window.jQuery = require( 'jquery' );
polyfill-init.js probably looks for jQuery in global scope while the var jQuery is only available in the local scope of this module.
Upvotes: 2