迁移到 Webpack 3 后,我注意到 jQuery 包含的工作并不像我预期的那样。
我的模板结构有 core/_global.html 根模板,我在其中渲染常见的 js 和 css 资源,例如:
<head>
{% render_bundle 'global' 'css' %}
{% block stylesheets %}{% endblock %}
{% render_bundle 'global' 'js' %}
{% block header_javascripts %}{% endblock %}
</head>
二级模板扩展了根模板并向html添加了额外的js和css:
{% extends "core/_global.html" %}
{% load render_bundle from webpack_loader %}
{% block stylesheets %}
{% render_bundle 'accounts/register' 'css' %}
{% endblock %}
{% block javascripts %}
{% render_bundle 'accounts/register' 'js' %}
{% endblock %}
在以前版本的 Webpack 中,在 global.js 的开头,我有:
import 'expose?jQuery!expose?$!jquery'
删除此行并将 webpack.config 更改为:
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
}),
我有以下问题 - 每个渲染文件、global.js 和 register.js 都包含 jQuery。结果每个文件的大小增加了appr。 300 KB。
我希望 jQuery 应该只加载一次,并且应该可以在 global.js 和 register.js 中访问
是否有任何解决方法允许以这种方式包含 jQuery 并可以从不同的 js 文件访问它?我应该重构模板的结构吗?谢谢。
最佳答案
我找到了答案here .
基本上,在较新版本的 Webpack 中,我可以使用附加插件 CommonsChunkPlugin。取决于它从所有 block 中提取所有常见 js 和 css 到单独 block 中的设置。该 block 稍后可以在 html 页面上使用。
什么对我的案例有帮助:
webpack.config.js
new webpack.optimize.CommonsChunkPlugin({
name: 'commons',
filename: 'commons.js',
minChunks: 2
}),
global.html 页面
<script type="text/javascript" src="{% static "bundles/commons.js" %}"></script>
关于jquery - 网页包 3.1。 jQuery被多次添加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46770855/