Roots Discourse

Importing .css via JS - webpack test issue?


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 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:

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:

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:

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

Will just add another solution as a reference: you can also import CSS for any lib separately in a relevant scss. No need to include everything via JS if you want to separate css/js clearly. An example for Magnific Popup lib:

  1. Adding external library: in your theme root yarn add magnific-popup

  2. In your relevant stylesheet scss below @import "./autoload/**/*";:
    @import "~magnific-popup/dist/magnific-popup.css";

  3. In your relevant script file on top:
    import 'magnific-popup/dist/jquery.magnific-popup.js';