首页 > 解决方案 > Bootstrap 5 与 Grunt 捆绑和优化 js

问题描述

我已经成功地使用 Grunt 将 bootstrap 5 scss 捆绑到一个文件中。我已经设置好了,所以我可以根据项目的需要添加和删除组件 scss 以进行优化。

我现在正在尝试对 js 做同样的事情。

我正在使用 grunt-contrib-uglify 完成以下任务:

uglify: {
    site: {
        options: {
            sourcemap: false
        },
        files: {
            'example/static/example/assets/js/example.min.js': [

                // popper bs5 dependency
                'node_modules/@popperjs/core/dist/umd/popper.js',

                // bootstrap 5 core js
                'node_modules/bootstrap/js/dist/dom/data.js',
                'node_modules/bootstrap/js/dist/dom/event-handler.js',
                'node_modules/bootstrap/js/dist/dom/manipulator.js',
                'node_modules/bootstrap/js/dist/dom/selector-engine.js',

                // component js
                // note ordering of components can be important
                // eg. popover relies on tooltip, therefore tooltip must therefore go first
                'node_modules/bootstrap/js/dist/base-component.js',
                'node_modules/bootstrap/js/dist/alert.js',
                'node_modules/bootstrap/js/dist/button.js',
                'node_modules/bootstrap/js/dist/carousel.js',
                'node_modules/bootstrap/js/dist/collapse.js',
                'node_modules/bootstrap/js/dist/dropdown.js',
                'node_modules/bootstrap/js/dist/modal.js',
                'node_modules/bootstrap/js/dist/offcanvas.js',
                'node_modules/bootstrap/js/dist/scrollspy.js',
                'node_modules/bootstrap/js/dist/tab.js',
                'node_modules/bootstrap/js/dist/toast.js',
                'node_modules/bootstrap/js/dist/tooltip.js',
                'node_modules/bootstrap/js/dist/popover.js',

                // custom js
                'example/src/js/**/*.js'
            ]
        }
    },
},

我将它包含在我的 html 中,然后在它下面有一个脚本,例如。

<script>
    var myOffcanvas = document.getElementById('offcanvasExample')
    var bsOffcanvas = new bootstrap.Offcanvas(myOffcanvas)
</script>

我得到错误:

ReferenceError:未定义引导程序

在控制台中。我从捆绑包中缺少什么来完成这项工作?我在 Github 上使用了 npm bs5 starter 作为文件的参考,例如。popper 依赖,核心 js 并在 node_modules/bootstrap/js/dist 文件夹中导入了所有其他组件文件。

Github Bootstrap 5 npm 启动器

引导程序 5.1

波普尔 2.9.2

编辑:与分布式捆绑正常工作。

标签: javascriptgruntjsbootstrap-5

解决方案


我不是超级专家,不确定问题是否足够清楚,但我不建议将 Boostrap 之类的库连接到框架外的其他 JS 文件中的单个主文件中,因为性能问题和库之间可能发生的崩溃由于定义,以及在没有构建过程的情况下更新的可能性以及您的网站可能会受到谷歌引擎的惩罚。

除此之外,如果您不打算更改原始设计模式的任何内容,Boostrap 通常已经提供.min.css并且.min.js已经压缩/缩小/丑化准备使用,如果您不打算自定义它,请避免使用解压缩文件。

对于其他自定义库或您创建的香草 JS 的其余部分,如果您想检查性能 ,您也可以使用grunt-contrib-concat ,您可以使用PageSpeed Insights结果将知道需要应用什么才能变得更好性能和优化。


推荐阅读