先来复制一些 bootstrap 的代码片断。

src/index.html

注意,本节使用的是 bootstrap 3,因为目前写这篇文章时,bootstrap 4 还没出正式版,所以我们用 bootstrap 3。

效果如下:

图标没显示出来,css 也没加载到,js 更是不可用。

要加载 bootstrap 框架,主要是使用这个这个 loader:。

现在主要通过查看它的官方文档,来了解如何安装和使用它。

安装。

  1. $ npm install resolve-url-loader url-loader --save-dev

接下来,我们来看如何使用 bootstrap-loader 这个 loader。

在项目根目录下,创建 .bootstraprc 文件,其内容拷贝于下面这个链接的内容。

这个内容是官方提供的,主要存放的是 bootstrap 的配置选项,就是通过它来控制一些 bootstrap 的功能。

webpack.bootstrap.config.js

这个内容是官方提供的,主要存放的是关于 bootstrap 的 webpack 配置的内容,它包含生产环境和开发环境的配置。

现在我们把刚才下载的 webpack.bootstrap.config.js 文件利用起来。

webpack.config.js

  1. const bootstrapEntryPoints = require('./webpack.bootstrap.config')
  2. var bootstrapConfig = isProd ? bootstrapEntryPoints.prod : bootstrapEntryPoints.dev;
  3. module.exports = {
  4. entry: {
  5. "app.bundle": './src/app.js',
  6. "contact": './src/contact.js',
  7. },
  8. ...
  9. }

运行一下 ,发现报了个错。

15. 加载和打包 Twitter Bootstrap 框架 - 图1

字体文件没处理好。

通过查看 bootstrap-loader 官方的 readme 文档,加上下面几行 loader 的配置,可解决问题。

再次运行 npm run dev,发现下面的页面效果。

字体图标和 css 都没问题了,但是 js 没加载好,点击按钮没有弹出模态框。

查看报错:

15. 加载和打包 Twitter Bootstrap 框架 - 图2

webpack.config.js 配置文件的 loader 部分加上下面这行:

  1. { test:/bootstrap-sass[\/\\]assets[\/\\]javascripts[\/\\]/, loader: 'imports-loader?jQuery=jquery' },

然后在终端上执行下面的命令:

  1. $ npm install --save-dev imports-loader jquery

即可解决问题。

效果:

点击按钮后,模态框弹出来了,good!

我们运行一下 npm run prod 命令,没啥问题,目录结构是下面这样的:

比较乱,如果能把 css,js,字体文件分开成各个目录就蛮好的。

我们来改一下配置:

webpack.config.js

  1. // css 文件放到 css 目录中
  2. new ExtractTextPlugin({
  3. filename: '[name].css',
  4. disable: !isProd,
  5. publicPath: 'css/'
  6. }),
  7. // 字体文件都放到 fonts 目录中
  8. { test: /\.(woff2?|svg)$/, loader: 'url-loader?limit=10000&name=[name].[ext]&outputPath=fonts/' },
  9. { test: /\.(ttf|eot)$/, loader: 'file-loader?name=[name].[ext]&outputPath=fonts/' },

运行 npm run prod 之后,dist 的目录结构如下:

  1. ├── bootstrap.0cc9d9267f555d83ccb0.js
  2. ├── contact.0cc9d9267f555d83ccb0.js
  3. ├── contact.html
  4. ├── css
  5. ├── app.bundle.css
  6. └── bootstrap.css
  7. ├── fonts
  8. ├── glyphicons-halflings-regular.eot
  9. ├── glyphicons-halflings-regular.svg
  10. ├── glyphicons-halflings-regular.ttf
  11. ├── glyphicons-halflings-regular.woff
  12. ├── glyphicons-halflings-regular.woff2
  13. └── money-bag.svg
  14. ├── images
  15. ├── glyphicons-halflings-regular.svg
  16. └── money-bag.svg

这样目录结构就比刚才清晰多了。

先说这么多吧。