Rails webpack page glitches on reload (html loaded first) - ruby-on-rails

In my Rails project I migrated my asset pipeline to webpack. I also migrated bootstrap and stylesheets to Webpack. The styling is loaded correctly, except that I have a glitch on every page reload (html is loaded first). This makes it weird to navigate from one page to another.
I browsed stackoverflow for a couple of hours and added a style loader to webpack, but can't seem to get it right.
I made a screen vide to illustrate what I mean:
https://imgur.com/2yWw0SQ
Hope someone can point me in the right direction! Thanks for the help.
Environment.js:
const {environment} = require('#rails/webpacker');
const webpack = require('webpack');
const styleLoader = require('./styleloader');
environment.config.merge(styleLoader);
environment.plugins.append('Provide', new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
jquery: 'jquery',
Popper: ['popper.js', 'default']
}));
module.exports = environment;
Styleloader.js
module.exports = {
module: {
rules: [{
test: /\.scss$/,
use: [
"style-loader", // creates style nodes from JS strings
"css-loader", // translates CSS into CommonJS
"sass-loader", // compiles Sass to CSS, using Node Sass by default
]
}]
}
};
Package.json:
{
"dependencies": {
"#babel/core": "^7.4.4",
"#fortawesome/fontawesome-free": "^5.9.0",
"#rails/ujs": "^6.0.0-alpha",
"#rails/webpacker": "^4.0.2",
"activestorage": "^5.2.3",
"babel-loader": "^8.0.6",
"bootstrap": "^4.3.1",
"bootstrap-select": "^1.13.10",
"choices.js": "^7.0.0",
"css-loader": "^2.1.1",
"jquery": "^3.4.1",
"moment": "^2.24.0",
"moment-timezone": "^0.5.11",
"node-sass": "^4.12.0",
"popper": "^1.0.1",
"popper.js": "^1.14.7",
"rails-ujs": "^5.2.3",
"sass-loader": "^7.1.0",
"stimulus": "^1.1.1",
"style-loader": "^0.23.1",
"sweetalert2": "^8.13.0",
"tempusdominus-bootstrap-4": "^5.1.2",
"tempusdominus-core": "5.0.3",
"turbolinks": "^5.2.0",
"webpack": "^4.35.2",
"webpack-cli": "^3.3.2"
},
"devDependencies": {
"sass-loader": "*",
"node-sass": "*",
"webpack-dev-server": "^3.2.1"
}
}
Application.html.erb:
<head>
<title>Youba</title>
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
<%= stylesheet_pack_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_pack_tag "application", 'data-turbolinks-track': 'reload' %>
</head>

I stumbled upon the solution today. The glitch was caused by Font Awesome.
The solution on the following page from #tagliala worked for me:
https://github.com/FortAwesome/Font-Awesome/issues/11924#issuecomment-475058975
Import this in your application.js:
https://github.com/diowa/ruby2-rails5-bootstrap-heroku/blob/422467be1206e2887ec49f71ba2866daf4c477a2/app/javascript/src/fontawesome.js

Related

Rails 6 with turbo-rails. popper.js is not loading on full page load

I am very new to rails and webpacker and cannot figure out what is happening, here. When I perform a 'full load' of my app from the address bar in the browser, the tooltips and popovers are not being instantiated and I get errors like this:
application.js:32 Uncaught TypeError: $(...).tooltip is not a function
But, when I load a page from within the app (click on link in the nav bar), the tooltips and popovers work as expected. Also, If I go to the chrome console and manually instantiate them, the tooltips and popovers begin working:
$('[data-bs-toggle="tooltip"]').tooltip();
Here are some of what I think are the pertinent configs:
packs/application.js
// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.
import Rails from "#rails/ujs"
import Turbo from "#hotwired/turbo"
import "#hotwired/turbo-rails"
import * as ActiveStorage from "#rails/activestorage"
import "channels"
import 'bootstrap'
import '../stylesheets/application'
import "controllers"
Rails.start()
ActiveStorage.start()
document.addEventListener("turbo:load", () => {
console.log("turbo!");
$('[data-bs-toggle="tooltip"]').tooltip();
$('[data-bs-toggle="popover"]').popover();
});
webpack/environment.js
environment.plugins.append(
'Provide',
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
Popper: ['popper.js', 'default']
})
);
environment.config.merge(customConfig);
module.exports = environment;
webpack/custom.js:
resolve: {
alias: {
jquery: 'jquery/src/jquery'
}
}
};
layouts/application.html.erb:
<%= javascript_pack_tag 'application', 'data-turbo-track': 'reload' %>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbo-track': 'reload' %>
<%= stylesheet_pack_tag 'application', media: 'all', 'data-turbo-track': 'reload' %>
package.json:
{
"name": "deploy-dashboard",
"private": true,
"dependencies": {
"#hotwired/turbo": "^7.0.0-beta.5",
"#hotwired/turbo-rails": "^7.0.0-beta.5",
"#popperjs/core": "^2.9.2",
"#rails/actioncable": "^6.0.0",
"#rails/activestorage": "^6.0.0",
"#rails/ujs": "^6.0.0",
"#rails/webpacker": "5.2.1",
"bootstrap": "^5.0.0",
"jquery": "^3.6.0",
"popper.js": "^1.16.1",
"stimulus": "^2.0.0"
},
"version": "0.1.0",
"devDependencies": {
"webpack-dev-server": "^3.11.2"
}
}
try
document.addEventListener("turbo:load", function() {
$(function () {
$('[data-toggle="tooltip"]').tooltip();
$('[data-toggle="popover"]').popover();
})
})

How can I troubleshoot why electron-builder isn't creating a working production package

My app builds fine on local, but when I try to create a production version, I'm having trouble. I'm not very well versed in either electron or electron-builder, so this could definitely be something simple I'm missing.
My project packages successfully, and when I open it from Finder (I'm on a mac) the window launches properly, but nothing renders; this is the result:
Previously (with different mucking around) I've had an error 'not allowed to access local file:' and then gives me a directory path.
Here is my package.json:
"main": "public/electron.js",
"name": "storyweaver-dm",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^4.2.4",
"#testing-library/react": "^9.3.2",
"#testing-library/user-event": "^7.1.2",
"axios": "^0.19.2",
"concurrently": "^5.1.0",
"electron-is-dev": "^1.1.0",
"nodemon": "^2.0.4",
"react": "^16.13.0",
"react-beautiful-dnd": "^13.0.0",
"react-dom": "^16.13.0",
"react-hook-form": "^6.1.2",
"react-scripts": "3.4.0",
"react-select": "^3.1.0",
"recoil": "0.0.10",
"sqlite3": "^5.0.0",
"styled-components": "^5.0.1",
"wait-on": "^4.0.1"
},
"devDependencies": {
"#rescripts/cli": "^0.0.13",
"#rescripts/rescript-env": "^0.0.11",
"electron": "^8.1.1",
"electron-builder": "^22.4.1",
"electron-devtools-installer": "^2.2.4",
"typescript": "^3.8.3"
},
"homepage": "./",
"scripts": {
"build": "rescripts build",
"eject": "react-scripts eject",
"electron-dev": "concurrently \"BROWSER=none yarn start\" \"wait-on http://localhost:4203 && electron .\"",
"dev": "concurrently \"BROWSER=none npm start\" \"wait-on http://localhost:4203 && electron .\"",
"electron-pack": "electron-builder build -mw",
"postinstall": "electron-builder install-app-deps",
"preelectron-pack": "npm install",
"start": "PORT=4203 rescripts start",
"test": "rescripts test"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"rescripts": [
"env"
],
"author": {
"name": "Jamie Sauve and other wonderful people",
"email": "jamiesauve#zohomail.com"
},
"build": {
"appId": "com.my-website.my-app",
"productName": "StoryWeaver DM",
"copyright": "Copyright © 2019 ${author}",
"mac": {
"icon": "./assets.icon.icns",
"category": "public.app-category.utilities"
},
"files": [
"public/**/*",
"build/**/*",
"node_modules/**/*",
"pseudoServer/**/*",
"./public/electron.js"
],
"directories": {
"buildResources": "assets"
}
}
}
and here is my electron.js (I renamed this - this is my main Electron process):
const electron = require('electron');
const app = electron.app;
const ipcMain = electron.ipcMain;
const BrowserWindow = electron.BrowserWindow;
// const { default: installExtension, REACT_DEVELOPER_TOOLS } = require('electron-devtools-installer');
const path = require('path');
const isDev = require('electron-is-dev');
process.env['APP_PATH'] = app.getAppPath();
const directory = isDev ? process.cwd() : process.env.APP_PATH;
const databaseApi = require(path.join(directory, './pseudoServer/api/controller/routes'))
ipcMain.handle('dbRequest', async (event, request) => {
const response = await databaseApi(request)
return response
})
let mainWindow;
function createWindow() {
mainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: false,
webSecurity: false,
/**
* import native Node modules explicitly in this file; something about Create-React-App and webpack mess
* with Electron's ability to provide these directly.
* See the comment by HemalR here: https://github.com/electron/electron/issues/9920
*/
preload: __dirname + '/preload.js'
},
});
mainWindow.maximize();
mainWindow.loadURL(isDev ? 'http://localhost:4203' : `file:///${__dirname}/public/index.html`)
if (isDev) {
// Open the DevTools.
//BrowserWindow.addDevToolsExtension('<location to your react chrome extension>');
mainWindow.webContents.openDevTools();
// installExtension(REACT_DEVELOPER_TOOLS)
// .then((name) => console.log(`Added Extension: ${name}`))
// .catch((err) => console.log('An error occurred: ', err));
}
mainWindow.on('closed', () => mainWindow = null);
}
app.on('ready', createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (mainWindow === null) {
createWindow();
}
});
and this is my index.html:
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<!-- see https://github.com/electron/electron/issues/19775 for the line below -->
<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' http://* 'unsafe-inline'; script-src 'self' http://* 'unsafe-inline'" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<base href="./" />
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>StoryWeaver DM</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
How can I get this app packaging properly in production?
The /pseudoServer directory might be an odd pattern - I'm using a sqlite3 database, and created a 'server' (really just called from the electron main process) to access it. I'm not sure if this actually counts as a backend or not in Electron.
My project is at https://github.com/jamiesauve/StoryWeaver-DM if these two files don't provide enough information.

how to configure service worker in react project ( npx create-react-app)?

I'm creating a pwa with reactJS but I can't get google lighthouse to recognize it as such. I created the project with npx create-react-app and these are the configuration files to get the service workers works:
registerServiceWorker.js
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.1/8 is considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
export default function register() {
console.log("register", process.env.PUBLIC_URL)
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
console.log(swUrl)
if (isLocalhost) {
// This is running on localhost. Lets check if a service worker still exists or not.
checkValidServiceWorker(swUrl);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit'
);
});
} else {
// Is not local host. Just register service worker
registerValidSW(swUrl);
}
});
}
}
function registerValidSW(swUrl) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the old content will have been purged and
// the fresh content will have been added to the cache.
// It's the perfect time to display a "New content is
// available; please refresh." message in your web app.
console.log('New content is available; please refresh.');
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl)
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
if (
response.status === 404 ||
response.headers.get('content-type').indexOf('javascript') === -1
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
console.log("registerValidSW", swUrl)
registerValidSW(swUrl);
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister();
});
}
}
index.js
import React from "react";
import ReactDOM from "react-dom";
import { createBrowserHistory } from "history";
import { Route, Switch, Redirect, HashRouter } from "react-router-dom";
import { Provider } from "react-redux";
import AuthLayout from "layouts/Auth.jsx";
import RtlLayout from "layouts/RTL.jsx";
import AdminLayout from "layouts/Admin.jsx";
import { store } from "helpers/store.js";
import LoginPage from "views/Pages/LoginPage.jsx";
import "assets/scss/material-dashboard-pro-react.scss?v=1.5.0";
import { PrivateRoute } from "./components/PrivateRoute/PrivateRoute";
import PDVDetails from "./views/Pages/PDVDetails";
import RegisterUserClientPage from "./views/Pages/RegisterUserClientPage";
import { createMuiTheme, MuiThemeProvider } from "#material-ui/core/styles";
import registerServiceWorker from './registerServiceWorker';
//import { App } from './App';
const hist = createBrowserHistory();
const theme = createMuiTheme({
overrides: {
MuiTableCell: {
root: {
textAlign: 'center'
}
}
}
});
ReactDOM.render(
<MuiThemeProvider theme={theme}>
<Provider store={store}>
<HashRouter history={hist}>
<Switch>
{/* <Route path="/admin/PDVDetails/:id" component={PDVDetails} /> */}
{/* <Route path="/auth/Login-Page" component={LoginPage}/>
<Route path="/auth/Register-user-client/:id" component={RegisterUserClientPage}/> */}
<Route path="/auth" component={AuthLayout} />
<PrivateRoute path="/admin" component={AdminLayout} />
<Redirect from="/" to="/admin/dashboard" />
</Switch>
</HashRouter>
</Provider>
</MuiThemeProvider>,
document.getElementById("root")
);
registerServiceWorker();
service-worker.js
/**
* The workboxSW.precacheAndRoute() method efficiently caches and responds to
* requests for URLs in the manifest.
* See
*/
// Precarga la app
importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.5.0/workbox-sw.js');
if (workbox) {
console.log(`Yay! Workbox is loaded 🎉`);
workbox.precaching.precacheAndRoute([]);
} else {
console.log(`Boo! Workbox didn't load 😬`);
}
// self.__precacheManifest = [].concat(self.__precacheManifest || [])
// workbox.precaching.suppressWarnings()
// workbox.precaching.precacheAndRoute(self.__precacheManifest, {})
// App Shell
workbox.routing.registerNavigationRoute('/index.html')
console.log("service worker js")
// La API usa Stale While Revalidate para mayor velocidad
workbox.routing.registerRoute(/^https?:\/\/mi.app.com\/api\/.*/,
workbox.strategies.staleWhileRevalidate(),
'POST')
// // Last fuentes van con Cache First y vencen al mes
// workbox.routing.registerRoute(/^https:\/\/fonts.(?:googleapis|gstatic).com\/(.*)/,
// workbox.strategies.cacheFirst({
// cacheName: 'google-fonts-cache',
// plugins: [
// new workbox.expiration.Plugin({
// maxAgeSeconds: 30 * 24 * 60 * 60
// })
// ]
// }),
// 'GET')
// Todo lo demás usa Network First
workbox.routing.registerRoute(/^https?.*/,
workbox.strategies.networkFirst(), 'GET')
manifest.json
{
"short_name": "ComercialPWA",
"name": "Comercial VEGA PWA",
"icons": [
{
"src": "icon.png",
"sizes": "512x512",
"type": "image/png"
}
],
"start_url": "/",
"scope": "/",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff",
"related_applications": [],
"prefer_related_applications": false
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<meta name="theme-color" content="#000000" />
<!--
manifest.json provides metadata used when your web app is added to the
homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<link rel="shortcut icon" href="%PUBLIC_URL%/icon.png" />
<link rel="apple-touch-icon" href="/icon.png" />
<meta name="apple-mobile-web-app-title" content="ComercialPWA" />
<meta name="apple-mobile-web-app-capable" content="no" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<link
rel="apple-touch-icon"
sizes="76x76"
href="%PUBLIC_URL%/apple-icon.png"
/>
<link
rel="stylesheet"
href="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.css"
/>
<script src="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.js"></script>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/jvectormap/2.0.4/jquery-jvectormap.css"
type="text/css"
media="screen"
/>
<link
rel="stylesheet"
href="//cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css"
type="text/css"
media="screen"
/>
<!-- Fonts and icons -->
<link
href="https://use.fontawesome.com/releases/v5.0.7/css/all.css"
rel="stylesheet"
/>
<link
rel="stylesheet"
type="text/css"
href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons"
/>
<link
href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet"
/>
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>Vive una experiencia única con Novaventa</title>
</head>
<body>
<noscript> You need to enable JavaScript to run this app. </noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
package.json
{
"name": "material-dashboard-pro-react",
"version": "1.5.0",
"private": true,
"dependencies": {
"#date-io/date-fns": "^1.3.13",
"#material-ui/core": "^4.9.5",
"#material-ui/icons": "3.0.2",
"#material-ui/pickers": "^3.2.10",
"chartist": "0.10.1",
"dashboard": "0.0.1",
"date-fns": "^2.10.0",
"history": "4.7.2",
"immutability-helper": "^3.0.1",
"material": "^0.4.3",
"moment": "^2.24.0",
"moment-timezone": "^0.5.27",
"node-sass": "^4.12.0",
"nouislider": "13.1.0",
"perfect-scrollbar": "1.4.0",
"react": "^16.13.0",
"react-big-calendar": "0.20.3",
"react-bootstrap-sweetalert": "4.4.1",
"react-chartist": "0.13.3",
"react-csv": "^1.1.1",
"react-datetime": "2.16.3",
"react-dnd": "^7.0.2",
"react-dnd-html5-backend": "^7.0.2",
"react-dom": "^16.8.1",
"react-google-maps": "9.4.5",
"react-jvectormap": "0.0.6",
"react-moment": "^0.9.7",
"react-number-format": "^4.3.0",
"react-redux": "^7.1.0",
"react-responsive-carousel": "^3.1.51",
"react-router-dom": "4.3.1",
"react-scripts": "^2.1.8",
"react-swipeable-views": "0.13.1",
"react-table": "6.9.2",
"react-tag-input": "^6.4.2",
"react-tagsinput": "3.19.0",
"redux": "^4.0.1",
"redux-thunk": "^2.3.0",
"serve": "^9.1.0"
},
"scripts": {
"dev": "react-scripts start",
"start": "serve ./build -s -p 5000",
"copy": "copyfiles -u 1 src/**/**/* src/**/* src/* build",
"build": "npm run copy && workbox injectManifest workbox-config.js",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject",
"deploy": "npm run build",
"lint:check": "eslint . --ext=js,jsx; exit 0",
"lint:fix": "eslint . --ext=js,jsx --fix; exit 0",
"install:clean": "rm -rf node_modules/ && rm -rf package-lock.json && npm install && npm start",
"compile-sass": "node-sass src/assets/scss/material-dashboard-pro-react.scss src/assets/css/material-dashboard-pro-react.css",
"minify-sass": "node-sass src/assets/scss/material-dashboard-pro-react.scss src/assets/css/material-dashboard-pro-react.min.css --output-style compressed",
"map-sass": "node-sass src/assets/scss/material-dashboard-pro-react.scss src/assets/css/material-dashboard-pro-react.css --source-map true"
},
"optionalDependencies": {
"#types/googlemaps": "3.30.16",
"#types/markerclustererplus": "2.1.33",
"ajv": "6.9.1",
"prettier": "1.16.4"
},
"devDependencies": {
"eslint-config-prettier": "4.0.0",
"eslint-plugin-prettier": "3.0.1",
"redux-devtools": "^3.5.0",
"remote-redux-devtools": "^0.5.16",
"copyfiles": "^1.2.0",
"workbox-cli": "^3.5.0"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
]
}
these are screenshots from the google inspector:
manifest
service-worker
the page has the ssl certificate configured too and this is the report generated by google lighthouse:
Google lighthouse report
What is missing to solve these problems?

Unable to access jQuery from my views on RoR

I need to access jquery from my views, and I can't figure out how to make rails inject it into the pages. I'm testing for having jquery with the following code:
=render 'nav'
:javascript
if (typeof jQuery != 'undefined') {
// jQuery is loaded => print the version
alert(jQuery.fn.jquery);
} else {
alert("JQuery undefined");
}
It's always been "jquery undefined".
I've tried many things including adding jquery-rails to the Gemfile. Running yarn add jquery.
I tried modifying config/webpack/environment.js to be like this:
const { environment } = require('#rails/webpacker')
const merge = require('webpack-merge')
const webpack = require('webpack')
// Add an additional plugin of your choosing : ProvidePlugin
environment.plugins.prepend('Provide', new webpack.ProvidePlugin({
$: 'jquery',
JQuery: 'jquery',
jquery: 'jquery',
'window.Tether': "tether",
Popper: ['popper.js', 'default'], // for Bootstrap 4
})
)
const envConfig = module.exports = environment
const aliasConfig = module.exports = {
resolve: {
alias: {
jquery: 'jquery/src/jquery'
}
}
}
module.exports = merge(envConfig.toWebpackConfig(), aliasConfig)
I added references to jquery also under app/assets/javascripts/application.js
//= require jquery_ujs
//= require jquery
//= require_tree .
//= require bootstrap-sprockets
Here is app/views/layouts/application.html.haml:
<!DOCTYPE html>
%html
%head
%title Imagehost
= csrf_meta_tags
= csp_meta_tag
%meta{"name"=>"viewport", "content"=>"width=device-width", "initial-scale"=>"1", "shrink-to-fit"=>"no"}
= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload'
= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload'
%body
= yield
There are no error messages on the console.
The ProvidePlugin as you've configured it will require jQuery (when missing) for legacy scripts bundled by Webpack. It does not expose jQuery to the global scope, which explains why it is undefined in your HAML template.
There are a number of ways you can accomplish this, though I'd recommend extending your Webpack configuration using the expose-loader for jQuery. The expose-loader "exposes" variables to the global scope from Webpack.
yarn add expose-loader
// config/webpack/environment.js
const { environment } = require('#rails/webpacker')
environment.loaders.prepend('jquery', {
test: require.resolve('jquery'),
use: [{
loader: 'expose-loader',
options: 'jQuery'
},{
loader: 'expose-loader',
options: '$'
}]
})
With the above config added, you should be able to access window.$ and window.jQuery from your HAML templates.

Angular component not executing with Webpack

Short Version:
I'm building an app with Angular2 and Webpack. I have the bundles building successfully, but when I include them on my page, the angular components loading. No errors are showing up.
webpack.config.js
"use strict";
let webpack = require('webpack');
let ExtractTextPlugin = require('extract-text-webpack-plugin');
let helpers = require('./webpack.helpers.js');
let HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
'app': helpers.root('/Modules/Shared/Main.ts'),
'vendor': helpers.root('/External/Vendor.ts'),
'polyfills': helpers.root('/External/Polyfill.ts')
},
devtool: 'source-map',
resolve: {
extensions: ['.ts', '.js', '.json', '.css', '.scss', '.html']
},
output: {
path: helpers.root('/wwwroot/scripts'),
filename: '[name].js'
},
module: {
rules: [
{
test: /\.ts$/,
loaders: [
{ loader: 'awesome-typescript-loader', options: { tsConfig: 'tsconfig.json' } },
'angular-router-loader',
'angular2-template-loader',
'source-map-loader',
'tslint-loader'
]
},
{
test: /\.(png|jpg|gif|woff|woff2|ttf|svg|eot)$/,
loader: 'file-loader?name=assets/[name]-[hash:6].[ext]'
},
{
test: /favicon.ico$/,
loader: 'file-loader?name=/[name].[ext]'
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract({
fallbackLoader: "style-loader",
loader: "css-loader"
})
},
{
test: /\.scss$/,
exclude: /node_modules/,
loaders: ['style-loader', 'css-loader', 'sass-loader']
},
{
test: /\.html$/,
loader: 'raw-loader'
}
]
},
plugins: [
new ExtractTextPlugin('css/[name].bundle.css'),
new webpack.NoEmitOnErrorsPlugin(),
// Workaround for angular/angular#11580
new webpack.ContextReplacementPlugin(
// The (\\|\/) piece accounts for path separators in *nix and Windows
/angular(\\|\/)core(\\|\/)#angular/,
'Modules/', // location of your src
{} // a map of your routes
),
new webpack.optimize.CommonsChunkPlugin({
name: ['app', 'vendor', 'polyfills']
}),
new webpack.ProvidePlugin({
jQuery: 'jquery',
$: 'jquery',
jquery: 'jquery',
}),
new HtmlWebpackPlugin()
]
};
tsconfig.json
{
"compilerOptions": {
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"module": "commonjs",
"moduleResolution": "node",
"noEmitOnError": true,
"noImplicitAny": true,
"removeComments": true,
"skipLibCheck": true,
"sourceMap": true,
"target": "es5"
},
"exclude": [
"node_modules",
"wwwroot"
],
"compileOnSave": true
}
The files are being generated correctly:
http://imgur.com/a/xzw0E
_Layout.cshtml
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>#ViewData["Title"]</title>
<base href="/" />
</head>
<body style="background-color: #333;">
#RenderBody()
<script type="text/javascript" src="/scripts/polyfills.js"></script>
<script type="text/javascript" src="/scripts/vendor.js"></script>
#RenderSection("scripts", required: false)
</body>
</html>
index.cshtml
#using System.Threading.Tasks
#{
ViewData["Title"] = "Home Page";
}
<div style="height: 100%;">
<app-component>Loading...</app-component>
</div>
#section Scripts{
<script type="text/javascript" src="/scripts/app.js"></script>
}
The component I'm expecting to see looks like this:
import { Component } from '#angular/core';
#Component({
selector: 'app-component'
})
export class AppComponent {
constructor() {
console.log('I\'m running !!!!');
}
}
But when I generate the page, it looks like this:
http://imgur.com/a/YrPJf
with no errors in the console:
http://imgur.com/a/Xepl2
Any help is greatly appreciated
Seems you forgot about bootstrapping your application via
platformBrowserDynamic().bootstrapModule(AppModule);

Resources