How to include a CSS from bower_components using webpack dev server?

∥☆過路亽.° 提交于 2019-12-25 09:29:39

问题


I am loading a fe library using bower which is situated in folder bower_components.

In public folder I have an html page which should contain a reference to the fe library.

Using the following code I get 404 when loading owfont-regular.css

How to load the css file correctly in webpack dev server?

<body>
    <div id="root"></div>
    <script src="/assets/bundle.js"></script>
    <link href="/assets/bower_components/owfont/css/owfont-regular.css" rel="stylesheet" type="text/css">
</body>



const path = require('path')
const webpack = require('webpack')

module.exports = {
  entry: {
    index: './src/index.js'
  },
  output: {
    path: path.resolve(__dirname, 'public'),
    publicPath: '/assets/', // virtual
    filename: 'bundle.js'
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin()
  ],
  devServer: {
    contentBase: path.resolve(__dirname, 'public'),
    publicPath: '/assets/', // virtual
    port: 8080,
    hot: true,
    inline: true
  },
  devtool: 'source-map',
  // devtool: 'eval-source-map',
  module: {
    loaders: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        query: {
          plugins: ['recharts'],
          presets: ['es2015']
        }
      }
    ]
  }
}

回答1:


dear firstly you should add a css loader, you can install it via npm as the follow commands

npm install style-loader css-loader --save-dev

and then add this loader to webpack.config, and then you can import your css file in your project any where, if you use react.js for example you can add it as:
import style from '/assets/bower_components/owfont/css/owfont-regular.css'

module: {
  loaders: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        query: {
          plugins: ['recharts'],
          presets: ['es2015']
        }
      },
      {
         test: /\.css$/, 
         loader: "style-loader!css-loader"
      }
   ]
 } 


来源:https://stackoverflow.com/questions/44093895/how-to-include-a-css-from-bower-components-using-webpack-dev-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!