Dapparatus

repository·master·Indexed 41 days ago

https://github.com/austintgriffith/dapparatus

A collection of reusable React components for building Decentralized Applications (Dapps), providing common blockchain-related UI and logic including Metamask integration, automatic gas tracking, transaction management, and contract loading. Version 1.0.96.

Tokens
20.8K
Snippets
87
Records
101
Agent score
52%

What's inside Dapparatus

  1. Understand the demoapp folder structure

    master

    The project follows a standard Create React App structure. For the project to build successfully, the following files must exist with these exact filenames:

    • public/index.html: The page template.
    • src/index.js: The JavaScript entry point.

    Key Rules:

    • JS and CSS files: Must be placed inside src so Webpack can process them.
    • Assets for HTML: Only files inside public can be used directly from public/index.html.
    • Subdirectories: You can create subdirectories inside src for organization. Files inside src are processed by Webpack for faster rebuilds.
    • Top-level directories: You can create other top-level directories, but they will not be included in the production build.
    my-app/
      README.md
      node_modules/
      package.json
      public/
        index.html
        favicon.ico
      src/
        App.css
        App.js
        App.test.js
        index.css
        index.js
        logo.svg
  2. Manage NODE_ENV for conditional logic

    master

    The NODE_ENV variable is a built-in environment variable that tells you the current execution mode. You cannot override it manually.

    • npm start sets NODE_ENV to 'development'
    • npm test sets NODE_ENV to 'test'
    • npm run build sets NODE_ENV to 'production'

    Use this to perform actions conditionally, such as disabling analytics in development or stripping code during minification in production.

    if (process.env.NODE_ENV !== 'production') {
      analytics.disable();
    }
  3. Support client-side routing in production

    master

    When using routers that rely on the HTML5 pushState API (like React Router's browserHistory), static servers will fail on direct page refreshes because they look for a physical file at the requested path (e.g., /todos/42). You must configure your server to redirect all unknown requests to index.html.

    Express Configuration

    Amend your Express catch-all route from / to /*:

    -app.get('/', function (req, res) {
    +app.get('/*', function (req, res) {
       res.sendFile(path.join(__dirname, 'build', 'index.html'));
     });

    Apache Configuration

    Create a .htaccess file in your public folder:

    Options -MultiViews
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.html [QSA,L]

    Netlify Configuration

    Create a public/_redirects file with the following rule:

    /*  /index.html  200

    Surge Configuration

    Rename index.html in your build folder to 200.html before deploying to ensure all URLs fall back to that file.

  4. Debug React code in Visual Studio Code

    master

    To enable debugging in VS Code, ensure you have the latest version of VS Code and the Chrome Debugger Extension installed.

    Create a .vscode/launch.json file in your app's root directory and add the following configuration:

    1. Start your app with npm start.
    2. Press F5 or click the green debug icon in VS Code to start debugging.

    Note: If you have changed the HOST or PORT environment variables, update the url field in the configuration accordingly.

    {
      "version": "0.2.0",
      "configurations": [{
        "name": "Chrome",
        "type": "chrome",
        "request": "launch",
        "url": "http://localhost:3000",
        "webRoot": "${workspaceRoot}/src",
        "sourceMapPathOverrides": {
          "webpack:///src/*": "${webRoot}/*"
        }
      }]
    }
  5. Implement code splitting with dynamic import()

    master

    To prevent downloading the entire application at once, you can use dynamic import() to load code chunks on demand. The import() function returns a Promise that resolves to the module's namespace object. This is useful for loading heavy components or modules only when a specific user action occurs.

    You can use either .then() syntax or async/await syntax.

    // moduleA.js
    const moduleA = 'Hello';
    export { moduleA };
    
    // App.js
    import React, { Component } from 'react';
    
    class App extends Component {
      handleClick = () => {
        import('./moduleA')
          .then(({ moduleA }) => {
            // Use moduleA
          })
          .catch(err => {
            // Handle failure
          });
      };
    
      render() {
        return (
          <div>
            <button onClick={this.handleClick}>Load</button>
          </div>
        );
      }
    }
    
    export default App;
  6. Generate dynamic <meta> tags on the server

    master

    Since Create React App does not support server-side rendering, you can implement dynamic <meta> tags (for SEO/social sharing) by using placeholders in your index.html and replacing them on your server before sending the response.

    Example pattern:

    1. Add placeholders like __OG_TITLE__ to index.html.
    2. On your backend, read the file, replace placeholders with sanitized values, and serve the modified HTML.

    Security Note: Always sanitize and escape interpolated values to prevent XSS attacks.

    <head>
      <meta property="og:title" content="__OG_TITLE__">
      <meta property="og:description" content="__OG_DESCRIPTION__">
    </head>
  7. Access assets in the `public` folder

    master

    Files in the public folder are not processed by Webpack and are copied to the build folder untouched. To reference these assets, use the %PUBLIC_URL% variable in HTML or process.env.PUBLIC_URL in JavaScript. This is an 'escape hatch' for cases like manifest files, large numbers of dynamic images, or scripts incompatible with Webpack.

    Downsides:

    • No minification or post-processing.
    • No content hashes (requires manual cache busting).
    • Missing files cause 404s at runtime rather than compilation errors.
    <!-- In index.html -->
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    
    <!-- In JavaScript -->
    <img src={process.env.PUBLIC_URL + '/img/logo.png'} />
  8. Fetch data with AJAX requests

    master

    The project includes a polyfill for the browser fetch() API and a Promise polyfill, allowing you to use fetch() and async/await syntax reliably. You can also use libraries like axios for AJAX requests.

    // Example using fetch with async/await
    async function fetchData() {
      const response = await fetch('https://api.example.com/data');
      const data = await response.json();
      return data;
    }
  9. Opting out of Progressive Web App (PWA) caching

    master

    The production build is configured as an offline-first Progressive Web App using sw-precache-webpack-plugin.

    To disable service workers before your initial production deployment, remove the call to registerServiceWorker() from src/index.js.

    To disable service workers for existing users who already have them enabled, modify the service worker import in src/index.js to use unregister instead of register:

    import { unregister } from './registerServiceWorker';

    Then call unregister(). Note that it may take up to 24 hours for the cache to be invalidated depending on how /service-worker.js is served.

    import { unregister } from './registerServiceWorker';
    
    // Call unregister() instead of registerServiceWorker()
    unregister();
  10. Set up React Styleguidist for component isolation

    master

    React Styleguidist provides a style guide and an environment for developing components in isolation. It uses Markdown to document props and usage, rendering code snippets as live editable playgrounds.

    To set up Styleguidist:

    1. Install the package:
    npm install --save react-styleguidist
    1. Add the following scripts to your package.json:
    "scripts": {
        "styleguide": "styleguidist server",
        "styleguide:build": "styleguidist build"
    }
    1. Run the server:
    npm run styleguide
    npm install --save react-styleguidist
    # Add to package.json:
    # "styleguide": "styleguidist server"
    # "styleguide:build": "styleguidist build"
    npm run styleguide