如何使用webpack dev服务器从bower_components中包含CSS?

时间:2017-05-21 06:37:15

标签: css webpack webpack-dev-server

我正在使用bower加载一个fe库,该文件位于文件夹bower_components

public文件夹中,我有一个html页面,其中应包含对fe库的引用。

使用以下代码,我在加载owfont-regular.css

时获得404

如何在webpack dev服务器中正确加载css文件?

<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 个答案:

答案 0 :(得分:3)

亲爱的首先你应该添加一个css加载器, 你可以通过npm安装它作为以下命令

  

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

然后将此加载器添加到webpack.config,然后您可以在项目中导入您的css文件,如果您使用react.js,例如您可以将其添加为:
来自&#39; /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"
      }
   ]
 }