machete
machete

Reputation: 1157

Define css files within webpack.config.js

I am building something like a static website generator that uses webpack to build the project and create a bundle with it.

In this project, a user is able to specify custom css files. I want those css files to be bundled with the final result. The issue is, that I do not have the paths to those css files available during development, so I can't do import 'some-asset-file-provided-by-the-user.css' in the javascript code that is going to be bundled. But I have them available when calling webpack.compile(config).

I am looking for a way to inject those css files into the bundle. So far I tried various ways, such as:

const stylesheet = 'some-asset-file-provided-by-the-user.css'
require(stylesheet)

Which did not work, probably because webpack is not able to deal with this "dynamic" require. Then I used the webpack define plugin for this

/* webpack.config.js */
new webpack.DefinePlugin({
  stylesheet: 'some-asset-file-provided-by-the-user.css'
}),

/* app.js */
require(stylesheet) // should be replaced by the webpack define plugin with 'some-asset-file-provided-by-the-user.css'

which also did not work. I also tried to find a way to do something like this:

{
  test: /\.css$/,
  loader: ExtractTextPlugin.extract(Object.assign({
    fallback: 'style-loader',
    use: [
      {
        loader: 'css-loader',
        options: {
          useFiles: ['file-a.css', 'file-b.css']
        }
      }
    ]
  }, extractTextPluginOptions))
    // Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
},

which also failed because apparently neither style-loader nor css-loader support this type of interaction.

How can I solve this? I am open to writing a plugin for this, but I'd rather use something existing.

Upvotes: 1

Views: 371

Answers (1)

Michael Jungo
Michael Jungo

Reputation: 32972

The simplest way to include the CSS is by adding it to your entry point. To make this easier, you should use an array as entry point even if it's just a single file, so you can simply push the CSS.

For example:

entry: {
  app: ['./src/index.js'],
  // Other entries
},

In your compile script you add it to entry.app before passing it to webpack.

config.entry.app.push('./user.css');
const compiler = webpack(config);

Upvotes: 2

Related Questions