I'm following the instruction of this site and I'm already trying with an empty create-react-app project and It's working fine
But when I'm trying with my existing project after deploy process was done It said
Firebase Hosting Setup Complete
You're seeing this because you've successfully setup Firebase Hosting. Now it's time to go build something extraordinary!
So I'm pretty curious what I missing
here's package.json
{
"name": "iplace",
"version": "0.1.0",
"private": false,
"dependencies": {
"node-sass": "^4.10.0",
"react": "^16.6.3",
"react-dom": "^16.6.3",
"react-router": "^4.3.1",
"react-router-dom": "^4.3.1",
"react-scripts": "2.1.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
]
}
firebase.json
{
"hosting": {
"public": "build",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
]
}
}
I already execute firebase init (change public-> build) > npm run build > firebase deploy
Here's project structure
And here's index.html file (I'm pretty wonder why index.html still have welcome to firebase wording...)
<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Welcome to Firebase Hosting</title><script defer="defer" src="/__/firebase/5.7.0/firebase-app.js"></script><script defer="defer" src="/__/firebase/5.7.0/firebase-auth.js"></script><script defer="defer" src="/__/firebase/5.7.0/firebase-database.js"></script><script defer="defer" src="/__/firebase/5.7.0/firebase-messaging.js"></script><script defer="defer" src="/__/firebase/5.7.0/firebase-storage.js"></script><script defer="defer" src="/__/firebase/init.js"></script><style media="screen">body{background:#eceff1;color:rgba(0,0,0,.87);font-family:Roboto,Helvetica,Arial,sans-serif;margin:0;padding:0}#message{background:#fff;max-width:360px;margin:100px auto 16px;padding:32px 24px;border-radius:3px}#message h2{color:#ffa100;font-weight:700;font-size:16px;margin:0 0 8px}#message h1{font-size:22px;font-weight:300;color:rgba(0,0,0,.6);margin:0 0 16px}#message p{line-height:140%;margin:16px 0 24px;font-size:14px}#message a{display:block;text-align:center;background:#039be5;text-transform:uppercase;text-decoration:none;color:#fff;padding:16px;border-radius:4px}#message,#message a{box-shadow:0 1px 3px rgba(0,0,0,.12),0 1px 2px rgba(0,0,0,.24)}#load{color:rgba(0,0,0,.4);text-align:center;font-size:13px}#media (max-width:600px){#message,body{margin-top:0;background:#fff;box-shadow:none}body{border-top:16px solid #ffa100}}</style><link href="/static/css/main.6f735e8f.chunk.css" rel="stylesheet"></head><body><div id="message"><h2>Welcome</h2><h1>Firebase Hosting Setup Complete</h1><p>You're seeing this because you've successfully setup Firebase Hosting. Now it's time to go build something extraordinary!</p><a target="_blank" href="https://firebase.google.com/docs/hosting/">Open Hosting Documentation</a></div><p id="load">Firebase SDK Loadingβ¦</p><script>document.addEventListener('DOMContentLoaded', function() {
// // π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯
// // The Firebase SDK is initialized and available here!
//
// firebase.auth().onAuthStateChanged(user => { });
// firebase.database().ref('/path/to/ref').on('value', snapshot => { });
// firebase.messaging().requestPermission().then(() => { });
// firebase.storage().ref('/path/to/ref').getDownloadURL().then(() => { });
//
// // π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯
try {
let app = firebase.app();
let features = ['auth', 'database', 'messaging', 'storage'].filter(feature => typeof app[feature] === 'function');
document.getElementById('load').innerHTML = `Firebase SDK loaded with ${features.join(', ')}`;
} catch (e) {
console.error(e);
document.getElementById('load').innerHTML = 'Error loading the Firebase SDK, check the console.';
}
});</script><script>!function(l){function e(e){for(var r,t,n=e[0],o=e[1],u=e[2],f=0,i=[];f<n.length;f++)t=n[f],p[t]&&i.push(p[t][0]),p[t]=0;for(r in o)Object.prototype.hasOwnProperty.call(o,r)&&(l[r]=o[r]);for(s&&s(e);i.length;)i.shift()();return c.push.apply(c,u||[]),a()}function a(){for(var e,r=0;r<c.length;r++){for(var t=c[r],n=!0,o=1;o<t.length;o++){var u=t[o];0!==p[u]&&(n=!1)}n&&(c.splice(r--,1),e=f(f.s=t[0]))}return e}var t={},p={2:0},c=[];function f(e){if(t[e])return t[e].exports;var r=t[e]={i:e,l:!1,exports:{}};return l[e].call(r.exports,r,r.exports,f),r.l=!0,r.exports}f.m=l,f.c=t,f.d=function(e,r,t){f.o(e,r)||Object.defineProperty(e,r,{enumerable:!0,get:t})},f.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},f.t=function(r,e){if(1&e&&(r=f(r)),8&e)return r;if(4&e&&"object"==typeof r&&r&&r.__esModule)return r;var t=Object.create(null);if(f.r(t),Object.defineProperty(t,"default",{enumerable:!0,value:r}),2&e&&"string"!=typeof r)for(var n in r)f.d(t,n,function(e){return r[e]}.bind(null,n));return t},f.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return f.d(r,"a",r),r},f.o=function(e,r){return Object.prototype.hasOwnProperty.call(e,r)},f.p="/";var r=window.webpackJsonp=window.webpackJsonp||[],n=r.push.bind(r);r.push=e,r=r.slice();for(var o=0;o<r.length;o++)e(r[o]);var s=n;a()}([])</script><script src="/static/js/1.734eb6b0.chunk.js"></script><script src="/static/js/main.14da6ff9.chunk.js"></script></body></html>
First task
You need to replace this code with the following one in index.html of public folder:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web Chat Application created using professional technologies"
/>
<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>Programmer Dost</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>
Second Task:
Delete .firebaserc file.
Delete firebase.json file.
Third Task:
Delete β.firebaseβ folder.
Delete βbuildβ folder.
Fourth Task:
run the command: firebase init
it will ask:
Which Firebase features do you want to set up for this directory?
choose: Hosting: Configure files for Firebase Hosting and (optionally) set up GitHub Action deploys
then select:
Please select an option: Use an existing project
then select your project name
Fifth Task:
(Type the folder name where you want to initialize the app. It would be build in case of react app.)
What do you want to use as your public directory? build
Sixth Task:
(Select Yes in single page app)
Configure as a single-page app (rewrite all urls to /index.html)? Yes
Seventh Task:
Set up automatic builds and deploys with GitHub? No
Eigth Task:
(Run this Command)
npm run build /yarn build
Last Task:
(Run this command)
firebase deploy
In my case that's How it worked.
You have overwritten you index.html with the default one created by firebase during firebase init.
ToFIX:
delete current index.html
get your original index.html
run firebase init again.
when it ask you to overwrite you "index.html" - say NO.
I had the same problem and it was confusing because it deployed. Turns out I had to make sure to run
npm run build
firebase deploy
then wait a few minutes for the site to show up. This assumes you did not modify the react index.html file
You need to add this line in your index.html file.
<div id="root"></div>
Then it will work, You can add it before try{}.
in firebase.json Instead of
<i>"public": "build" </i>
put
<i>"public": "./build" </i>
and then
npm run build
firebase deploy
You say Β«I'm pretty wonder why index.html still have welcome to firebase wordingΒ». Most probably it is simply because your build process doesnβt overwrite it.
It is difficult to say from the elements and images you have added to your post, but when you do npm run build you either donβt build your react project or you build it in a dist directory that is not at all the public Firebase folder. You should copy the result of your build to the public folder and then re-deploy.
Related
I'm using Django 4 and wish to integrate a ReactJS application within the Django framework.
I chose to use the exact approach here to start and installed it identically as outlined.
Here's a list of the installed components and versions:
βββ #babel/core#7.20.12
βββ #babel/preset-env#7.20.2
βββ #babel/preset-react#7.18.6
βββ babel-loader#9.1.2
βββ clean-webpack-plugin#4.0.0
βββ css-loader#6.7.3
βββ react-dom#18.2.0
βββ react#18.2.0
βββ style-loader#3.3.1
βββ webpack-bundle-tracker#0.4.3
βββ webpack-cli#5.0.1
βββ webpack#5.75.0
I do not want to post all of my code here since it is 100% identical to the code in the link above.
Unfortunately, I'm receiving a strange error in the console:
GET http://127.0.0.1:8001/frontend/static/frontend/frontend-dc3188e75be82e0a01e0.js net::ERR_ABORTED 404 (Not Found)
127.0.0.1/:1 Refused to execute script from 'http://127.0.0.1:8001/frontend/static/frontend/frontend-dc3188e75be82e0a01e0.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
This appears to be related to the path, but the referenced JS filename is spelled correctly and exists at the exact referenced path.
The server console also displays a similar error:
Not Found: /frontend/static/frontend/frontend-dc3188e75be82e0a01e0.js
the link you provided is an old tutorial. You should always follow the documentation. Based on docs
You must generate the front-end bundle using webpack-bundle-tracker
before using django-webpack-loader. You can compile the assets and
generate the bundles by running:
npx webpack --config webpack.config.js --watch
this is webpack config setting related to webpack-bundle-tracker. It spits out the webpack-stats.json file and looks like django webpack-loader reads from this .json file
const path = require('path');
const webpack = require('webpack');
const BundleTracker = require('webpack-bundle-tracker');
module.exports = {
context: __dirname,
entry: './assets/js/index',
output: {
path: path.resolve('./assets/webpack_bundles/'),
filename: "[name]-[hash].js"
},
plugins: [
new BundleTracker({filename: './webpack-stats.json'})
],
}
and then:
WEBPACK_LOADER = {
'DEFAULT': {
'CACHE': not DEBUG,
'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'),
'POLL_INTERVAL': 0.1,
'IGNORE': [r'.+\.hot-update.js', r'.+\.map'],
}
Thank you for the feedback. This is how I ultimately performed this integration entirely using a combination of online tutorials, the feedback here and the github repo for django-webpack-loader.
Please see the comment at the very bottom for details on resolving the path issue with DigitalOcean Spaces.
Keep in mind this approach below eliminates a lot of the unnecessary steps and ensures the latest versions of the software are used. References are below.
If React and React-Dom are not already installed into your environment, start here:
npm install react react-dom
A: Setup the Django App and Dependencies
Create the frontend app in Django
python manage.py startapp frontend
Update the list of installed apps within settings.py or base.py:
INSTALLED_APPS = [
'frontend',
...
]
Create the templates folder for the frontend app. In my case, my Templates directory is in the root of the project, so under the folder I added 'frontend': ./templates/frontend
Create the template in the newly created frontend folder: ./templates/frontend/index.html
Add the following into the index.html, which contains Django tags to use later for rendering the bundle:
<!DOCTYPE html>
{% load render_bundle from webpack_loader %}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Site</title>
</head>
<body>
<div id="app"></div>
<p>hello</p>
{% render_bundle 'frontend' %}
</body>
</html>
Create the view in the app frontend/views.py
from django.shortcuts import render
def index(request):
return render(request, 'frontend/index.html')
Update the URL pattern within urls.py at the project level: config/urls.py. In this case, the react app is loading from the root of the domain. I recommend using this configuration (outlined in step 7 and 8) or you will receive path errors. This can be changed later.
path('', include('frontend.urls'))
Update the URL patterns within urls.py at the app level:
path('', views.index)
At this point, you can test and run the server or continue on. If you test, remember that you have 2 Django tags loading in Step 5 that you will need to comment out.
python manage.py runserver
B: Install React & Babel
From the root of the project, run the following command to create the package.json file.
npm init -y
Setup Babel.
npm install --save-dev #babel/core
Install Babel plugins:
npm install --save-dev #babel/preset-env #babel/preset-react
Create a .babelrc file in the root of your project and add this into it:
{
"presets": ["#babel/preset-env", "#babel/preset-react"]
}
C: Install & Configure Webpack
Install Webpack and the additional packages.
npm install --save-dev webpack webpack-cli webpack-bundle-tracker babel-loader css-loader style-loader clean-webpack-plugin
Create a webpack.config.js file in the root of the project.
const path = require('path');
const webpack = require('webpack');
const BundleTracker = require('webpack-bundle-tracker');
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
module.exports = {
context: __dirname,
entry: {
frontend: './frontend/src/index.js',
},
output: {
path: path.resolve('./frontend/static/frontend/'),
filename: '[name]-[hash].js',
publicPath: 'static/frontend/',
},
plugins: [
new CleanWebpackPlugin(),
new BundleTracker({ filename: './webpack-stats.json' })
],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: ['babel-loader'],
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
],
},
}
Add the following scripts to your package.json file located in the project root. You should already have scripts in this file; just add the two new lines of code for "dev" and "build".:
{
...,
"scripts": {
...,
"dev": "webpack --config webpack.config.js --watch --mode development",
"build": "webpack --config webpack.config.js --mode production"
}
}
C: Create a basic React APP for testing
In the frontend app folder, create a folder called src.
In the src folder, create an App.js file. Be sure to follow the capitalization. And, add the following to it:
import React from 'react'
const App = () => {
return (
<div>Hello, World!</div>
)
}
export default App
In the src folder, create an index.js file and add the following to it:
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
ReactDOM.render(
<App />,
document.getElementById('app')
)
D: Install Webpack Loader & Configure
Run the following command:
pip install django-webpack-loader
Update the list of installed apps within settings.py or base.py:
INSTALLED_APPS = (
...
'webpack_loader',
...
)
Also, update the Webpack Loader configurations in the settings.py or base.py file:
WEBPACK_LOADER = {
'DEFAULT': {
'CACHE': not DEBUG,
'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'),
'POLL_INTERVAL': 0.1,
'IGNORE': [r'.+\.hot-update.js', r'.+\.map'],
}
}
If you receive an error related to DEBUG, check the available options in the django-webpack-loader instructions (see below for link).
E: Compile the frontend asset files and test
If you commented out the django tags in step A9, remove the comment before proceeding.
Run the following command:
npx webpack --config webpack.config.js --watch
Run your server:
python manage.py runserver
Open your browser and navigate to the root of your site. You should receive a Hello World printout on the screen. If not, and you only receive an empty white screen, the react assets are not loading. Check the server console and/or the browser console for errors.
References:
Outdated Tutorial
https://dev.to/zachtylr21/how-to-serve-a-react-single-page-app-with-django-1a1l
django-webpack-loader repo
https://github.com/django-webpack/django-webpack-loader
I've been upgrading my CRA project to TailwindCSS 3, but now CSS nesting no longer works. Upon starting the server, the console spits out:
(8:3) Nested CSS was detected, but CSS nesting has not been configured correctly.
Please enable a CSS nesting plugin *before* Tailwind in your configuration.
See how here: https://tailwindcss.com/docs/using-with-preprocessors#nesting
However, I don't see what must be done to correct this. I've tried setting up a plain CRA project with Tailwind (following this guide) just to make sure I have no conflicts, and still no success.
postcss.config.js:
module.exports = {
plugins: {
"tailwindcss/nesting": {},
tailwindcss: {},
autoprefixer: {},
},
};
As you can see, I have added the nesting plugin before Tailwind. It appears to me as if the plugin isn't being detected whatsoever. I've also tried replacing it with postcss-nesting with same outcome.
Note: I've also tried using the array syntax with require('tailwind/nesting') like the guide suggests.
Interestingly, removing all plugins from postcss.config.js (or using a require that fails to resolve) still outputs the same error, implying that this file isn't needed to get Tailwind to load. Maybe I am missing something that causes the whole postcss.config.js file to not be loaded in the first place?
index.js:
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
ReactDOM.render(
<React.StrictMode>
<div className="a">
aaa
<div className="b">bbb</div>
</div>
</React.StrictMode>,
document.getElementById("root")
);
index.css:
#tailwind base;
#tailwind components;
#tailwind utilities;
.a {
#apply text-blue-500;
.b {
#apply text-green-500;
}
}
package.json: (omitted things for brevity)
{
"name": "tailwindtest",
"dependencies": {
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-scripts": "5.0.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"devDependencies": {
"autoprefixer": "^10.4.2",
"postcss": "^8.4.5",
"tailwindcss": "^3.0.12"
}
}
This is mostly just bad news.
Create React App's Tailwind support means that they will detect tailwind.config.js in the project and add tailwindcss to their existing postcss configuration. Source in CRA
The guide that Tailwind offers on their site creates a dummy postcss.config.js - Making changes in this file does not change the actual postcss configuration. (misleading if anything)
This is a known issue currently - Github discussion on Tailwind support PR between Adam Wathan (Tailwind founder) and Ian Sutherland (CRA maintainer). But it does not seem like there is an intention to be fixed soon.
If you want to use nesting (or any PostCSS plugin really) is to eject from CRA using:
npm run eject
After ejecting you can find CRA's postcss configuration in config/webpack.config.js - look for postcss-loader. Editing the configuration there can enable any postcss features.
PS: Look out for postcss-preset-env in the default configuration while enabling nesting. Tailwind requires you to edit configuration if this is present.
I use CRA and to fix the issue I used postinstall to run a script after npm install or yarn. The script is changing the web pack config of CRA after all dependencies are installed(a temporary solution of cause).
You can find the web pack config in node_modules/react-scripts/config/webpack.config.js.
The script adds my postcss packages to the actual CRA web pack config.
WHY? CRA does not respect any postcss config in your repo
Have also a look at this comment to see how you should use postinstall https://github.com/facebook/create-react-app/issues/2133#issuecomment-347574268.
I also added tailwindcss/nesting before tailwindcss because tailwind is throwing a warning when it sees any nested css. The warning was blocking my CI since CI=true in CRA means all warnings are treated as errors.
Here is the script that is running in my repo.
FILE="node_modules/react-scripts/config/webpack.config.js"
function replace {
TARGET_FILE=$1
PATTERN_TO_FIND=$2
VALUE_FOR_REPLACEMENT=$3
OLD_FILE_CONTENT=$(cat "$TARGET_FILE") # we need to collect the content of the file so we can overwrite it in the next command
echo "$OLD_FILE_CONTENT" | sed -e "s/$PATTERN_TO_FIND/$VALUE_FOR_REPLACEMENT/g" > "$TARGET_FILE"
}
# add postcss-nesting
replace "$FILE" "'postcss-flexbugs-fixes'," "'postcss-flexbugs-fixes','postcss-nesting',"
# add tailwind/nesting
replace "$FILE" "'tailwindcss'," "'tailwindcss\/nesting', 'tailwindcss',"
acording to #aricma answer, is easier if you create a script.js file on parent directory (same as package.json) and add this on package.json
"scripts": {
"postinstall": "node script.js",
...
}
and this on script.js
const fs = require('fs');
fs.readFile('node_modules/react-scripts/config/webpack.config.js', 'utf8', (err, data) => {
if (err) {
return console.log(err);
}
const result = data.replace("'postcss-flexbugs-fixes',", "'postcss-flexbugs-fixes','postcss-nesting',").replace("'tailwindcss',", "'tailwindcss/nesting', 'tailwindcss',");
fs.writeFile('node_modules/react-scripts/config/webpack.config.js', result, 'utf8', (err) => {
if (err) {
return console.log(err);
}
return console.log(true);
});
return console.log(true);
});
I have been trying to deploy a Server-side rendered react app I built with NextJS on Azure. I set up the Azure pipeline and release successfully but after running it the app doesn't seem to load up when I went to the azure website URL. The build file content is different from a client rendered app. Please share a resource or explanation about deploying SSR React apps (on Azure).
I used this resource to set up the pipeline and I encountered no error but the URL is still not loading the app.
As mentioned by #James in the comment in Doris's answer, using a custom server.js in a Next.js app would make it slower in production because the routes aren't pre-built. Using next build followed by next start would solve this issue. But for you to be able to do that, you should not have a server.js.
And as per Microsoft documentation for deploying Node JS / Next JS application on Azure Linux web app, the recommended way is to use PM2 rather than using npm start (or) node server.js.
So you don't need server.js or web.config. All you need to do is to have a file called ecosystem.config.js with the below content
module.exports = {
apps: [
{
name: "my-nextJs-site",
script: "./node_modules/next/dist/bin/next",
args: "start -p " + (process.env.PORT || 3000),
watch: false,
autorestart: true,
},
],
};
and have the startup command for your Azure app to be this
pm2 --no-daemon start /home/site/wwwroot/ecosystem.config.js
and no change in your package.json scripts
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
Azure Windows App Service
pm2 is not available in Azure Windows Service - it uses IIS Server. Check out the following answer and its linked questions.
Other useful resources:
Deploying a Node.js application on Windows IIS using a reverse proxy
Deploying Nextjs on IIS server without custom server
Deploying Nextjs on Digital Ocean - App Platform
You need two file: server.js and web.config, and modify package.json like below. I've answered a question about deploy nextjs app step by step, you could have a look at this.
package.json modify.
"scripts": {
"dev": "node server.js",
"build": "next build",
"start": "node server.js"
server.js (create this file with the code below:)
const { createServer } = require('http')
const next = require('next')
const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
app.prepare().then(() => {
createServer((req, res) => {
const parsedUrl = new URL(req.url, 'http://w.w')
const { pathname, query } = parsedUrl
if (pathname === '/a') {
app.render(req, res, '/a', query)
} else if (pathname === '/b') {
app.render(req, res, '/b', query)
} else {
handle(req, res, parsedUrl)
}
}).listen(port, (err) => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
})
})
web.config (create this file with the code below:)
<?xml version="1.0" encoding="utf-8"?>
<!--
This configuration file is required if iisnode is used to run node processes behind
IIS or IIS Express. For more information, visit:
https://github.com/tjanczuk/iisnode/blob/master/src/samples/configuration/web.config
-->
<configuration>
<system.webServer>
<!-- Visit http://blogs.msdn.com/b/windowsazure/archive/2013/11/14/introduction-to-websockets-on-windows-azure-web-sites.aspx for more information on WebSocket support -->
<webSocket enabled="false" />
<handlers>
<!-- Indicates that the server.js file is a node.js site to be handled by the iisnode module -->
<add name="iisnode" path="server.js" verb="*" modules="iisnode"/>
</handlers>
<rewrite>
<rules>
<!-- Do not interfere with requests for node-inspector debugging -->
<rule name="NodeInspector" patternSyntax="ECMAScript" stopProcessing="true">
<match url="^server.js\/debug[\/]?" />
</rule>
<!-- First we consider whether the incoming URL matches a physical file in the /public folder -->
<rule name="StaticContent">
<action type="Rewrite" url="public{REQUEST_URI}"/>
</rule>
<!-- All other URLs are mapped to the node.js site entry point -->
<rule name="DynamicContent">
<conditions>
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="True"/>
</conditions>
<action type="Rewrite" url="server.js"/>
</rule>
</rules>
</rewrite>
<!-- 'bin' directory has no special meaning in node.js and apps can be placed in it -->
<security>
<requestFiltering>
<hiddenSegments>
<remove segment="bin"/>
</hiddenSegments>
</requestFiltering>
</security>
<!-- Make sure error responses are left untouched -->
<httpErrors existingResponse="PassThrough" />
<!--
You can control how Node is hosted within IIS using the following options:
* watchedFiles: semi-colon separated list of files that will be watched for changes to restart the server
* node_env: will be propagated to node as NODE_ENV environment variable
* debuggingEnabled - controls whether the built-in debugger is enabled
See https://github.com/tjanczuk/iisnode/blob/master/src/samples/configuration/web.config for a full list of options
-->
<!--<iisnode watchedFiles="web.config;*.js"/>-->
</system.webServer>
</configuration>
I'm trying to use test framework Jest with Next.js and styled-jsx.
This is my external css style.
import css from 'styled-jsx/css';
export const TextStyle = css`
p {
font-size: 14px;
color: #a8a8a8;
}
`;
and this is my package.json script. It works well.
"test": "jest --verbose",
I want to use coverage option. so I tried this "test": "jest --coverage --verbose", but it is not working.
ReferenceError: css is not defined
I have read this https://github.com/zeit/styled-jsx/issues/436. However, the issue is still open and doesn't help me.
How can I fix it?
styled-jsx docs mention how to solve it but that didn't work well for me.
I made it work by doing the following:
Set the node env in your package.json test scripts to "test" like so (can add the --verbose flag as well if you want):
"test": "NODE_ENV=test jest",
"test:coverage": "NODE_ENV=test jest --coverage"
In your babel configuration (.babelrc in my case) add babel-test: true to the test env config like so (refer to the Next docs for more details):
{
// this is your original config, it's required if you don't have a babel config yet and are using `Next` since `Next` normally does it under the hood for you:
"presets": [
[
"next/babel",
]
],
// this is what you're adding:
"env": {
"test": {
"presets": [
[
"next/babel",
{
"styled-jsx": {
"babel-test": true
}
}
]
]
}
}
}
Your tests should now pass but may show a warning saying:
styled-jsx/css: if you are getting this error it means that your css tagged template literals were not transpiled.
In that case you should add a jest auto mock for styled-jsx/css by adding a new file with this exact path from the root of your project (the __mocks__ folder has to be a sibling of your node_modules folder) /__mocks__/styled-jsx/css.js:
function css() {
return ""
}
module.exports = css
*Note: what this whole setup does is disable styled-jsx transpilation when you run your tests which means that the generated classes will not be generated in your test components. In my case for example that breaks my tests because I'm relying on the generated classes for hiding some elements and my tests rely on those elements being hidden. I'm now trying to figure out a way around that but it may not be an issue in your case.
I have a webpack4+babel bundler setup for a react web app. In a LESS file, I reference a local font. This font gets copied over to the dist folder on build and its filename is hashed. I want to be able to preload this font.
Here is my LESS file:
#font-face {
font-family: 'Test';
src: url('../fonts/test.ttf') format('truetype');
font-weight: 400;
}
I have tried the following approaches but so far with no success:
Add custom import to my app's main JS file.
import(/* webpackPreload: true */ "../fonts/test.ttf");
Here is my .babelrc file:
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
],
"plugins": [
"#babel/plugin-syntax-dynamic-import"
]
}
Running webpack does not produce preload directions anywhere as far as I can see in the outputted html - I have searched through the dist folder contents and found nothing.
preload-webpack-plugin
I add this to my webpack.config.js file:
plugins: [
new HtmlWebpackPlugin(),
new PreloadWebpackPlugin({
rel: 'preload',
as(entry) {
if (/\.css$/.test(entry)) return 'style';
if (/\.woff$/.test(entry)) return 'font';
if (/\.png$/.test(entry)) return 'image';
return 'script';
}
})
]
This creates preloads for the JS script file bundles but not for the CSS and fonts.
Any ideas on how to get this to work?
was able to make it work on webpack4 by installing version 3beta and using while list option:
yarn add -D preload-webpack-plugin#3.0.0-beta.3
new PreloadWebpackPlugin({
rel: 'preload',
as: 'font',
include: 'allAssets',
fileWhitelist: [/\.(woff2?|eot|ttf|otf)(\?.*)?$/i],
}),
Posting this since I think it might help someone in a similar position - I realize it doesn't solve the described issue.
Had the same problem - didn't need to hash my font-files but had another part of the url that was not static. A bit hackish, but solved my problem. Maybe it can help someone. In theory you can create your own hash-id and set that as the htmlWebpack-plugin variable.
In my index.html
<html>
<head>
<link rel="preload" href="<%= htmlWebpackPlugin.options.woffSrc %>" as="font" type="font/woff" crossorigin>
<link rel="preload" href="<%= htmlWebpackPlugin.options.woff2Src %>" as="font" type="font/woff2" crossorigin>
//rest of html
webpack.prod.conf.js - updated HtmlWebpackPlugin
plugins: [
new HtmlWebpackPlugin({
...config,
woffSrc: `https://url.to.my.page.com/${ASSETS_FOLDER}/static/assets/fonts/GilroyRegular.woff`,
woff2Src: `https://url.to.my.page.com/${ASSETS_FOLDER}/static/assets/fonts/GilroyExtraBold.woff2`
})
]
I reasoned that the font-files didn't need to have the hash - since that is mainly used to control cache and I won't change the font files, so I turned that of in my webpack file-loader. Please correct me if I'm wrong here.
Having the loader:
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 2000,
name: utils.assetsPath('assets/fonts/[name].[ext]')
}
}
Was unable to get the preload-webpack-plugin to work due to build errors and got tired troubleshooting after 2 days.
I found a workaround for this. It isn't pleasant but I think is't better than nothing.
here I only wanted to preload woff and woff2 files.
new PreloadWebpackPlugin({
rel: 'preload',
include: 'allAssets',
fileBlacklist: [/\.(js|ttf|png|eot|jpe?g|css|svg)/]
}),
I think was able to fix this by moving the font file to my public folder, and then moving my #font-face definition to <style> tags within my index.html file, where I could use %PUBLIC_URL% to specify the location to Webpack:
<head>
<!-- Some stuff... -->
<link rel="preload" href="%PUBLIC_URL%/my-font-file.ttf" as="font" />
<style>
#font-face {
font-family: my-font-name;
src: url('%PUBLIC_URL%/my-font-file.ttf');
}
</style>
</head>
(with my-font-file.ttf in the public folder of my project)
I believe to preload the font file you can just manually specify the <link /> in your index.html file:
<link rel="preload" href="../fonts/test.ttf" as="font" type="font/ttf">
See this for some details.