Electron: How to import or include CSS installed using npm package manager in our index.html?

Viewed 2115

During development there is node_modules folder in the root directory of our Electron project which contains all packages we have installed. So, during development we can write something like this to import our CSS file to our webpage:

<link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.css">

How can we include CSS for a project which is intended to be packaged and distributed without node_modules?

Edit: After some research I found out that node_modules are not meant to be used this way (see this). Still, if something changes in future please feel free to add your answer.

Link to the repository I started with: https://github.com/electron/electron-quick-start

1 Answers

After doing some research, and since you are using the original boilerplate, I installed it and did the same as you said. Since your main issue is importing the style sheets in production when packaged, you can use electron-packager to build your app which will result in the latter being independent of the node module you installed during development. You can do these steps for testing:

  1. npm i
  2. npm i bootstrap --save
  3. added <link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.css"> in the head
  4. added <button type="button" class="btn btn-danger">Button</button> in the body for the sake of testing
  5. npm install electron-packager --save

  6. Add "build": "electron-packager . --asar" to your scripts in package.json

  7. npm run build

Then you can see that Bootstrap is being used normally.

Related