0

I would like to create a single-page web app where the user can change the CSS theme. I'm using Webpack.

Here is the html with two buttons for the tests:

<button id="dark">Dark</button>
<button id="light">Light</button>

Here is my JS file:

import './assets/css/style.css';

document.getElementById('dark').addEventListener('click', () => {
    import './assets/css/themes/dark.css';
})

document.getElementById('light').addEventListener('click', () => {
    import './assets/css/themes/light.css';
})

Webpack returns the following error

ERROR in ./src/index.js 5:4
Module parse failed: 'import' and 'export' may only appear at the top level (5:4)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| 
| document.getElementById('dark').addEventListener('click', () => {
>     import './assets/css/themes/dark.css';
| })

I already read the following ressources:

But the solutions are not suited for my issue. I understand that I can't import somewhere else than top level. But I don't understand how to load css dynamicaly with Webpack. Should I copy the CSS themes in the dist folder and write my own JS code to load apply the CSS?

Fifi
  • 3,360
  • 2
  • 27
  • 53

0 Answers0