Skip to content

Instantly share code, notes, and snippets.

@corinneling
Last active October 22, 2020 13:51
Show Gist options
  • Save corinneling/769c09c9b2effbe6bf13c2c4cdbe91dd to your computer and use it in GitHub Desktop.
Save corinneling/769c09c9b2effbe6bf13c2c4cdbe91dd to your computer and use it in GitHub Desktop.
How to add a npm package’s css to your site

How to add a npm package’s css to your site with webpack

style loader & css loader

  1. npm i --save-dev style-loader css-loader we have to use both of these loaders because the css-loader lets webpack parse the css and the style loader adds a <style> tag to the head of the html file so the css can be added to it
  2. Add the style-loader and css-loader to the webpack rules array (we dont need to import it into the file)
// webpack.config.js

rules: [
  {
    test: /\.css$/,
    use: ['style-loader', 'css-loader'],
  }
]
  1. import the css file into your js file
// index.js

require('whirligiggle/build/index.css');
  1. your webapck file will look like this now
// webpack.config.js

const path = require('path');

module.exports = {
  devtool: 'eval-source-map',
  mode: 'development',
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'js/[name]-[contenthash:8].js',
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
        }
      }, {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      }
    ]
  },
  plugins: []
};

Copy Webpack Plugin

  1. npm i --save-dev copy-webpack-plugin
  2. Import it into your webpack.config.js file const CopyWebpackPlugin = require(‘copy-webpack-plugin’);
  3. Create an instance of the CopyWeboack in the plugins section of webpack config
// webpack.config.js

  plugins: [
    new CopyWebpackPlugin({
      patterns: [
        { from: './node_modules/whirligiggle/build/index.css', to: './' },
      ],
    }),
  ]
  1. Add a link tag to the head of your html or html template
<!-- index.html -->

<link href="./index.css" rel="stylesheet">
  1. your webapck file will look like this now
// webpack.config.js

const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');

module.exports = {
  devtool: 'eval-source-map',
  mode: 'development',
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'js/[name]-[contenthash:8].js',
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
        }
      }
    ]
  },
  plugins: [
    new CopyWebpackPlugin({
      patterns: [
        { from: './node_modules/whirligiggle/build/index.css', to: './' },
      ],
    }),
  ]
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment