首页 文章

Webpack导入bootstrap .js和.css

提问于
浏览
21

我正在使用带有babel的es6使用react,bootstrap和webpack来构建应用程序 .

但是我无法将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文件(反应组件)中我试图做:import'bootstrap' . 但是css没有实施 . .js导入效果很好 .

那么如何导入boostrap或配置webpack呢?

2 回答

  • 0

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

    • 在您的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]
    }
    
    • 确保你有样式加载器和css加载器 . 例如 . loaders:[{ test: /\.css$/, loader: "style-loader!css-loader" }]

    • 在js文件中使用它 require('bootstrap.min.css');

  • 8

    只需使用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,但我很快就会告诉你:-)

相关问题