C
C
coderlex2016-07-27 08:31:04
npm
coderlex, 2016-07-27 08:31:04

How to load CSS assets from NPM using Webpack?

Using Webpack, you can include resources from a non-web-accessible directory (such as node_modules). As far as I understand, this is done, for example, using the file-loader, which copies the files to the public directory and returns the url to the copied resource. But what if you need to include, for example, font-awesome, whose font paths are specified in the CSS file?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Nemiro, 2016-07-27
@coderlex

Bootstrap and Font Awesome have separate loaders: bootstrap -loader and font-awesome-loader . Simply add them to the devDependencies section of package.json . In the application initialization code, connect, for example like this:

require('bootstrap-loader');
require('font-awesome-loader');

For fonts, in webpack.config.js , write something like this:
module {
  loaders: [
    {
      test: /\.woff(.*)$/,
      loader: 'url',
      query: {
        limit: 10000,
        mimetype: 'application/font-woff',
        name: 'fonts/[name].[ext]' // путь output, куда будут скопированы файлы
      }
    },
    {
      test: /\.woff2(.*)$/,
      loader: 'url',
      query: {
        limit: 10000,
        mimetype: 'application/font-woff',
        name: 'fonts/[name].[ext]'
      }
    },
    {
      test: /\.ttf(.*)$/,
      loader: 'url',
      query: {
        limit: 10000,
        mimetype: 'application/octet-stream',
        name: 'fonts/[name].[ext]'
      }
    },
    {
      test: /\.eot(.*)$/,
      loader: 'file',
      query: {
        limit: 10000,
        name: 'fonts/[name].[ext]'
      }
    },
    {
      test: /\.svg(.*)$/,
      loader: 'url',
      query: {
        limit: 10000,
        mimetype: 'image/svg+xml',
        name: 'fonts/[name].[ext]'
      }
    }
  ]
}

If you need to extract CSS from JavaScript , you can use the extract-text-webpack-plugin .
webpack.config.js :
var extractTextPlugin = require('extract-text-webpack-plugin');
// ...
module.exports = {
  // ...
  module: {
    loaders: [
      {
        test: /\.scss$/, // для scss
        loader: extractTextPlugin.extract('style', 'css!sass')
      }
    ]
  },

  plugins: [
    new extractTextPlugin('bundle.css') // вынести css в файл bundle.css в папку output
  ]
}

You can use the copy-webpack-plugin to copy other static files .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question