Roots Discourse

Importing .css via JS - webpack test issue?

Hello,

I was wondering how you are supposed to include external library css files via JS in Sage?
I added the library via yarn add ol.

I created a script under /scripts/util and imported it inside home.js where it is needed, then called new Maps();. Seems it’s working without style inclusion, but with it it throws an error.

I was following https://openlayers.org/en/latest/doc/tutorials/bundle.html and when importing it says:

in ./node_modules/ol/ol.css
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
| .ol-box {
|   box-sizing: border-box;
|   border-radius: 2px;

Any tips appreciated - perhaps I have to edit webpack config in a way? Or should this be handled already, since I see a test for .css files in it.

The error is telling you what’s wrong:

You may need an appropriate loader to handle this file type.

Loaders are central to how Webpack works, so you might find it useful to read up on them: https://webpack.js.org/loaders/

The error is telling you it can’t load a CSS file because it doesn’t have a loader for CSS files. Sage comes with a loader for CSS files, but it only loads them from particular locations. You can see where that loader is defined here: https://github.com/roots/sage/blob/9a8ca10365fb8ca83a5c2714aa5f3ecbfd322034/resources/assets/build/webpack.config.js#L61-L77

As you can see, it will only load CSS files that are found in the path(s) defined in config.paths.assets. That value is defined here: https://github.com/roots/sage/blob/9a8ca10365fb8ca83a5c2714aa5f3ecbfd322034/resources/assets/build/config.js#L21

By modifying the paths it checks to include the path where your file is located, you should be able to resolve this error.

1 Like

Thanks @alwaysblank, that sure helped. Never really took time to read much about Webpack to be honest.

Was able to solve it by adding additional asset variable to build/config.js (should I be able to use an array for assets, since it did not work?:

paths: {
    root: rootPath,
    assets: path.join(rootPath, 'resources/assets'),            // <-- should be able to work as an array here but it doesn't? 
    assets_node_modules: path.join(rootPath, 'node_modules'), // <-- added this instead
    dist: path.join(rootPath, 'dist'),
  },

and within build/webpack.config.js:

{
        test: /\.css$/,
        include: [config.paths.assets, config.paths.assets_node_modules], // <-- used newly created path here