Webpack Encore - $未定义

Kri*_*fon 3 symfony twig webpack webpack-encore

我按照文档使Webpack Encore在我的项目中工作.webpack.config.js中导入的js文件工作正常,但我在页面特定的js中遇到问题:$ is not defined.

Webpack.config.js:

const Encore = require('@symfony/webpack-encore');
var webpack = require('webpack');

Encore
.setOutputPath('public/build/')
.setPublicPath('http://localhost/tharmo/public/build')
.setManifestKeyPrefix('build/')
.cleanupOutputBeforeBuild()
.enableSourceMaps(!Encore.isProduction())
.autoProvidejQuery()

.createSharedEntry('vendor', [
    './assets/js/custom.js',
    'materialize-css',
])
.addEntry('app', './assets/js/app.js')
.addEntry('statistiques', './assets/js/statistiques.js')
.addPlugin(new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery',
    'window.jQuery': 'jquery',
}))

.enableSassLoader()
;

module.exports = Encore.getWebpackConfig();
Run Code Online (Sandbox Code Playgroud)

base.html.twig:

<script src="{{ asset('build/manifest.js') }}"></script>
<script src="{{ asset('build/vendor.js') }}"></script>
<script type="text/javascript" src="{{ asset('build/app.js') }}"></script>
<script>
    $(document).ready(function () {
        getNotifications(1);
    });
</script>
Run Code Online (Sandbox Code Playgroud)

$(document).ready 不起作用.

Kri*_*fon 16

通过以下文档了解它:https://symfony.com/doc/current/frontend/encore/legacy-apps.html

我不得不在app.js中写这个:

// require jQuery normally
const $ = require('jquery');

// create global $ and jQuery variables
global.$ = global.jQuery = $;
Run Code Online (Sandbox Code Playgroud)

我从webpack.conig.js中删除了它,因为它相当于.autoProvidejQuery:

.addPlugin(new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery',
    'window.jQuery': 'jquery',
}))
Run Code Online (Sandbox Code Playgroud)

谢谢您的帮助 !


Mar*_*tin 0

您应该在 webpack.config.js 中使用output.library: "Root" //Or what name you want配置,并在入口 js 文件中执行以下操作:

从'jquery'导入$

...您的通用入口文件代码

导出{$};

你将像这样访问jquery:

根.$