Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

reactjs - Webpack import bootstrap .js and .css

I am building an app using react, bootstrap and webpack using es6 with babel.

But I can't import boostrap.js and bootstrap.css to my app.

My 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
  }
};

So in my .js files (react components) I am trying to do: import 'bootstrap'. But the css is not being implemented. The .js imports works well.

So how can I import boostrap or configure webpack?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to do the following things to make it work:

  1. In your webpack config file, resolve section, make sure your bootstrap css file path is included.

As an example:

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

Then in your webpack config object:

resolve: {
    alias: {
        jquery: path.join(__dirname, 'development/bower_components/jquery/jquery')
    },
    root: srcPath,
    extensions: ['', '.js', '.css'],
    modulesDirectories: ['node_modules', srcPath, commonStylePath, bootstrapPath]
}
  1. Make sure you have style loader and css loader. E.g. loaders:[{ test: /.css$/, loader: "style-loader!css-loader" }]
  2. Use it in your js file require('bootstrap.min.css');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...