favicon is not displayed using react-static-plugin-favicons - javascript

I would like to display a favicon using the lib react-static-plugin-favicons.
I added it to my static.config.js :
export default {
entry: path.join(__dirname, 'src', 'index.tsx'),
getRoutes: async () => {
return [
{
path: '/',
template: 'src/containers/individuals.tsx'
}
]
},
plugins: [
require.resolve("react-static-plugin-sass"),
['react-static-plugin-typescript', { typeCheck: true }],
[
require.resolve('react-static-plugin-source-filesystem'),
{
location: path.resolve('./src/page'),
},
],
require.resolve('react-static-plugin-reach-router'),
require.resolve('react-static-plugin-sitemap'),
[
'react-static-plugin-favicons',
{ inputFile: path.resolve('./src/assets', 'favicon-32px.png') },
]
],
basePath: basepath,
Document: ({
Html,
Head,
Body,
children,
state: { siteData, renderMeta },
}) => (
<Html lang="en-US">
<Head>
<meta charSet="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</Head>
<Body>{children}</Body>
</Html>
),
}
And this is my file structure :
Can you spot what did I do wrong because it doesn't work ?
Thanks

I tried this plugin as well and could not get it to work - however adding the file as favicon.ico to the public folder worked for me as suggested at https://github.com/react-static/react-static/issues/1483.

Related

Remove 'All Files' option from HTML file input and limit to .json type when using File System Access API

I am using File System Access API to disable all files options when uploading files, and want to be accepted only .json files but it brings under All Files (*.*) As in pic:
I don't know if I'm entering wrong "application/json", maybe should be something else instead of this.
Official documentation https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API#examples
Can someone help?
My code is as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Open file</title>
</head>
<body>
<button onclick="getFile()">Open file</button>
<script>
const pickerOpts = {
types: [
{
accept: {
"application/json": [".json"],
},
},
],
excludeAcceptAllOption: true,
multiple: false,
};
let fileHandle;
async function getFile() {
[fileHandle] = await window.showOpenFilePicker(pickerOpts);
// run code with our fileHandle
}
console.log(fileHandle);
</script>
</body>
</html>

Blazor, Razor Library, npm and webpack

Hopefully I can explain this clearly.
I have a Blazor WASM project that is referencing a Razor library (everything fine here).
The Razor library compiles a JavaScript bundle using webpack (everything works here).
One of the components I am trying to create has one simple function that returns the revesion of a package (threejs) as a string.
Now the problem.
When I try to call the function from the Blazor project I keep receiving that the function does not exist.
Error
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>Atom.Web.Client</title>
<base href="/" />
<link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
<link href="css/app.css" rel="stylesheet" />
<link href="Atom.Web.Client.styles.css" rel="stylesheet" />
</head>
<body>
<div id="app">Loading...</div>
<div id="blazor-error-ui">
An unhandled error has occurred.
Reload
<a class="dismiss">🗙</a>
</div>
<script src="_framework/blazor.webassembly.js"></script>
<script src="./_content/Atom.Web.Viewer.Components/js/atom.bundle.js"></script>
</body>
</html>
Webpack config
const path = require("path");
module.exports = {
devtool: 'source-map',
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
}
]
},
output: {
path: path.resolve(__dirname, '../wwwroot/js'),
filename: "atom.bundle.js",
library: "Atom"
}
};
the component code
private readonly Lazy<Task<IJSObjectReference>> moduleTask;
public ThreeViewer(IJSRuntime jsRuntime)
{
moduleTask = new(() => jsRuntime.InvokeAsync<IJSObjectReference>(
"import", "./_content/Atom.Web.Viewer.Components/js/atom.bundle.js").AsTask());
}
public async ValueTask<string> GetRevision()
{
var module = await moduleTask.Value;
var rev = await module.InvokeAsync<string>("Atom.GetCurrentThreeRevision");
return rev;
}
the Program.cs
using Atom.Web.Client;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Atom.Web.Viewer.Components;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
builder.Services.AddScoped<ThreeViewer>();
await builder.Build().RunAsync();
the Index.razor
#inject IJSRuntime JSRuntime;
#inject ThreeViewer threeViewer;
#page "/"
#using Newtonsoft.Json
<PageTitle>Index</PageTitle>
#if(revisionMessage != string.Empty)
{
<h1>#revisionMessage</h1>
}
<SurveyPrompt Title="How is Blazor working for you?" />
#code {
string revisionMessage = string.Empty;
protected override async Task OnInitializedAsync()
{
revisionMessage = await JSRuntime.InvokeAsync<string>("Atom.GetCurrentThreeRevision");
var rev = await threeViewer.GetRevision();
}
}
The interesting part is, if I call the function directly using jsruntime revisionMessage it works fine, if I try to call it from the component library, it doesn't.
Anyone can be of any help?
Ok I have figured this out myself.
I had to remove dynamic loading of the library within the Razor component and assume that this library will be loaded in the main Blazor app.
public async Task<string> GetRevision()
{
return await JSRuntime.InvokeAsync<string>("Atom.GetCurrentThreeRevision");
}
public async Task<Scene> InitiateScene()
{
string text = JsonConvert.SerializeObject((object)new { Scene, ViewerSettings, Camera, OrbitControls }, SerializationHelper.GetSerializerSettings());
return await JSRuntime.InvokeAsync<Scene>("Atom.InitiateScene");
}
everything else remains the same basically.

React is not defined when using SystemJS

I was trying using SystemJS to load React but it didn't loaded instead throwing an error message in Console > 'React is not defined'
I've read their documentation also searching through similar questions but doesn't satisfy my need, did i miss something?
Here's is what I was tried
<!DOCTYPE html> <html lang="en"> <head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>React 18 with SystemJS</title>
<script src="dependencies/systemjs-6.12.1.min.js"></script>
<script type="systemjs-importmap"> {
"imports": {
"react" : "/react.production-18.min.js"
, "reactDOM" : "/react-dom.production-18.min.js"
} }
</script>
</head><body>
<div id="root">
<script type="systemjs-module">
System.import('react');
System.import('reactDOM');
class Hello extends React.Component {
render() {
return React.createElement('div', null, `Hello ${this.props.toWhat}`);
} }
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(React.createElement(Hello, {toWhat: 'World'}, null));
</script>
</div></body></html>
Edit1: I'm using SystemJS version 6.12.1
You need a bit more configuration to get it going. It is also recommended to keep react code in separate files.
Full working example here.
SystemJS configuration for react:
System.config({
baseURL: '//npm.jspm.io/',
// CDN resolves
paths: {
'npm:*': '//npm.jspm.io/*',
'unpkg:*': '//unpkg.com/*',
'jsdelivr:*': '//cdn.jsdelivr.net/g/*',
'jsdelivr-npm:*': '//cdn.jsdelivr.net/npm/*'
},
meta: {
'*.scss': { loader: "sass" }
},
map: {
// The Application path
'index': INDEX + '?' + Date.now(),
// SystemJS plugins
'plugin-babel': 'unpkg:systemjs-plugin-babel#0/plugin-babel.js',
'systemjs-babel-build': 'unpkg:systemjs-plugin-babel#0/systemjs-babel-browser.js',
// 'scss': 'npm:scss',
// Application modules
'react': 'jsdelivr:react#15/react.js',
'react-dom': 'jsdelivr:react#15/react-dom.js'
},
packages: {
'https://npm.jspm.io/' : { defaultExtension: 'js' },
'https://cdn.rawgit.com/*' : { defaultExtension: false },
'https://unpkg.com/' : { defaultExtension: false },
'./index.scss' : { defaultExtension: false },
},
transpiler: 'plugin-babel',
babelOptions: {
sourceMaps: false,
stage0: true,
react: true
}
});

Webpack 5: How to inject CSS into head tag directly

I want to place CSS in the head tag of my HTML template directly instead of loading CSS into JS. But I can't find any reliable examples how to do this.
/* webpack.config.js */
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyPlugin = require("copy-webpack-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
module.exports = {
mode: 'development',
entry: {
main: path.resolve(__dirname, 'src/script.js'),
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].[contenthash].js',
clean: true,
},
optimization: {
minimize: true,
minimizer: [
new CssMinimizerPlugin(),
],
},
module: {
rules: [
{test: /\.css$/, use: ['style-loader', 'css-loader']},
],
},
plugins: [
new HtmlWebpackPlugin({
title: 'My optimized file',
filename: 'index.html',
template: path.resolve(__dirname, 'src/temp.html'),
templateParameters: {
'style': '[name].[contenthash].css' // doesn't bind with CopyPlugin
},
}),
new CopyPlugin({
patterns: [
{ from: path.resolve(__dirname, 'src/style.css'), to: '[name].[contenthash].css' },
],
}),
],
};
And my HTML template src/temp.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><%= htmlWebpackPlugin.options.title %></title>
<link rel="stylesheet" href="<%= style %>">
</head>
<body>
<h1>Hello there!</h1>
</body>
</html>
Now as the result in my compiled HTML file dist/index.html I get this:
<head>
...
<link rel="stylesheet" href="[name].[contenthash].css">
</head>
After webpack build href attribute has just a wapback parameter [name].[contenthash].css instead of compiled CSS filename style.347572c74109b5f9ef4e.css.
And my folder structure:
dist
├─ index.html
├─ main.3d522b68c880128437a8.js
└─ style.347572c74109b5f9ef4e.css
src
├─ script.js
├─ style.css
└─ temp.html
webpack.config.js
package.json
For now I found temporary solution to this problem. I've just tried mini-css-extract-plugin and looked at example from html-webpack-plugin.
/* webpack.config.js */
...
module: {
rules: [
{ test: /\.css$/, use: [MiniCssExtractPlugin.loader, 'css-loader'] },
]
},
plugins: [
new HtmlWebpackPlugin({
template: 'template.html'
}),
new MiniCssExtractPlugin({ filename: 'style.css' })
]
But to make it work you must require CSS in JS file:
/* script.js */
require('./style.css');
...
But I'm still looking for how to do it without hardcoding CSS in JS using only webpack.config.js file since style.css has nothing to do with script.js in my case.

Uncaught SyntaxError: Cannot use import statement outside a module in node js

while using the ES6 module language in nodejs it gives me an error of
" IMPORTS CANNOT BE USED OUTSIDE THE MODULE" ERROR IN CHROME BROWSER.
I am trying to build my project using Node js express mongoose morgan express-handlebars and ES6
but while I run the project it gives me an error for the same
I tried using .babelrc and webpack.config.js but not able to resolve it.
can anyone help me to achieve it?
I am putting images of my project for your reference.
Thank You
enter image description here
enter image description here
Babelrc:
{
"presets": [
["#babel/env", {
"useBuiltIns": "usage",
"corejs": "3",
"targets": {
"browsers": [
"last 5 versions",
"ie >= 8"
]
}
}]
]
}
webpack.config.js:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: ['./index.js'],
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'js/bundle.js'
},
devServer: {
contentBase: './dist'
},
plugins: [
new HtmlWebpackPlugin({
title: 'Custom template using Handlebars',
filename: 'index.html',
template: 'main.hbs'
})
],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
}
],
loaders: [
{ test: /\.hbs$/, loader: "handlebars-loader" }
]
}
};
main.js:
enter code here
import Search from './models/search';
import Movie from './models/Movie'
import User from './models/user'
import * as searchView from './views/searchView'
import * as movieView from './views/movieView'
import { elements , renderLoader, clearLoader } from './views/base'
const state = {};
const controlSearch = async () => {
// const query = searchView.getInput();
const query = 'avengers';
if (query) {
searchView.clearInput();
searchView.clearResult();
state.search = new Search(query);
state.user = new User();
searchView.clearInput();
searchView.clearResult();
renderLoader(elements.searchRes);
await state.search.getResult();
await state.user.userSignUp();
clearLoader();
console.log(state.search.result);
searchView.renderResults(state.search.result);
}
};
elements.searchForm.addEventListener('submit', e => {
e.preventDefault();
controlSearch();
});
main.hbs
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Movie Recherer</title>
<link rel="stylesheet" href="/css/bootstrap.min.css"/>
<link rel="stylesheet" href="/css/all.min.css"/>
<link rel="stylesheet" href="/css/main.css" />
<link rel="stylesheet" href="/css/home.css" />
</head>
<body>
<div class="container">
<div class="row">
{{{body}}}
</div>
</div>
<script src="/jquery.min.js"></script>
<script src="/js/bootstrap.min.js"></script>
<script language="javascript" src="/js/main.js"></script>
<script language="javascript" src="/js/models/Movie.js"></script>
<script language="javascript" src="/js/models/search.js"></script>
<script language="javascript" src="/js/views/base.js"></script>
<script language="javascript" src="/js/views/movieView.js"></script>
<script language="javascript" src="/js/views/searchView.js"></script>
</body>
</html>
You need to include you import inside a module:
Try this:
<script type="module"> import btn from './helper' </script>
Add type="module" in every script tag of your main.hbs file

Categories