Truffle solidity loader Not working with Truffle 3.2.1 - node.js

I was using truffle-webpack-demo but started getting errors since I upgraded to truffle 3.2.1. I found the new branch of the same repo and copied config from there. Which should be working, but now npm start gives me the following error.
Starting the development server...
Failed to compile.
Error in ./contracts/MetaCoin.sol
Module build failed: Error: You must specify the network name to deploy to. (network)
# ./src/components/AccountList/AccountListContainer.js 37:16-49
I have upgraded to the following versions of truffle, webpack-dev-server, webpack and truffle-solidity-loader
truffle-solidity-loader: "git+https://github.com/sogoiii/truffle-solidity-loader.git#1f1e213d52f033b6863218307b8968ae68220fe1"
truffle: 3.2.1
webpack-dev-server: 2.4.1
webpack: 2.2.1
Below is my config/webpack.config.dev.js
var path = require('path')
var autoprefixer = require('autoprefixer')
var webpack = require('webpack')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var precss = require('precss')
// TODO: hide this behind a flag and eliminate dead code on eject.
// This shouldn't be exposed to the user.
var isInNodeModules = path.basename(path.resolve(path.join(__dirname, '..', '..'))) === 'node_modules'
var relativePath = isInNodeModules ? '../../..' : '..'
var isInDebugMode = process.argv.some(arg =>
arg.indexOf('--debug-template') > -1
)
if (isInDebugMode) {
relativePath = '../template'
}
var srcPath = path.resolve(__dirname, relativePath, 'src')
var nodeModulesPath = path.join(__dirname, '..', 'node_modules')
var indexHtmlPath = path.resolve(__dirname, relativePath, 'index.html')
var faviconPath = path.resolve(__dirname, relativePath, 'favicon.ico')
var buildPath = path.join(__dirname, isInNodeModules ? '../../..' : '..', 'build')
var provided = {
'Web3': 'web3'
}
module.exports = {
devtool: 'eval',
entry: [
require.resolve('webpack-dev-server/client') + '?http://localhost:3000',
require.resolve('webpack/hot/dev-server'),
path.join(srcPath, 'index')
],
output: {
// Next line is not used in dev but WebpackDevServer crashes without it:
path: buildPath,
pathinfo: true,
filename: 'bundle.js',
publicPath: '/'
},
resolve: {
root: srcPath,
extensions: ['', '.js'],
alias: {
contracts: path.resolve('contracts'),
// config: require('../truffle').networks.development,
config: path.resolve('truffle.js')
}
},
module: {
preLoaders: [
{
test: /\.js$/,
loader: 'eslint',
include: srcPath
}
],
loaders: [
{
test: /\.js$/,
include: srcPath,
loader: 'babel',
query: require('./babel.dev')
},
{
test: /\.css$/,
include: srcPath,
loader: 'style!css!postcss'
},
{
test: /\.json$/,
loader: 'json'
},
{
test: /\.(jpg|png|gif|eot|svg|ttf|woff|woff2)$/,
loader: 'file'
},
{
test: /\.(mp4|webm)$/,
loader: 'url?limit=10000'
},
{
test: /\.sol/,
loader: 'truffle-solidity',
loaders: ['json-loader', 'truffle-solidity-loader?migrations_directory=' + path.resolve(__dirname, '../migrations') + '&network=development&contracts_build_directory=' + path.resolve(__dirname, '../dist/contracts')]
}
]
},
eslint: {
configFile: path.join(__dirname, 'eslint.js'),
useEslintrc: false
},
postcss: function () {
return [precss, autoprefixer]
},
plugins: [
new HtmlWebpackPlugin({
inject: true,
template: indexHtmlPath,
favicon: faviconPath
}),
new webpack.ProvidePlugin(provided),
new webpack.DefinePlugin({
'myEnv': JSON.stringify(require('../truffle').networks.development),
'process.env.NODE_ENV': '"development"'
}),
new webpack.EnvironmentPlugin(['NODE_ENV']),
new webpack.HotModuleReplacementPlugin()
]
}
Here's my MetaCoin.sol
pragma solidity ^0.4.4;
import "./ConvertLib.sol";
// This is just a simple example of a coin-like contract.
// It is not standards compatible and cannot be expected to talk to other
// coin/token contracts. If you want to create a standards-compliant
// token, see: https://github.com/ConsenSys/Tokens. Cheers!
contract MetaCoin {
mapping (address => uint) balances;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
function MetaCoin() {
balances[tx.origin] = 6000000000;
}
function sendCoin(address receiver, uint amount) returns(bool sufficient) {
if (balances[msg.sender] < amount) return false;
balances[msg.sender] -= amount;
balances[receiver] += amount;
Transfer(msg.sender, receiver, amount);
return true;
}
function getBalanceInEth(address addr) returns(uint){
return convert(getBalance(addr),2);
}
function getBalance(address addr) returns(uint) {
return balances[addr];
}
function convert(uint amount,uint conversionRate) returns (uint convertedAmount)
{
return amount * conversionRate;
}
}
Here's my AccountListContainer.js
import React, { Component } from 'react'
import AccountList from 'components/AccountList/AccountList'
import SendCoin from 'components/SendCoin/SendCoin'
import Contract from 'truffle-contract'
import MetaCoinArtifact from 'contracts/MetaCoin.sol';
const MetaCoin = Contract(MetaCoinArtifact)
import Web3 from 'web3';
const provider = new Web3.providers.HttpProvider('http://localhost:8545')
MetaCoin.setProvider(provider);
class AccountListContainer extends Component {
constructor(props) {
super(props)
this.state = {
accounts: [],
coinbase: ''
}
this._getAccountBalance = this._getAccountBalance.bind(this)
this._getAccountBalances = this._getAccountBalances.bind(this)
}
_getAccountBalance (account) {
return MetaCoin.deployed()
.then(meta => {
return meta.getBalance.call(account, {from: account})
})
.then(function (value) {
return { account: value.valueOf() }
})
.catch(function (e) {
console.log(e)
throw e
})
}
_getAccountBalances () {
this.props.web3.eth.getAccounts(function (err, accs) {
if (err != null) {
window.alert('There was an error fetching your accounts.')
console.error(err)
return
}
if (accs.length === 0) {
window.alert("Couldn't get any accounts! Make sure your Ethereum client is configured correctly.")
return
}
this.setState({coinbase: accs[0]})
var accountsAndBalances = accs.map((account) => {
return this._getAccountBalance(account).then((balance) => { return { account, balance } })
})
Promise.all(accountsAndBalances).then((accountsAndBalances) => {
this.setState({accounts: accountsAndBalances, coinbaseAccount: accountsAndBalances[0]})
})
}.bind(this))
}
componentDidMount() {
const refreshBalances = () => {
this._getAccountBalances()
}
refreshBalances()
setInterval(()=>{
refreshBalances();
return refreshBalances
}, 5000)
}
render() {
return (
<div>
<AccountList accounts={this.state.accounts} />
<SendCoin sender={this.state.coinbase} />
</div>
)
}
}
export default AccountListContainer
Here's the truffle.js
module.exports = {
networks: {
development: {
host: "localhost",
port: 8545,
network_id: "*"
},
staging: {
host: "localhost",
port: 8546,
network_id: 1337
}
}
};

Given the error Module build failed: Error: You must specify the network name to deploy to. (network), I suspect your truffle.js file has not been updated to the new truffle 3 spec.
Review how the config changed at the migration guided. It should look something like.
module.exports = {
networks: {
development: {
host: "localhost",
port: 8545,
network_id: "*"
},
staging: {
host: "localhost",
port: 8546,
network_id: 1337
},
ropsten: {
host: "158.253.8.12",
port: 8545,
network_id: 3
}
}
};

Related

Cypress publicPath not supported with percy and nock

I'm getting an issue where I am trying to add percy to my Cypress tests using nock and webpack 5. Based on a solution found here, I tried to set the publicPath to an empty string, but with no success. The error message I get is
The following error originated from your test code, not from Cypress.
Automatic publicPath is not supported in this browser
When Cypress detects uncaught errors originating from your test code
it will automatically fail the current test.
Cypress could not associate this error to any specific test.
We dynamically generated a new test to display this failure
.../webpack/runtime/publicPath:14:1
// When supporting browsers where an automatic publicPath is not supported you must specify an output.publicPath manually via configuration
// or pass an empty string ("") and set the __webpack_public_path__ variable from your code to use your own logic.
if (!scriptUrl) throw new Error("Automatic publicPath is not supported in this browser");
^
scriptUrl = scriptUrl.replace(/#.*$/, "").replace(/\?.*$/, "").replace(/\/[^\/]+$/, "/");
__webpack_require__.p = scriptUrl;
In my cypress/plugins/webpack.config.js file, I have the following.
module.exports = {
resolve: { extensions: ['.ts', '.js'], fallback: { http: false } },
output: {
publicPath: '/',
},
module: {
rules: [
{
test: /\.svg$/,
use: ['#svgr/webpack'],
},
],
},
module: {
rules: [
{
test: /\.ts$/,
loader: 'ts-loader',
exclude: /node_modules/,
options: {
transpileOnly: true,
},
},
],
},
};
In my cypress/plugins/index.js, I have the following.
const nock = require('nock');
const http = require('http');
const next = require('next');
const webpackPreprocessor = require('#cypress/webpack-preprocessor');
module.exports = async (on, config) => {
const app = next({ dev: true });
const handleNextRequests = app.getRequestHandler();
await app.prepare();
const customServer = new http.Server(async (req, res) => {
return handleNextRequests(req, res);
});
await new Promise((resolve, reject) => {
customServer.listen(3000, (err) => {
if (err) {
return reject(err);
}
resolve();
});
});
on('task', {
clearNock() {
nock.restore();
nock.cleanAll();
return null;
},
async nock({ hostname, method, path, statusCode, body }) {
nock.activate();
// add one-time network stub like
method = method.toLowerCase();
nock(hostname)[method](path).reply(statusCode, body);
return null;
},
});
const options = {
webpackOptions: require('./webpack.config'),
watchOptions: {},
};
on('file:preprocessor', webpackPreprocessor(options));
return config;
};
How can I configure the publicPath properly?

Why is my _middleware not able to route well in production (NEXTJS)?

I have the following on my _middleware.ts file with the objective of mainly routing requests to mysubdomain. Its working well on my local server but when I deploy to vercel its throwing a 404. Any help will be much appreciated.
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { request } from "http";
export default function middleware(req: NextRequest) {
// Clone the request url
const newReq = req.nextUrl.clone();
const regex = new RegExp(`\.subdomaingivenbyvercel-[\w\w\w\w\w\w\w\w\w]-username\.vercel\.app`);
const pathname = req.nextUrl.pathname.toString();
// Get hostname of request (e.g. demo.vercel.pub)
const hostname = req.headers.get("host");
if (!hostname)
return new Response(null, {
status: 400,
statusText: "No hostname found in request headers"
});
const currentHost =
process.env.VERCEL_ENV === `production` && process.env.VERCEL === `1`
? // You have to replace ".vercel.pub" with your own domain if you deploy this
example under your domain.
// You can use wildcard subdomains on .vercel.app links that are associated
with your Vercel team slug
// in this case, our team slug is "platformize", thus
*.platformize.vercel.app works
hostname
.replace(`.myrootdomain.com`, "")
.replace(`.branchname.vercel.app`, "")
.replace(`.*.vercel.app`, "")
.replace(regex, "")
: hostname.replace(`.localhost:3000`, "");
if (pathname.startsWith(`/_sites`))
return new Response(null, {
status: 404
});
if (
!pathname.includes(".") &&
!pathname.startsWith("/api")
) {
if (currentHost === "mysubdomain") {
if (
pathname === "/login" &&
(req.cookies["next-auth.session-token"] ||
req.cookies["__Secure-next-auth.session-token"])
) {
newReq.pathname = "/";
return NextResponse.redirect(newReq.toString());
}
newReq.pathname = `/mysubdomain${pathname}`;
return NextResponse.rewrite(newReq.toString());
}
newReq.pathname = `${pathname}`;
return NextResponse.rewrite(newReq.toString());
}
}
I try all of the routes and none of them can be found. I have tried everything around the way the middleware parses the URL without success. Here you can see my next.config.js just in case Im doing a redirect without knowing it:
/**
* #type {import('next').NextConfig}
*/
const plugins = require("next-compose-plugins");
const withBundleAnalyzer = require("#next/bundle-analyzer")({
enabled: process.env.ANALYZE === "true"
});
const withOffline = require("next-offline");
function esbuildLoader(config, options) {
const jsLoader = config.module.rules.find(
(rule) => rule.test && rule.test.test(".js")
);
if (jsLoader && jsLoader.use) {
if (jsLoader.use.length > 0) {
jsLoader.use.forEach((e) => {
e.loader = "esbuild-loader";
e.options = options;
});
} else {
jsLoader.use.loader = "esbuild-loader";
jsLoader.use.options = options;
}
}
}
// the config break if we use next export
const nextConfig =
process.env.EXPORT !== "true"
? {
webpack(config, { webpack, dev, isServer }) {
config.plugins.push(
new webpack.ProvidePlugin({
React: "react"
})
);
// audio support
config.module.rules.push({
test: /\.(ogg|mp3|wav|mpe?g)$/i,
exclude: config.exclude,
use: [
{
loader: require.resolve("url-loader"),
options: {
limit: config.inlineImageLimit,
fallback: require.resolve("file-loader"),
publicPath: `${config.assetPrefix}/_next/static/images/`,
outputPath: `${isServer ? "../" : ""}static/images/`,
name: "[name]-[hash].[ext]",
esModule: config.esModule || false
}
}
]
});
config.module.rules.push({
test: /\.(glsl|vs|fs|vert|frag)$/,
exclude: /node_modules/,
use: ["raw-loader", "glslify-loader", "#svgr/webpack"]
});
config.module.rules.push({
test: /\.svg$/,
use: [`#svgr/webpack`]
});
return config;
},
images: {
domains: [
"lomplay.com/ipfs",
"nft.storage",
"avatars.githubusercontent.com"
]
},
reactStrictMode: true,
swcMinify: false // Required to fix: https://nextjs.org/docs/messages/failed-
loading-swc
}
: {};
module.exports = plugins(
[
[
withOffline,
{
workboxOpts: {
swDest: process.env.NEXT_EXPORT
? "service-worker.js"
: "static/service-worker.js",
runtimeCaching: [
{
urlPattern: /^https?.*/,
handler: "NetworkFirst",
options: {
cacheName: "offlineCache",
expiration: {
maxEntries: 200
}
}
}
]
},
async rewrites() {
return {
beforeFiles: [
{
source: "/_subdomain/api/newsletter",
destination: "https://rootdomain.com/api/newsletter"
}
],
afterFiles: [
{
source: "/service-worker.js",
destination: "/_next/static/service-worker.js"
}
]
};
}
}
],
withBundleAnalyzer
],
nextConfig
);

How to setup webpack-hot-server-middleware with vue-server-renderer and vue-router?

I'm trying to setup an own express server with webpack to use hot module replacement & server side rendering. Everything seems to work except the integration of webpack-hot-server-middleware which needs an express middleware function with (res, req, next) params - but I can't get my head around about how to implement it correctly.
This is my configuration so far:
webpack.config.js
const webpack = require('webpack');
const path = require('path');
const config = [{
name: 'client',
entry: [
'webpack-hot-middleware/client',
'./src/js/entry_client.js'
],
output: {
path: path.resolve(__dirname, 'dist/js/'),
filename: 'app.js'
},
module: {
rules: [{
test: /\.vue$/,
loader: 'vue-loader'
}, {
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
}]
},
resolve: {
alias: {
vue$: 'vue/dist/vue.runtime.js'
}
}
}, {
name: 'server',
target: 'node',
entry: './src/js/entry_server.js',
output: {
path: path.resolve(__dirname, 'dist/js/'),
filename: 'app.server.js',
libraryTarget: 'commonjs2'
},
externals: require('webpack-node-externals')(),
module: {
rules: [{
test: /\.vue$/,
loader: 'vue-loader'
}]
},
resolve: {
alias: {
vue$: 'vue/dist/vue.runtime.js',
}
}
}];
if (process.env.NODE_ENV !== 'production') {
config[0].plugins = [new webpack.HotModuleReplacementPlugin()];
}
module.exports = config;
entry_client.js
import {createApp} from './app';
const {app, router} = createApp();
router.onReady(() => {
app.$mount('#app');
});
entry_server.js
import {createApp} from './app';
export default context => {
return new Promise((resolve, reject) => {
const {app, router} = createApp();
router.push(context.url);
router.onReady(() => {
if (!router.getMatchedComponents().length) return reject({code: 404});
resolve(app);
}, reject);
});
};
app.js
import Vue from 'vue';
import App from '../vue/app.vue';
import {createRouter} from './router';
export function createApp() {
const router = createRouter();
const app = new Vue({
router,
render: h => h(App)
});
return {app, router};
}
router.js
import Vue from 'vue';
import Router from 'vue-router';
import Home from '../vue/home.vue';
import About from '../vue/about.vue';
Vue.use(Router);
export function createRouter() {
return new Router({
mode: 'history',
routes: [{
path: '/',
component: Home
}, {
path: '/about',
component: About
}]
});
}
server.js
const express = require('express');
const fs = require('fs');
const path = require('path');
const bundle = require('./dist/js/app.server');
const renderer = require('vue-server-renderer').createRenderer({
template: fs.readFileSync('./src/html/index.html', 'utf-8')
});
const server = express();
// add vue HMR middleware
if (process.env.NODE_ENV !== 'production') {
const webpack = require('webpack');
const compiler = webpack(require('./webpack.config'));
server.use(require('webpack-dev-middleware')(compiler, {
noInfo: true,
serverSideRender: true
}));
server.use(require('webpack-hot-middleware')(compiler.compilers.find(compiler => compiler.name === 'client')));
// server.use(require('webpack-hot-server-middleware')(compiler));
} else {
// static file serving
server.use(require('serve-favicon')(path.join(__dirname, 'src/png/favicon-32x32.png')));
server.use(express.static(path.join(__dirname, 'dist/'), {index: false}));
}
server.get('*', (req, res) => {
bundle.default({url: req.url}).then(app => {
renderer.renderToString(app, {
title: 'Some title',
description: 'Some description'
}, (err, html) => {
if (err) {
console.error('Error in renderToString:', err);
return res.status(500).send('Internal Server Error');
}
res.send(html);
});
}, err => {
if (err.code === 404) return res.status(404).send('Page not found');
console.error(err);
return res.status(500).send('Internal Server Error');
});
});
server.listen(4040);

Getting found-relay to work with universal-webpack

I'm encountering this error on npm run start:
TypeError: Cannot read property 'pathname' of undefined
Which is getting thrown by:
ReactDOMServer.renderToString(element)
Edit: Got some better logging and found that createResolver(fetcher) is returning an object with:
lastQueries: [ undefined, undefined ],
/src/server.js
import path from 'path';
import express from 'express';
import bodyParser from 'body-parser';
import httpProxy from 'http-proxy';
import { getFarceResult } from 'found/lib/server';
import ReactDOMServer from 'react-dom/server';
import serialize from 'serialize-javascript';
import { ServerFetcher } from './fetcher';
import { createResolver, historyMiddlewares, render, routeConfig } from './router';
const {PRIVATE_IP, API_IP, PORT, API_PORT} = process.env;
const publicPath = path.join(__dirname, '/..', 'public');
export default parameters => {
const app = express();
const proxy = httpProxy.createProxyServer({ ignorePath: true });
const proxyOptions = {
target: `http://${API_IP}:${API_PORT}/graphql-api`,
ignorePath: true,
};
function getFromProxy (req, res) {
req.removeAllListeners('data');
req.removeAllListeners('end');
process.nextTick(_ => {
if (req.body) {
req.emit('data', JSON.stringify(req.body));
}
req.emit('end');
});
proxy.web(req, res, proxyOptions);
}
app.use(express.static(publicPath));
app.use(bodyParser.json({ limit: '1mb' }));
app.use('/graphql-api', getFromProxy);
app.use(async (req, res) => {
const fetcher = new ServerFetcher(`http://${PRIVATE_IP}:${PORT}/graphql-api`);
const { redirect, status, element } = await getFarceResult({
url: req.url,
historyMiddlewares,
routeConfig,
resolver: createResolver(fetcher),
render,
});
if (redirect) {
res.redirect(302, redirect.url);
return;
}
res.status(status).send(`
<!DOCTYPE html>
<html lang="en">
...
<body>
<div id="root">${ReactDOMServer.renderToString(element)}</div>
<script>
window.__RELAY_PAYLOADS__ = ${serialize(fetcher, { isJSON: true })};
</script>
<script src="/bundle.js"></script>
</body>
</html>
`);
});
app.listen(PORT, PRIVATE_IP, err => {
if (err) {
console.log(`[Error]: ${err}`);
}
console.info(`[express server]: listening on ${PRIVATE_IP}:${PORT}`);
});
};
Other files:
/package.json
"scripts": {
"schema": "gulp load-schema",
"relay": "relay-compiler --src ./src --schema ./data/schema.graphql",
"start": "npm-run-all schema relay prepare-server-build start-development-workflow",
"start-development-workflow": "npm-run-all --parallel development-webpack-build-for-client development-webpack-build-for-server development-start-server",
"prepare-server-build": "universal-webpack --settings ./webpack.isomorphic.settings.json prepare",
"development-webpack-build-for-client": "webpack-dev-server --hot --inline --config \"./webpack.isomorphic.client.babel.js\" --port 8080 --colors",
"development-webpack-build-for-server": "webpack --watch --config \"./webpack.isomorphic.server.babel.js\" --colors",
"development-start-server": "nodemon \"./start-server.babel\" --watch \"./build/dist/server\"",
...
},
/start-server.babel
require('babel-register')({ ignore: /\/(build|node_modules)\// });
require('babel-polyfill');
require('./src/start-server.js');
/src/start-server
import 'source-map-support/register';
import startServer from 'universal-webpack/server';
import settings from '../webpack.isomorphic.settings.json';
import configuration from '../webpack.config';
startServer(configuration, settings);
/webpack.config
import webpack from 'webpack';
import path from 'path';
import env from 'gulp-env';
import CopyWebpackPlugin from 'copy-webpack-plugin';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
// process.traceDeprecation = true;
if (!process.env.NODE_ENV) {
env({file: './.env', type: 'ini'});
}
const {
NODE_ENV,
PRIVATE_IP,
API_IP,
PORT,
API_PORT,
GOOGLE_ANALYTICS_KEY,
} = process.env;
const PATHS = {
root: path.join(__dirname),
src: path.join(__dirname, 'src'),
public: path.join(__dirname, 'build', 'public'),
shared: path.join(__dirname, 'src', 'shared'),
fonts: path.join(__dirname, 'src', 'shared', 'fonts'),
robots: path.join(__dirname, 'src', 'robots.txt'),
};
let devtool;
const plugins = [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(NODE_ENV),
PRIVATE_IP: JSON.stringify(PRIVATE_IP),
API_IP: JSON.stringify(API_IP),
PORT: JSON.stringify(PORT),
API_PORT: JSON.stringify(API_PORT),
GOOGLE_ANALYTICS_KEY: JSON.stringify(GOOGLE_ANALYTICS_KEY),
},
}),
new ExtractTextPlugin('styles.css'),
];
if (NODE_ENV === 'production') {
devtool = 'source-map';
plugins.push(
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
screw_ie8: true,
},
}),
new webpack.NoErrorsPlugin(),
new CopyWebpackPlugin([
{ from: PATHS.robots, to: PATHS.public },
]),
);
} else {
devtool = 'eval-source-map';
plugins.push(
new webpack.NamedModulesPlugin(),
);
}
const config = {
devtool,
context: PATHS.root,
entry: [
PATHS.src,
],
output: {
path: PATHS.public,
filename: 'bundle.js',
publicPath: '/',
},
plugins,
module: {
rules: [
{
test: /\.js$/,
include: PATHS.src,
loader: 'babel-loader',
},
{
test: /\.css$/,
include: PATHS.src,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: {
loader: 'css-loader',
options: {
modules: true,
localIdentName: '[name]_[local]__[hash:base64:5]',
},
},
}),
},
{
test: /\.svg$/,
include: PATHS.src,
use: [
{ loader: 'url-loader', options: { limit: 10000 } },
],
},
{
test: /\.png$/,
include: PATHS.src,
use: [
{ loader: 'url-loader', options: { limit: 65000 } },
],
},
{
test: /\.(woff|woff2)$/,
include: PATHS.fonts,
loader: 'url-loader',
options: {
name: 'font/[hash].[ext]',
limit: 50000,
mimetype: 'application/font-woff',
},
},
],
},
resolve: {
modules: [
PATHS.src,
'node_modules',
],
alias: {
root: PATHS.root,
},
},
};
export default config;
/webpack.isomorphic.settings.json
{
"server": {
"input": "./src/server.js",
"output": "./build/dist/server.js"
}
}
/webpack.isomorphic.client.babel.js
import { client } from 'universal-webpack/config';
import settings from './webpack.isomorphic.settings.json';
import configuration from './webpack.config';
export default client(configuration, settings);
/webpack.isomorphic.server.babel.js
import { server } from 'universal-webpack/config';
import settings from './webpack.isomorphic.settings.json';
import configuration from './webpack.config';
export default server(configuration, settings);
/src/fetcher.js
import 'isomorphic-fetch';
// TODO: Update this when someone releases a real, production-quality solution
// for handling universal rendering with Relay Modern. For now, this is just
// enough to get things working.
class FetcherBase {
constructor (url) {
this.url = url;
}
async fetch (operation, variables) {
const response = await fetch(this.url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ query: operation.text, variables }),
});
return response.json();
}
}
export class ServerFetcher extends FetcherBase {
constructor (url) {
super(url);
this.payloads = [];
}
async fetch (...args) {
const i = this.payloads.length;
this.payloads.push(null);
const payload = await super.fetch(...args);
this.payloads[i] = payload;
return payload;
}
toJSON () {
return this.payloads;
}
}
export class ClientFetcher extends FetcherBase {
constructor (url, payloads) {
super(url);
this.payloads = payloads;
}
async fetch (...args) {
if (this.payloads.length) {
return this.payloads.shift();
}
return super.fetch(...args);
}
}
/src/router.js
import queryMiddleware from 'farce/lib/queryMiddleware';
import createRender from 'found/lib/createRender';
import makeRouteConfig from 'found/lib/makeRouteConfig';
import Route from 'found/lib/Route';
import { Resolver } from 'found-relay';
import React from 'react';
import { Environment, Network, RecordSource, Store } from 'relay-runtime';
// static
import CorePage from 'core/components/CorePage';
import LoadingComponent from 'core/components/LoadingComponent';
import ErrorComponent from 'core/components/ErrorComponent';
import HomePage from 'home/components/HomePage';
import NotFound from 'not-found/components/NotFoundPage';
// user
import UserContainer from 'user/containers/UserContainer';
import UserContainerQuery from 'user/queries/UserContainerQuery';
export const historyMiddlewares = [queryMiddleware];
export function createResolver (fetcher) {
const environment = new Environment({
network: Network.create((...args) => fetcher.fetch(...args)),
store: new Store(new RecordSource()),
});
return new Resolver(environment);
}
export const routeConfig = makeRouteConfig(
<Route path={'/'} Component={CorePage}>
<Route Component={HomePage} />
<Route
path={'user/:userId'}
Component={UserContainer}
query={UserContainerQuery}
/>
<Route path={'*'} component={NotFound} />
</Route>,
);
export const render = createRender({
renderPending: _ => <LoadingComponent />,
renderError: error => {
console.error(`Relay renderer ${error}`);
return <ErrorComponent />; // renderArgs.retry?
},
});
/src/index.js
import BrowserProtocol from 'farce/lib/BrowserProtocol';
import createInitialFarceRouter from 'found/lib/createInitialFarceRouter';
import React from 'react';
import ReactDOM from 'react-dom';
import injectTapEventPlugin from 'react-tap-event-plugin';
import { AppContainer } from 'react-hot-loader';
import { ClientFetcher } from './fetcher';
import { createResolver, historyMiddlewares, render, routeConfig } from './router';
injectTapEventPlugin();
(async () => {
// eslint-disable-next-line no-underscore-dangle
const fetcher = new ClientFetcher('/graphql-api', window.__RELAY_PAYLOADS__);
const resolver = createResolver(fetcher);
const Router = await createInitialFarceRouter({
historyProtocol: new BrowserProtocol(),
historyMiddlewares,
routeConfig,
resolver,
render,
});
const rootRender = Component => {
ReactDOM.render(
<AppContainer>
<Component resolver={resolver} />
</AppContainer>,
document.getElementById('root'),
);
};
rootRender(Router);
})();
I had some legacy code for a component that was referencing context.router.isActive from when I was using react-router-relay. Getting rid of that cleared up the problem

cannot find in electron render process

I am using electron v1.2.3 with react js and es6 (with babel-preset-es2015).
I have a module where I need to import the app module in the render process. But I got this error:
Cannot read property 'app' of undefined
Here is the module that I need to import:
const app = require('electron').remote.app;
const userData = app.getPath('userData');
var nconf = require('nconf').file({file: userData + '/settings.json'});
function saveSettings(settingKey, settingValue) {
nconf.set(settingKey, settingValue);
nconf.save();
}
function readSettings(settingKey) {
nconf.load();
return nconf.get(settingKey);
}
module.exports = {
saveSettings: saveSettings,
readSettings: readSettings
};
I also have tried with
const app = require('electron').remote.require('app');
Still i get the error:
Cannot read property 'require' of undefined
Not sure is the webpack configuration matters. I am refer to this answer to setting up the webpack configuration.
module.exports = {
context: __dirname + '/app',
entry: './entry.js',
node: {
fs: "empty"
},
output: {
filename: 'bundle.js',
path: __dirname + '/build',
publicPath: 'http://localhost:8080/build/'
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'react-hot',
},
{
test: /\.js$/,
loader: "babel-loader",
exclude: /node_modules/ ,
query: { presets:['es2015','react'] }
}
]
},
externals: [
(function () {
var IGNORES = [
'electron'
];
return function (context, request, callback) {
if (IGNORES.indexOf(request) >= 0) {
return callback(null, "require('" + request + "')");
}
return callback();
};
})()
]
};

Resources