Webpack如何引入Bootstrap的.js和.css文件?

22

我正在使用React、Bootstrap和Webpack构建应用程序,使用Babel处理ES6语法。

但是我无法将boostrap.js和bootstrap.css导入到我的应用程序中。

我的webpack.config.js文件如下:

    var webpack = require('webpack'),
  HtmlWebpackPlugin = require('html-webpack-plugin'),
  path = require('path'),
  srcPath = path.join(__dirname, 'src');

module.exports = {
  target: 'web',
  cache: true,
  entry: {
    module: path.join(srcPath, 'module.js'),
    common: ['react', 'react-router', 'alt']
  },
  resolve: {
    root: srcPath,
    extensions: ['', '.js'],
    modulesDirectories: ['node_modules', 'src']
  },
  output: {
    path: path.join(__dirname, 'tmp'),
    publicPath: '',
    filename: '[name].js',
    library: ['Example', '[name]'],
    pathInfo: true
  },

  module: {
    loaders: [
      {test: /\.js?$/, exclude: /node_modules/, loader: 'babel?cacheDirectory'}
    ]
  },
  plugins: [
    new webpack.optimize.CommonsChunkPlugin('common', 'common.js'),
    new HtmlWebpackPlugin({
      inject: true,
      template: 'src/index.html'
    }),
    new webpack.ProvidePlugin({
           $: "jquery",
           jQuery: "jquery"
    }),
    new webpack.ProvidePlugin({
           bootstrap: "bootstrap.css",
    }),
    new webpack.NoErrorsPlugin()
  ],

  debug: true,
  devtool: 'eval-cheap-module-source-map',
  devServer: {
    contentBase: './tmp',
    historyApiFallback: true
  }
};

在我的.js文件(React组件)中,我想做:import 'bootstrap'。但是CSS没有被实现。.js导入运作良好。

那么,我该如何导入Bootstrap或配置webpack?


我成功地按照这里找到的指南完成了它:http://blog.theodybrothers.com/2015/07/how-to-use-bootstrap-css-only-and.html 这个指南只帮助加载bootstrap.css,但这正是我所需要的。 - Yuri Dogandjiev
2个回答

8

您需要执行以下步骤才能使其正常工作:

  1. 在您的webpack配置文件的resolve部分中,确保包含了Bootstrap CSS文件的路径。

例如:

var bootstrapPath = path.join(
    __dirname,
    'development/bower_components/bootstrap/dist/css'
);

然后在你的webpack配置对象中:

resolve: {
    alias: {
        jquery: path.join(__dirname, 'development/bower_components/jquery/jquery')
    },
    root: srcPath,
    extensions: ['', '.js', '.css'],
    modulesDirectories: ['node_modules', srcPath, commonStylePath, bootstrapPath]
}
  1. 确保你已经安装了style loader和css loader。例如: loaders:[{ test: /\.css$/, loader: "style-loader!css-loader" }]
  2. 在你的js文件中使用它: require('bootstrap.min.css');

0

只需使用less插件并正确声明它们即可...

// Webpack file
{
  test: /\.less$/,
  loader: "style-loader!css-loader!less-loader"
},
// I have to add the regex .*? because some of the files are named like... fontello.woff2?952370
{
  test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)(\?.*)?$/,
  loader: 'url?limit=50000'
}

// Less file
@import '~bootstrap/less/bootstrap';

我还在继续编写JS代码,不过很快会告诉你的 :-)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接