I’m creating a React component for Dash, and would like to include a CSS loader into the webpack configuration for the component, which will allow me to enforce some simple CSS rules for behaviour onto the components without necessitating their inclusion in Dash directly.
Is what I’d like to do possible, and if so, what are the best practices for doing this?
After some tinkering, I have managed to get CSS modules loaded into a Dash component. It does require completely overriding the webpack configuration from dash-components-archetype.
Copy the webpack config directory from node_modules/dash-components-archetype/config to a config folder in your root directory.
In config/webpack/partials add a new file, styles.js, and add the following content:
'use strict';
var path = require('path');
var partial = require('webpack-partial').default;
var ROOT = process.cwd();
var SRC = path.join(ROOT, 'src');
module.exports = function (config) {
return partial(config, {
module: {
loaders: [
{
test: /\.css/,
include: [SRC],
/*
* Use require.resolve to get a deterministic path
* and avoid webpack's magick loader resolution
*/
loaders: [require.resolve('style-loader'), require.resolve('css-loader')]
}
]
}
});
};
Then, all that’s left to do is install the loaders, with npm install --save style-loader css-loader and override the builder commands in package.json to use the local webpack config (take a look at node_modules/dash-components-archetype/package.json and builder help for clues).
I’d appreciate any feedback concerning best practices for the above, but for the interim it works.
The relative_package_path refers to the location of the CSS inside the distribution folder (e.g. https://github.com/plotly/dash-core-components/blob/master/dash_core_components/rc-slider%406.1.2.css) and this path is used if the user has set app.css.config.serve_locally=True. If serve_locally=False, then the CSS from the external_url path is used (served from the unpkg CDN which serves packages from NPM).
Using a CSS loader seems like a better way to do this. I wonder if we could do something similar with images as well.
I believe that url-loader (https://github.com/webpack-contrib/url-loader) can be used for including images in React, and also works for images specified in url() within CSS. You can find a great discussion about it here