Skip to content

Commit

Permalink
build: react compat (#24)
Browse files Browse the repository at this point in the history
* build: ship react classic runtime for v18 compat

* build: rm replace from rollup

* build: extend from build tsconfig

* build: import React globally

* build: include react 18 in peer deps

* build: use automatic runtime with cosmos

* build: fix rollup warnings
  • Loading branch information
zzmp authored Jun 5, 2022
1 parent 3aaf1f4 commit d2f640d
Show file tree
Hide file tree
Showing 11 changed files with 91 additions and 115 deletions.
32 changes: 32 additions & 0 deletions babel.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
const isDevelopment =
process.env.NODE_ENV === 'test' || // jest
process.env.NODE_ENV === 'development' // cosmos

module.exports = {
compact: false,
presets: [
'@babel/preset-env',
[
'@babel/preset-react',
{
development: isDevelopment,
// Ship with 'classic' runtime for compatibility with React >=17, otherwise ESM module resolution differs
// between versions (see https://github.com/facebook/react/issues/20235); develop with 'automatic' runtime for
// ease of development, so that React does not need to be top-level imported everywhere.
runtime: isDevelopment ? 'automatic' : 'classic',
},
],
['@babel/preset-typescript', { isTSX: true, allExtensions: true }],
],
plugins: [
'@babel/plugin-transform-runtime',
'macros',
[
'module-resolver',
{
root: ['src'],
extensions: ['.js', '.jsx', '.ts', '.tsx'],
},
],
],
}
19 changes: 0 additions & 19 deletions babel.config.json

This file was deleted.

8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -98,9 +98,9 @@
},
"peerDependencies": {
"@babel/runtime": "^7.17.0",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-redux": "^7.2.2",
"react": ">=17.0.1",
"react-dom": ">=17.0.1",
"react-redux": ">=7.2.2",
"redux": "^4.1.2"
},
"optionalDependencies": {
Expand All @@ -120,9 +120,9 @@
"@nomiclabs/hardhat-ethers": "^2.0.6",
"@rollup/plugin-babel": "^5.3.0",
"@rollup/plugin-commonjs": "^21.0.1",
"@rollup/plugin-inject": "^4.0.4",
"@rollup/plugin-json": "^4.1.0",
"@rollup/plugin-node-resolve": "^13.1.3",
"@rollup/plugin-replace": "^3.0.1",
"@rollup/plugin-url": "^6.1.0",
"@semantic-release/changelog": "^6.0.1",
"@semantic-release/git": "^10.0.1",
Expand Down
33 changes: 14 additions & 19 deletions rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@
/* eslint-disable @typescript-eslint/no-var-requires */
const { babel } = require('@rollup/plugin-babel')
const commonjs = require('@rollup/plugin-commonjs')
const inject = require('@rollup/plugin-inject')
const json = require('@rollup/plugin-json')
const { nodeResolve: resolve } = require('@rollup/plugin-node-resolve')
const replace = require('@rollup/plugin-replace')
const { default: dts } = require('rollup-plugin-dts')
const url = require('@rollup/plugin-url')
const svgr = require('@svgr/rollup')
Expand All @@ -35,7 +35,10 @@ const EXTENSIONS = ['.js', '.jsx', '.ts', '.tsx']
*/
const transpile = {
input: 'src/index.tsx',
external: isEthers,
external: (source) => {
// @ethersproject/* modules are provided by ethers
return source.startsWith('@ethersproject/')
},
plugins: [
// Dependency resolution
externals({
Expand All @@ -50,23 +53,25 @@ const transpile = {
resolve({ extensions: EXTENSIONS }), // resolves third-party modules within node_modules/

// Source code transformation
replace({
// esm requires fully-specified paths:
'react/jsx-runtime': 'react/jsx-runtime.js',
preventAssignment: true,
}),
json(), // imports json as ES6; doing so enables module resolution
url({ include: ['**/*.png', '**/*.svg'], limit: Infinity }), // imports assets as data URIs
svgr(), // imports svgs as React components
svgr({ jsxRuntime: 'automatic' }), // imports svgs as React components (without re-importing React)
sass({ output: 'dist/fonts.css', verbose: false }), // generates fonts.css
commonjs(), // transforms cjs dependencies into tree-shakeable ES modules

babel({
babelHelpers: 'runtime',
extensions: EXTENSIONS,
}),
inject({ React: 'react' }), // imports React (on the top-level, un-renamed), for the classic runtime
],
onwarn: squelchTypeWarnings, // this pipeline is only for transpilation
onwarn: (warning, warn) => {
// This pipeline is for transpilation - checking is done through tsc.
if (warning.code === 'UNUSED_EXTERNAL_IMPORT') return

warn(warning)
console.log(warning.loc, '\n')
},
}

const esm = {
Expand Down Expand Up @@ -130,13 +135,3 @@ const config = [esm, cjs, types, locales]
config.config = { ...esm, output: { ...esm.output, sourcemap: true } }
config.assets = assets
module.exports = config

function isEthers(source) {
// @ethersproject/* modules are provided by ethers
return source.startsWith('@ethersproject/')
}

function squelchTypeWarnings(warning, warn) {
if (warning.code === 'UNUSED_EXTERNAL_IMPORT') return
warn(warning)
}
21 changes: 9 additions & 12 deletions src/components/Swap/Settings/MaxSlippageSelect.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,6 @@ import { DecimalInput, inputCss } from '../../Input'
import Row from '../../Row'
import { Label, optionCss } from './components'

const tooltip = (
<Trans>Your transaction will revert if the price changes unfavorably by more than this percentage.</Trans>
)
const highSlippage = <Trans>High slippage increases the risk of price movement</Trans>
const invalidSlippage = <Trans>Please enter a valid slippage %</Trans>

const placeholder = '0.10'

const Button = styled(TextButton)<{ selected: boolean }>`
${({ selected }) => optionCss(selected)}
`
Expand Down Expand Up @@ -63,12 +55,12 @@ const Warning = memo(function Warning({ state, showTooltip }: { state?: 'warning
switch (state) {
case 'error':
icon = XOctagon
content = invalidSlippage
content = <Trans>Please enter a valid slippage %</Trans>
show = true
break
case 'warning':
icon = AlertTriangle
content = highSlippage
content = <Trans>High slippage increases the risk of price movement</Trans>
break
}
return (
Expand Down Expand Up @@ -120,7 +112,12 @@ export default function MaxSlippageSelect() {

return (
<Column gap={0.75}>
<Label name={<Trans>Max slippage</Trans>} tooltip={tooltip} />
<Label
name={<Trans>Max slippage</Trans>}
tooltip={
<Trans>Your transaction will revert if the price changes unfavorably by more than this percentage.</Trans>
}
/>
<Row gap={0.5} grow="last">
<Option wrapper={Button} selected={autoSlippage} onSelect={() => setAutoSlippage(true)}>
<ThemedText.ButtonMedium>
Expand All @@ -140,7 +137,7 @@ export default function MaxSlippageSelect() {
size={Math.max(maxSlippageInput.length, 4)}
value={maxSlippageInput}
onChange={(input) => processValue(+input)}
placeholder={placeholder}
placeholder={'0.10'}
ref={input}
/>
%
Expand Down
9 changes: 6 additions & 3 deletions src/components/Swap/Settings/TransactionTtlInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ import { inputCss, IntegerInput } from '../../Input'
import Row from '../../Row'
import { Label } from './components'

const tooltip = <Trans>Your transaction will revert if it has been pending for longer than this period of time.</Trans>

const Input = styled(Row)`
${inputCss}
`
Expand All @@ -22,7 +20,12 @@ export default function TransactionTtlInput() {
const input = useRef<HTMLInputElement>(null)
return (
<Column gap={0.75}>
<Label name={<Trans>Transaction deadline</Trans>} tooltip={tooltip} />
<Label
name={<Trans>Transaction deadline</Trans>}
tooltip={
<Trans>Your transaction will revert if it has been pending for longer than this period of time.</Trans>
}
/>
<ThemedText.Body1>
<Input justify="start" onClick={() => input.current?.focus()}>
<IntegerInput
Expand Down
16 changes: 7 additions & 9 deletions src/components/Swap/Status/StatusDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,6 @@ import ActionButton from '../../ActionButton'
import Column from '../../Column'
import Row from '../../Row'

const errorMessage = (
<Trans>
Try increasing your slippage tolerance.
<br />
NOTE: Fee on transfer and rebase tokens are incompatible with Uniswap V3.
</Trans>
)

const TransactionRow = styled(Row)`
flex-direction: row-reverse;
`
Expand Down Expand Up @@ -105,7 +97,13 @@ function TransactionStatus({ tx, onClose }: TransactionStatusProps) {
export default function TransactionStatusDialog({ tx, onClose }: TransactionStatusProps) {
return tx.receipt?.status === 0 ? (
<ErrorDialog
header={errorMessage}
header={
<Trans>
Try increasing your slippage tolerance.
<br />
NOTE: Fee on transfer and rebase tokens are incompatible with Uniswap V3.
</Trans>
}
error={new Error('TODO(zzmp)')}
action={<Trans>Dismiss</Trans>}
onClick={onClose}
Expand Down
13 changes: 8 additions & 5 deletions src/components/TokenImg.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
import { Currency } from '@uniswap/sdk-core'
import missingTokenSrc from 'assets/missing-token-image.png'
import { useToken } from 'hooks/useCurrency'
import useCurrencyLogoURIs from 'hooks/useCurrencyLogoURIs'
import { MissingToken } from 'icons'
import { useCallback, useMemo, useState } from 'react'
import styled from 'styled-components/macro'

const badSrcs = new Set<string>()

const MissingTokenImg = styled.img`
height: 1em;
width: 1em;
`

interface BaseProps {
token: Currency
}
Expand All @@ -16,8 +21,8 @@ type TokenImgProps = BaseProps & Omit<React.ImgHTMLAttributes<HTMLImageElement>,
function TokenImg({ token, ...rest }: TokenImgProps) {
// Use the wrapped token info so that it includes the logoURI.
const tokenInfo = useToken(token.isToken ? token.wrapped.address : undefined) ?? token

const srcs = useCurrencyLogoURIs(tokenInfo)
const alt = tokenInfo.name || tokenInfo.symbol

const [attempt, setAttempt] = useState(0)
const src = useMemo(() => {
Expand All @@ -34,9 +39,7 @@ function TokenImg({ token, ...rest }: TokenImgProps) {
[src]
)

if (!src) return <MissingToken color="secondary" {...rest} />

const alt = tokenInfo.name || tokenInfo.symbol
if (!src) return <MissingTokenImg src={missingTokenSrc} alt={alt} color="secondary" {...rest} />
return <img src={src} alt={alt} key={alt} onError={onError} {...rest} />
}

Expand Down
8 changes: 0 additions & 8 deletions src/icons/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import MissingTokenIcon from 'assets/missing-token-image.png'
import { ReactComponent as RouterIcon } from 'assets/svg/auto_router.svg'
import { ReactComponent as CheckIcon } from 'assets/svg/check.svg'
import { ReactComponent as ExpandoIcon } from 'assets/svg/expando.svg'
Expand Down Expand Up @@ -34,10 +33,6 @@ import { Color } from 'theme'

type SVGIcon = FunctionComponent<SVGProps<SVGSVGElement>>

const StyledImage = styled.img`
height: 1em;
width: 1em;
`
function icon(Icon: FeatherIcon | SVGIcon) {
return styled(Icon)<{ color?: Color }>`
clip-path: stroke-box;
Expand Down Expand Up @@ -98,9 +93,6 @@ export const Trash2 = icon(Trash2Icon)
export const Wallet = icon(WalletIcon)
export const X = icon(XIcon)
export const XOctagon = icon(XOctagonIcon)
export const MissingToken = (props: React.ImgHTMLAttributes<HTMLImageElement>) => (
<StyledImage src={MissingTokenIcon} alt="Missing token" {...props} />
)

export const Check = styled(icon(CheckIcon))`
circle {
Expand Down
30 changes: 2 additions & 28 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,36 +1,10 @@
{
"extends": "./tsconfig.build.json",
"compilerOptions": {
"allowJs": true,
"alwaysStrict": true,
"allowSyntheticDefaultImports": true,
"baseUrl": "src",
"declaration": true,
"declarationDir": "dts",
"downlevelIteration": true,
"emitDeclarationOnly": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"isolatedModules": true,
"jsx": "react-jsx",
"lib": ["dom", "dom.iterable", "esnext"],
"module": "esnext",
"moduleResolution": "node",
"noFallthroughCasesInSwitch": true,
"noImplicitAny": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noUnusedLocals": false,
"paths": {
"@uniswap/widgets": ["index"]
},
"resolveJsonModule": true,
"skipLibCheck": true,
"strict": true,
"strictNullChecks": true,
"target": "es5",
"types": ["jest"],
"useUnknownInCatchVariables": false
"types": ["jest"]
},
"exclude": ["node_modules"],
"include": ["src/"]
}
17 changes: 9 additions & 8 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2542,6 +2542,15 @@
magic-string "^0.25.7"
resolve "^1.17.0"

"@rollup/plugin-inject@^4.0.4":
version "4.0.4"
resolved "https://registry.yarnpkg.com/@rollup/plugin-inject/-/plugin-inject-4.0.4.tgz#fbeee66e9a700782c4f65c8b0edbafe58678fbc2"
integrity sha512-4pbcU4J/nS+zuHk+c+OL3WtmEQhqxlZ9uqfjQMQDOHOPld7PsCd8k5LWs8h5wjwJN7MgnAn768F2sDxEP4eNFQ==
dependencies:
"@rollup/pluginutils" "^3.1.0"
estree-walker "^2.0.1"
magic-string "^0.25.7"

"@rollup/plugin-json@^4.1.0":
version "4.1.0"
resolved "https://registry.yarnpkg.com/@rollup/plugin-json/-/plugin-json-4.1.0.tgz#54e09867ae6963c593844d8bd7a9c718294496f3"
Expand All @@ -2561,14 +2570,6 @@
is-module "^1.0.0"
resolve "^1.19.0"

"@rollup/plugin-replace@^3.0.1":
version "3.0.1"
resolved "https://registry.yarnpkg.com/@rollup/plugin-replace/-/plugin-replace-3.0.1.tgz#f774550f482091719e52e9f14f67ffc0046a883d"
integrity sha512-989J5oRzf3mm0pO/0djTijdfEh9U3n63BIXN5X7T4U9BP+fN4oxQ6DvDuBvFaHA6scaHQRclqmKQEkBhB7k7Hg==
dependencies:
"@rollup/pluginutils" "^3.1.0"
magic-string "^0.25.7"

"@rollup/plugin-url@^6.1.0":
version "6.1.0"
resolved "https://registry.yarnpkg.com/@rollup/plugin-url/-/plugin-url-6.1.0.tgz#1234bba9aa30b5972050bdfcf8fcbb1cb8070465"
Expand Down

1 comment on commit d2f640d

@vercel
Copy link

@vercel vercel bot commented on d2f640d Jun 5, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

widgets – ./

widgets-uniswap.vercel.app
widgets-seven-tau.vercel.app
widgets-git-main-uniswap.vercel.app

Please sign in to comment.