简体   繁体   中英

How to reference CSS from libraries installed via npm?

So for example say I installed something:

npm install --save something

and it downloads into

./node_modules/something/

and it has a folder in there perhaps called styles and in that folder you have something.css . How would I include that css file in my html document (if my html document was along-side the node-modules folder?

I mean I could do this in my html head:

<link rel="stylesheet" href="./node_modules/something/styles/something.css" type="text/css" media="screen" />

But it feels wrong to go dig in your node_modules directory for stuff. Especially if the html document perhaps needs to get minified and then thrown into some ./dist/ directory. Because then the path to something.css is off..

Isn't there a way to simply just go:

<link rel="stylesheet" href="something.css" type="text/css" media="screen" />

in your html document - regardless of where it's sitting in your project structure - and it'll just know where to go find that css file?

There is a package for this called npm-css

In webpack you can require css like require('bootstrap.css') , this is why installing css via npm quite useful

if you don't have it, you can create a npm script task that would require (with fs.readFile) all the css files from the node_modules, compile them into single file (which is what npm-css does)

Actually there's no need to reference the css files explicitly in your html head. Because you've already involved the css library via npm ,once you run npm start to run your project , Node.js will load all the node_moudules which also includes the css libraries you need.

Depending on which module loader you are using . For example Webpack then please read this link https://github.com/JedWatson/react-select/issues/176

Otherwise in your server you need to have node_modules as static file directory and then you can safely do

<link rel="stylesheet" href="./node_modules/something/styles/something.css" type="text/css" media="screen" />

and it correct no harm in that

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM