node.js - can't load css when param express.js too long - css

I'm writting a application by Node.js,express.js,ejs....
I'm using this code to use ejs and load css:
app.engine('.html', require('ejs').__express);
app.set('views', __dirname + '/views');
app.set('view engine', 'html');
app.use(express.static(__dirname + '/views'));
This is my dir struct
myapp
--Controller
----admin.js
--db
----db.js
--views
----admin
------user.html
------addUser.html
----css
------style.css
--app.js
Html load css like this
<link href="../css/style.css" rel="stylesheet">
And i had used css for my web. when i use params :
app.get('/admin/users', admin.users);
app.get('/admin/add', admin.add);
url are:
loocalhost:1080/admin/users
loocalhost:1080/admin/add
then my css active. but when i use param:
app.get('/admin/users/add', admin.add);
url is:
loocalhost:1080/admin/users/add
then my css not active.
so how to fix it??
Please help.

Avoid making your CSS links relative. So specify them like so:
<link href="/css/style.css" rel="stylesheet">

Related

How to import css file from assets folder in nuxt.js

<template>
<div class="container">
<head>
<link rel="stylesheet" href="~assets/css/style-light.css" />
<link rel="stylesheet" href="~assets/css/login-light.css" />
</head>
</div>
</template>
Importing css like above results in this error
vue.runtime.esm.js:5717 GET http://localhost:3000/~assets/css/login-light.css net::ERR_ABORTED 404 (Not Found)
Is there really no other way loading css other than putting the whole css in the template?
The first thing you need to know is, you can't declare a html head inside any place, neither in yours tamplate, neither in yours components, neither in yours pages, neither in nowhere.
Keep in mind that you can't use a html tags for this, you will use a json schema.
take a look https://nuxtjs.org/guide/configuration for more detailed explanations.
Now about you doubt if you want to import the CSS as globally, the correct place is inside your nuxt.config.js, inside this file, you have a property called head, and inside the head we will configure all the imports.
So, inside nuxt.config.js find your head session, and then create new property called css, some thing like this:
head: {
css: [
'~/assets/style/app.styl',
'~/assets/style/main.css'
],
}
...
Another way, is import your css directly inside your component, for this you can do some thing like this:
<style scoped>
#import '~/assets/style/main.css';
</style>
OR
<style scoped src="#/assets/styles/mystyles.css">
</style>
In Nuxt, you will need a CSS loader instaled in your application too, so have sure you had intalled a "stylus" and "stylus-loader" in your app.
try to impot your css files in script like this :
<script>
import "#/assets/css/style-light.css";
import "#/assets/css/login-light.css";
///
</script>
EDIT: changed ~ to #
You could bring your files in using the head method like so :
head () {
return {
link: [
{ rel: 'stylesheet', href: '/style-light.css' },
{ rel: 'stylesheet', href: '/login-light.css' }
]
}
}
You should also move these css files into the static folder. See this discussion on the Vue forum https://forum.vuejs.org/t/nuxt-import-css-file-and-js-file/42498

Webpack-React with server-side-rendering: linking to css file in server template with hash name

I'm preparing a starter for react from scratch, here is the code: https://github.com/antondc/react-starter
I managed to set up bundling for client and server, with css modules and less, and now I'm with server side rendering. I'm doing that with a js template:
// src/server/views/index.ejs
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>INDEX.EJS</title>
<link rel="stylesheet" type="text/css" href="assets/index.css">
</head>
<body>
<div id="app"></div>
<script src="/assets/bundle.js"></script>
</body>
</html>
As you see, the link to the css file is harcoded there. But in my Webpack configuration I have this file name hashed, because I want to prevent caching from browsers when I update the code on development.
I am wondering how can I link the css file there. Now in the template I have href="assets/index.css, but the css file is in /dist/assets/d47e.css.
It would be great if would be possible to do something like href="assets/*.css, but is not possible, so what is the common approach for a problem like this one?
Thanks!
It depends.
Step 1: Get the current asset name
To get the current name of the generated webpack css/js files, you can use the assets-webpack-plugin. This will (with default config) generate an assets.json file in your output folder with essentially this structure:
{
"bundle_name": {
"asset_kind": "/public/path/to/asset"
}
}
Step 2a: Your html is rendered from a template (pug/jade/what ever)
// in your render code
const assets = require('<webpack-output-folder>/assets.json');
// ...
res.render('template', {
scripts: [{src: `${WEBPACK_PUBLIC_PATH}/${assets.myEntryPointName.js}` }],
links: [{href: `${WEBPACK_PUBLIC_PATH}/${assets.myEntryPointName.css}` rel: 'stylesheet' }],
});
// in your template (example for pug)
// ...
each link in links
link(rel=link.rel href=link.href)
// ...
each script in scripts
script(src=script.src)
// ...
Step 2b: Your html is static
You need to update the html (using a script) with the information from the asset.json file. This script needs to be run after webpack. Something like
const assets = require('<webpack-output-folder>/assets.json');
const fs = require('fs');
const css = /assets\/[a-z0-9]*\.css/i;
const js = /assets\/[a-z0-9]*\.js/i;
fs.readFile('<yourhtml>.html', (err, data) => {
// ... (error handling)
const updatedCss = data.replace(css, assets.myEntryPointName.css);
const updatedJs = updatedCss.replace(js, assets.myEntryPointName.js);
fs.writeFile('<yourhtml>.html', updated, (err) => {
// ... (error handling)
});
});
You can use HTMLWebpackPlugin to generate an HTML file that will have your JS and CSS output inserted.

express js not serving the static css files from router

I am actually facing this problem in another bigger project but, I have made a simple one so as to explain it easily
Tree Structure of my project is as follows
demo
|____admin
| |____admin.js
|____node_modules
|
|____static
| |____bootstrap.min.css
| |____headerStyle.min.css
|
|____views
| |____admin
| | |____admin_home.ejs
| |
| |____partials
| |____admin_header.ejs
|
|____index.js
|____package-lock.json
|____package.json
please bear with me, I am going to post the code of some of important files
code in 'index.js' is this
let express = require('express');
let app = express();
let path = require('path');
app.use(express.static(path.join(__dirname, 'static')));
app.set('view engine', 'ejs');
app.get('/',function(req,res)
{
res.render('./admin/admin_home');
});
let admin = require('./admin/admin.js');
app.use('/admin',admin);
app.listen(9000,function(){
console.log('listening to port : 9000');
});
Code in 'admin/admin.js' is this
let express = require('express');
let router = express.Router();
router.get('/',function(req,res)
{
res.render('./admin/admin_home');
});
router.get('/adminhome',function(req,res)
{
res.render('./admin/admin_home');
});
module.exports = router;
Code in 'views/admin/admin.ejs' is this
<%- include('../partials/admin_header.ejs') %>
<h1>Admin Home</h1>
I am having problem with express js static file serving.
For the following URL's the webpages are rendered with all the styles from css files
http://localhost:9000
http://localhost:9000/admin
they are served from these paths
http://localhost:9000/bootstrap.min.css
and
http://localhost:9000/headerStyle.css
but for the following URL webpages are rendered with plain html with out serving the css syles
http://localhost:9000/admin/adminhome
the error is
Failed to load the resources: the server responded with 404
css files are served from these paths
http://localhost:9000/admin/bootstrap.min.css
and
http://localhost:9000/admin/headerStyle.css
and the 'Link' tags in 'vies/partials/admin_header.ejs' are as follows
<link rel="stylesheet" type="text/css" href="bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="headerStyle.css">
versions of the modules are as follows
ejs:^2.5.7
express:^4.16.2
path:^0.12.7
my nodejs version is
v8.5.0
Please help me in finding the solution for this problem. Thank You
as quoted by Roland Starke, the hrefs of the styles were relative to the url I was visiting. I can make them absolute just by adding a ' / ' like
href="/bootstrap.min.css"
You should add a line to index.js
app.set('views', path.join(__dirname, 'views'));

How can I contain the styles of a Chrome Extension content script?

I'm working on a Chrome extension that injects some UI react components into a page.
The UI components come from react-mdl. Using them requires me to include a css file in the top of my project.
Unfortunately, once the css is injected into the page, the entire page's font is changed.
Is there a way to limit the scope of the css used by react-mdl such that it doesn't affect the page into which I'm injecting?
Just posting this for posterity as accepted answer deserves credit, but if anyone finds themselves in a similar predicament, here is a snippet of the code that worked for me:
// my injected code
window.addEventListener('load', () => {
const injectDiv = document.createElement('div')
const shadowRoot = injectDiv.attachShadow({ mode: 'open' })
// note inline use of webpack raw-loader, so that the css
// file gets inserted as raw text, instead of attached to <head>
// as with the webpack style-loader
shadowRoot.innerHTML = // just using template string
`
<style>${require('raw-loader!app/styles/extension-material.css')}</style>
<div id='shadowReactRoot' />
`
document.body.appendChild(injectDiv)
ReactDOM.render(
<App />,
// note you have to start your query in the shadow DOM
// in order to find your root
shadowRoot.querySelector('#shadowReactRoot')
)
})
Then, sure enough:
I think you should use the Shadow DOM API. It is good practice for those cases when you just need to append your UI component to a webpage.
https://developers.google.com/web/fundamentals/getting-started/primers/shadowdom
As mentioned in this other SO post, <link> tag is also supported, so one can simply do as follows:
const injectedDiv = document.createElement('div');
const shadowRoot = injectedDiv.attachShadow({ mode: 'open' });
shadowRoot.innerHTML = `\
<link rel="stylesheet" type="text/css" href="${chrome.extension.getURL("bootstrap.min.css")}"></link>\
<link rel="stylesheet" type="text/css" href="${chrome.extension.getURL("whatever.css")}"></link>\
`;
document.body.appendChild(injectedDiv);
Notes:
Using chrome.extension.getURL is required for getting an extension's local resource url, see e.g. in this answer.
The linked .css resources must be declared under the web_accessible_resources property in your manifest.json (otherwise, you'll get this error)

styles dont connect when loading local server

my dir looks like that :
|-project
-gulpfile.js
|-build
-index.html
|-js
-app.min.js
-vendors.min.js
|-styles
-all.css
-vendors.min.css
i inject the css and js files with this gulp task:
gulp.task('index',function () {
return gulp.src('src/index.html')
.pipe(inject(gulp.src(['**/vendors.min.css','**/vendors.min.js','**/app.min.js','**/all.css'], {read: false})))
.pipe(gulp.dest('build'))
.pipe(livereload());
})
i set up a local server with node.js,when i do the request , the html file loads up,but the .js and .css files dont connect for some reason.Although when i check page's source code at output their paths are written in.
<!-- inject:css -->
<link rel="stylesheet" href="/build/styles/vendors.min.css">
<link rel="stylesheet" href="/build/styles/all.css">
<!-- endinject -->
when i hover on one of them it shows :
http://localhost:5000/build/styles/all.css
i use this task for setting the server :
gulp.task('connect', function() {
connect.server({
root: 'build',
livereload: true,
port: 5000
});
});
EDIT
any recommendation about how to make it on hovering look like
localhost:5000/styles/all.css
If the build folder is the root of the server, you shouldn't be including it in the path of the js and css files. This is failing because you are trying to reference a build folder inside the build folder.
Change your injection of css to the following:
<link rel="stylesheet" href="styles/vendors.min.css">
<link rel="stylesheet" href="styles/all.css">

Resources