问题
i am having problem with implementing jquery 3rd party plugins in symfony webpack encore. so far i have several .js files with varous logic, and also some scripts inside twig files that execute some of js.
this is app.js :
var $ = require('jquery');
global.$ = global.jQuery = global.jquery = $;
require('jquery-validation');
webpack compiles, but when i execute program i get:
$(...).validate is not a function
webpack.config.js is straightforward:
var Encore = require('@symfony/webpack-encore');
Encore
// directory where compiled assets will be stored
.setOutputPath('public/build/')
// public path used by the web server to access the output path
.setPublicPath('/build')
.setManifestKeyPrefix('build/')
.addEntry('base', './assets/js/base.js')
.splitEntryChunks()
.enableSingleRuntimeChunk()
;
module.exports = Encore.getWebpackConfig();
package.json:
"jquery": "^3.3.1",
"jquery-validation": "^1.18.0",
"jquery-datetimepicker": "^2.5.20",
update: jquery-datetimepicker is working fine, but jquery-validation is not!
回答1:
solution: update webpack.config.js with alias information, so that every jquery 3rd party plugin uses same jquery
var path = require('path');
Encore
.addAliases({
'jquery': path.join(__dirname, 'node_modules/jquery/src/jquery')
})
回答2:
from: https://symfony.com/doc/current/frontend/encore/legacy-apps.html
jQuery Plugins and Legacy Applications
Inside Webpack, when you require a module, it does not (usually) set a global variable. Instead, it just returns a value:
// this loads jquery, but does *not* set a global $ or jQuery variable
const $ = require('jquery');
...
Fixing jQuery Plugins that Expect jQuery to be Global
jQuery plugins often expect that jQuery is already available via the $ or jQuery global variables. To fix this, call autoProvidejQuery() from your webpack.config.js file:
Encore
// ...
.autoProvidejQuery() // add this line into your webpack.config.js file
;
Accessing jQuery from outside of Webpack JavaScript Files
If your code needs access to $ or jQuery and you are inside of a file that's processed by Webpack/Encore, you should remove any "$ is not defined" errors by requiring jQuery: var $ = require('jquery').
But if you also need to provide access to $ and jQuery variables outside of JavaScript files processed by Webpack (e.g. JavaScript that still lives in your templates), you need to manually set these as global variables in some JavaScript file that is loaded before your legacy code.
For example, in your app.js file that's processed by Webpack and loaded on every page, add:
// require jQuery normally
const $ = require('jquery');
+ // create global $ and jQuery variables
+ global.$ = global.jQuery = $;
来源:https://stackoverflow.com/questions/53359791/webpack-symfony-encore-jquery-third-party-plugins