Snowpack is not reloading - reactjs

i started to use snowpack and ran into a big problem. Snowpack is not hot reloading for me.
I tried the basic minimal template, a svelte template and a react template - Everytime the same problem. I also created on from scratch based on the getting started.
Here a my example files:
index.jsx
import React from 'https://cdn.skypack.dev/react';
import ReactDom from 'https://cdn.skypack.dev/react-dom';
ReactDom.render(
<React.StrictMode>
<div>This is working</div>
</React.StrictMode>,
document.getElementById('root'),
);
// Hot Module Replacement (HMR) - Remove this snippet to remove HMR.
// Learn more: https://www.snowpack.dev/concepts/hot-module-replacement
if (import.meta.hot) {
import.meta.hot.accept();
}
snowpack.config.js
/** #type {import("snowpack").SnowpackUserConfig } */
module.exports = {
mount: {
public: { url: '/', static: true },
src: { url: '/dist' },
},
plugins: ['#snowpack/plugin-react-refresh'],
packageOptions: {
/* ... */
},
devOptions: {
/* ... */
},
buildOptions: {
/* ... */
},
};
package.json
{
"name": "chatclient",
"version": "1.0.0",
"description": "",
"scripts": {
"start": "snowpack dev",
"build": "snowpack build",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#snowpack/plugin-react-refresh": "^2.4.0",
"snowpack": "^3.0.11"
}
}
I hope someone can help me. Snowpack is such an amazing tool but i can't get it to work.

I found a solution
Credits
I used to run my dev environment on wsl2. Some no known reason does nodejs not hot reload when you are in wsl2 and the files are on the windows filesystem. Moved everything to my linux filesystem and i worked.
I hope someone will find this helpful!

Related

React is not loaded / Build is not generated

I am trying to create a WordPress plugin with React. I am following this link. I have the following package.json file
{
"name": "test-plugin",
"version": "1.0.0",
"private": true,
"description": "Sample plugin for React",
"main": "index.js",
"devDependencies": {
"#wordpress/scripts": "^13.0.3"
},
"scripts": {
"build": "wp-scripts build",
"check-engines": "wp-scripts check-engines",
"check-licenses": "wp-scripts check-licenses",
"lint:css": "wp-scripts lint-style",
"lint:js": "wp-scripts lint-js",
"lint:pkg-json": "wp-scripts lint-pkg-json",
"start": "wp-scripts start",
"test:e2e": "wp-scripts test-e2e",
"test:unit": "wp-scripts test-unit-js"
},
"author": "thor",
"license": "ISC"
}
I am enqueueing the react script as follows
wp_enqueue_script( 'react-script', plugin_dir_url(__DIR__) . 'build/index.js', ['wp-element'], $this->version, false );
ISSUES
The build react js file is not generated. I have followed the above link and everything was installed correctly. But no index.js file is created in build folder
The script is not working if I enqueue src/index.js instead of build/index.js. The script is loaded but not working as expected. I have the div with id my_app in one of the pages in which the script is loaded.
Following is the react script file
const { render, useState } = wp.element;
const Votes = () => {
const [votes, setVotes] = useState(0);
const addVote = () => {
setVotes(votes + 1);
};
return (
<div>
<h2>{votes} Votes test</h2>
<p>
<button onClick={addVote}>Vote!</button>
</p>
</div>
);
};
render(<Votes />, document.getElementById('my_app'));
Had the same problem with you and I spent good couple of hours trying to fix this. Here are problem that I encountered:
One of the issues was the node_modules folder was in the wrong place, supposed to be at the same level as your theme.
The other one was I had to run npm run start instead of npm start. Whenever wp-scripts output something like this :
asset index.js 4.35 KiB [emitted] (name: index)
1 related asset asset index.asset.php 107 bytes [emitted] (name: index)
means it is working. If don't get that means something wrong with your folder location.
Try and let me know.

Building a React-Electron app using electron-builder, index.js loads inside pre tags

I have an app that I'm now trying to build to distribute for testing.
I'm using React and Electron with electron-builder to build the app itself. I'm not a web developer so I've been trying to keep things basic and just get something to work.
After about five hours I was finally able to get the app to build somewhat properly and launch, but when it loads index.js (the first page in the app) it displays the source for index.js instead of rendering the content. In the devtools everything is inside a pre tag.
I've already looked at this thread and tried that but it didn't change anything, and I'm not using service workers as far as I can tell.
What the actual Electron window displays after launching with the devtools alongside.
Here's the createWindow function from main.js.
I've tried doing all kinds of things to the pathname with no effect.
function createWindow() {
const startUrl = process.env.ELECTRON_START_URL || url.format({
pathname: path.join(__dirname, '../src/index.js'),
protocol: 'file:',
slashes: true,
});
mainWindow = new BrowserWindow({
width: 800, height: 600, title: "Electron App", webPreferences: {
nodeIntegration: true
}
});
mainWindow.loadURL(startUrl);
mainWindow.on('closed', function () {
mainWindow = null;
});
}
Here are my scripts from package.json
"scripts": {
"start": "nf start -p 3000",
"start-electron": "set ELECTRON_START_URL=http://localhost:3000 && electron .",
"react-start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"build-electron": "npm run build && electron-builder build --win"
}
Here's the build part too. To be honest, I don't really understand what this is or does but after a few hours of trial and error this is what gets me to the point I am now.
"build": {
"appId": "Test",
"extends": null,
"files": [
"./build/**/*",
"./electron/main.js",
"./src/**/*"
]
}
As far as I can tell, it has something to do with the Electron start URL, because when I removed that from const startUrl in createWindow, running the app using npm start did the same thing as the built Electron app, whereas before using npm would launch the app normally every time.
EDIT after solution:
Modified build in package.json to
"build": {
"appId": "Test",
"extends": null,
"files": [
"./build/**/*",
"./electron/main.js",
"./src/**/*"
],
"directories": {
"buildResources": "./public"
}
}
I haven't tested it without this modification so I'm not sure that it's actually necessary.
Start URL was changed to
const startUrl = process.env.ELECTRON_START_URL || url.format({
pathname: path.join(__dirname, '../build/index.html'),
protocol: 'file:',
slashes: true,
});
You're supposed to set it up with an html file.
const startUrl = process.env.ELECTRON_START_URL || url.format({
pathname: path.join(__dirname, '../src/index.html'),
protocol: 'file:',
slashes: true,
});
Your browser window should load the build/index.html on production mode
const isDev = require("electron-is-dev");
if (isDev) {
mainWindow.loadURL(process.env.ELECTRON_START_URL);
} else {
mainWindow.loadFile(path.join("build", "index.html"));
}

Detox tests are assigned to Undefined, and all e2e are skipped

I installed jest and detox on a fresh react-native init project.
Install jest and jest-circus as per detox docs
Setup iOS build and test configuration
Get the following error consistently on new builds
my .detoxrc.json file:
{
"testRunner": "jest",
"runnerConfig": "e2e/config.json",
"configurations": {
"ios": {
"type": "ios.simulator",
"build": "xcodebuild -workspace ios/rndetox.xcworkspace -scheme rndetox -configuration Debug -sdk iphonesimulator -derivedDataPath ios/build",
"binaryPath": "ios/build/Build/Products/Debug-iphonesimulator/rndetox.app",
"device": {
"type": "iPhone 11"
}
},
"android": {
"type": "android.emulator",
"binaryPath": "SPECIFY_PATH_TO_YOUR_APP_BINARY",
"device": {
"avdName": "Pixel_2_API_29"
}
}
}
}
detox config.json
{
"testEnvironment": "./environment",
"testRunner": "jest-circus/runner",
"testTimeout": 120000,
"testRegex": "\\.e2e\\.js$",
"reporters": ["detox/runners/jest/streamlineReporter"],
"verbose": true
}
and e2e/environment.js
const {
DetoxCircusEnvironment,
SpecReporter,
WorkerAssignReporter,
} = require('detox/runners/jest-circus');
class CustomDetoxEnvironment extends DetoxCircusEnvironment {
constructor(config) {
super(config);
// Can be safely removed, if you are content with the default value (=300000ms)
this.initTimeout = 300000;
// This takes care of generating status logs on a per-spec basis. By default, Jest only reports at file-level.
// This is strictly optional.
this.registerListeners({
SpecReporter,
WorkerAssignReporter,
});
}
}
module.exports = CustomDetoxEnvironment;
I have tried including an init.js with a detox.init but same error.
At the time I tried this, detox was not supported yet on the fresh 0.63 release of React Native. If you build a new project at 0.62 it should be fine. I am not sure if this has been fixed yet though!

Error: Cannot export when target is not server. with next js and zeit-NOW during deployee

I am working a react app where i am using next js and express, I have choose zeit now for servless but when i deploying this facing error Error: No serverless pages were built
next.config.js
const configuration = withTypescript(
withLess({,
target: process.env.NODE_ENV === "development" ? "server" : "serverless",
cssModules: true,
lessLoaderOptions: {
javascriptEnabled: true,
modifyVars: themeVariables // make your antd custom effective
},
exportPathMap: async function(defaultPathMap) {
return {
"/": { page: "/index" },
};
},
webpack: config => {
config.plugins = config.plugins || [];
config.plugins = [
...config.plugins,
// Read the .env file
new Dotenv({
path: path.join(__dirname, "../.env"),
systemvars: true
})
];
return config;
},
})
);
module.exports = configuration;
using next version : "#types/next": "^8.0.0",
now.json
{
"version": 2,
"name": "web",
"builds": [
{ "src": "package.json", "use": "#now/next" }
],
}
inside package json
"scripts": {
"dev": "next src",
"build": "next build src",
"start": "next run build && next start src",
"export": "npm run build && next export src -o ./out",
"now-build": "next build src","
},
Getting error from zeit Now logs
preparing lambda files...
2019-04-19T17:24:04.955Z Error: No serverless pages were built. https://err.sh/zeit/now-builders/now-next-no-serverless-pages-built
at Object.exports.build (/tmp/utils/build-module/node_modules/#now/next/index.js:305:13)
at <anonymous>
please help me here to figure it out.
Thanks.

Transpiling NextJS for IE 10/11; 'Weakset undefined'

I have a NextJS website I'm building and it's great, except that it does not work in IE 10/11 because some code is not being transpiled correctly. I'm really bad with babel and webpack, and have never had to config them myself before. I've been trying to solve by reading online for two days now, and nothing seems to work for me.
The exact error I get is weakSet is not defined, and it is coming from the common.js file.
Here is my .babelrc file, located in the root of my project.
// .babelrc
{
"presets": ["next/babel"],
"plugins": [
["styled-components", {
"ssr": true,
"displayName": true,
"preprocess": false
}]
]
}
my package.json
{
"name": "bradshouse",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "next",
"build": "next build",
"start": "next start"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"next": "^7.0.2",
"react": "^16.6.0",
"react-dom": "^16.6.0",
"react-pose": "^4.0.1",
"styled-components": "^4.0.2"
},
"devDependencies": {
"babel-plugin-styled-components": "^1.8.0"
}
}
The full repo is here if you're interested in launching it yourself. node modules are excluded, so npm install, then npm run build, then npm run start.
https://github.com/TJBlackman/Brads-House
Thanks for the help! Feel free to just link articles and I'll read them thoroughly! Thanks.
Edit: As a quick fix, I added this polyfill script to the <head> of all my pages, and it still did not fix this issue... Wat?! <script src="https://cdn.polyfill.io/v2/polyfill.min.js"></script>
How to support IE 11 by transpiling node_modules code in NextJS
Original answer found in the ziet/nextjs issues thread (view here). Shout out to joaovieira <3
npm install --save-dev babel-polyfill
create a polyfill.js where ever you want it, and inside that file, import the babel-polyfill like so:
import 'babel-polyfill';
Next, if you do not have a next.config.js file, create it at your root directory. Now update your this file to include the following webpack config. Notice how it's using the polyfill file you just made. Full file example:
module.exports = {
webpack: (config) => {
// Unshift polyfills in main entrypoint.
const originalEntry = config.entry;
config.entry = async () => {
const entries = await originalEntry();
if (entries['main.js']) {
entries['main.js'].unshift('./path_to/polyfills.js'); // <- polyfill here
}
return entries;
};
return config;
}
}
Finally, if you don't have a .babelrc file in your project's root directory, create one. Inside it, use the code below that matches the version of babel you're using.
Babel 7
{
"presets": [
[
"next/babel",
{
"preset-env": {
"useBuiltIns": "usage"
}
}
]
]
}
Babel 6
{
"presets": [
[
"next/babel",
{
"preset-env": {
"targets": {
"browsers": "defaults"
},
"useBuiltIns": true
}
}
]
]
}
That's all I know. I'm not even thinking about IE 10...
Good luck!!
I am using next#9.3 with reflect-metadata, and here is my solution:
/** next.config.js > webpack **/
const pathToPolyfills = './src/polyfills.js'
// Fix [TypeError: Reflect.metadata is not a function] during production build
// Thanks to https://leerob.io/blog/things-ive-learned-building-nextjs-apps#polyfills
// There is an official example as well: https://git.io/JfqUF
const originalEntry = config.entry
config.entry = async () => {
const entries = await originalEntry()
Object.keys(entries).forEach(pageBundleEntryJs => {
let sourceFilesIncluded = entries[pageBundleEntryJs]
if (!Array.isArray(sourceFilesIncluded)) {
sourceFilesIncluded = entries[pageBundleEntryJs] = [sourceFilesIncluded]
}
if (!sourceFilesIncluded.some(file => file.includes('polyfills'))) {
sourceFilesIncluded.unshift(pathToPolyfills)
}
})
return entries
}
/** src/polyfills.js **/
// Other polyfills ...
import 'reflect-metadata'

Resources