如何在搭载Vue v3的Nuxt.js v2.14项目中导入Bootstrap v5的JS与CSS?
Nuxt 2.14 导入纯Bootstrap的实现步骤
- 方式1:通过npm包安装(推荐新手使用)
- 执行安装命令,安装Bootstrap及对应依赖:
- 若使用兼容Nuxt2的稳定Bootstrap 4版本,执行:
npm install bootstrap@4.6.2 jquery popper.js - 若需要使用Bootstrap 5版本,执行:
npm install bootstrap@5 @popperjs/core
- 若使用兼容Nuxt2的稳定Bootstrap 4版本,执行:
- 修改根目录下的
nuxt.config.js配置,全局引入CSS、配置JS加载规则:// nuxt.config.js 核心配置片段 export default { // 全局引入Bootstrap CSS css: [ 'bootstrap/dist/css/bootstrap.min.css' ], // 配置第三方依赖打包规则 build: { vendor: ['jquery', 'popper.js', 'bootstrap'] }, // 配置客户端专属插件,避免SSR阶段报错 plugins: [ { src: '~/plugins/bootstrap.js', mode: 'client' } ] } - 创建插件文件:如果根目录下没有
plugins文件夹,先手动新建该文件夹,再在其中创建bootstrap.js文件,写入以下内容:- Bootstrap 4版本使用的文件内容:
// plugins/bootstrap.js(Bootstrap 4用) import $ from 'jquery' window.$ = window.jQuery = $ import Popper from 'popper.js' window.Popper = Popper import 'bootstrap/dist/js/bootstrap.min.js' - Bootstrap 5版本使用的文件内容:
// plugins/bootstrap.js(Bootstrap 5用) import '@popperjs/core' import 'bootstrap/dist/js/bootstrap.bundle.min.js'
- Bootstrap 4版本使用的文件内容:
- 验证效果:重启本地开发服务
npm run dev,在任意页面写入测试代码:
按钮显示默认Bootstrap样式、点击下拉可正常展开,即为配置成功。<!-- 测试CSS样式 --> <button class="btn btn-primary">测试按钮</button> <!-- 测试JS交互 --> <div class="dropdown mt-2"> <button class="btn btn-secondary dropdown-toggle" type="button" data-toggle="dropdown"> 下拉测试 </button> <div class="dropdown-menu"> <a class="dropdown-item" href="#">选项1</a> <a class="dropdown-item" href="#">选项2</a> </div> </div>
- 执行安装命令,安装Bootstrap及对应依赖:
- 方式2:使用本地静态文件引入
- 将提前下载好的Bootstrap相关文件(css、js、对应依赖文件)放入项目的
static目录下,例如存放路径为static/bootstrap/ - 修改
nuxt.config.js的head配置,直接引入静态资源:// nuxt.config.js 核心配置片段 export default { head: { link: [ { rel: 'stylesheet', href: '/bootstrap/css/bootstrap.min.css' } ], script: [ { src: '/bootstrap/js/jquery.min.js' }, { src: '/bootstrap/js/popper.min.js' }, { src: '/bootstrap/js/bootstrap.min.js' } ] } }
- 将提前下载好的Bootstrap相关文件(css、js、对应依赖文件)放入项目的
注意:Bootstrap的JS组件依赖浏览器专属的window对象,所有涉及JS引入的配置必须确保仅在客户端加载,否则会触发SSR阶段的运行报错。
内容的提问来源于stack exchange,提问作者Tadas V.
相关产品推荐
相关产品推荐

