Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: Basepath support (pass both variables) #1

Open
wants to merge 3 commits into
base: canary
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions build/webpack.js
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,8 @@ export default async function getBaseWebpackConfig (dir: string, {dev = false, i
.filter((p) => !!p)

const outputPath = path.join(dir, config.distDir, isServer ? SERVER_DIRECTORY : '')


const pagesEntries = await getPages(dir, {nextPagesDir: DEFAULT_PAGES_DIR, dev, buildId, isServer, pageExtensions: config.pageExtensions.join('|')})
const totalPages = Object.keys(pagesEntries).length
const clientEntries = !isServer ? {
Expand Down
13 changes: 9 additions & 4 deletions client/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,16 @@ const {
query,
buildId,
assetPrefix,
runtimeConfig
basePath,
runtimeConfig,
},
location
} = window

const prefix = assetPrefix || ''

console.log('Yupiii', basePath);

const prefix = assetPrefix || '/account' || ''

// With dynamic assetPrefix it's no longer possible to set assetPrefix at the build time
// So, this is how we do it in the client side at runtime
Expand All @@ -48,7 +52,7 @@ envConfig.setConfig({

const asPath = getURL()

const pageLoader = new PageLoader(buildId, prefix)
const pageLoader = new PageLoader(buildId, prefix, basePath)
window.__NEXT_LOADED_PAGES__.forEach(({ route, fn }) => {
pageLoader.registerPage(route, fn)
})
Expand Down Expand Up @@ -99,7 +103,8 @@ export default async ({
App,
Component,
ErrorComponent,
err: initialErr
err: initialErr,
basePath,
})

router.subscribe(({ App, Component, props, hash, err }) => {
Expand Down
2 changes: 1 addition & 1 deletion client/next-dev.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const {
}
} = window

const prefix = assetPrefix || ''
const prefix = assetPrefix || '/account' || ''
const webpackHMR = initWebpackHMR({assetPrefix: prefix})

window.next = next
Expand Down
2 changes: 1 addition & 1 deletion client/webpack-hot-middleware-client.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ const handlers = {

export default ({assetPrefix}) => {
const options = {
path: `${assetPrefix}/_next/webpack-hmr`
path: `${assetPrefix || '/account'}/_next/webpack-hmr`
}

const devClient = connect(options)
Expand Down
4 changes: 4 additions & 0 deletions examples/with-zones/.babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"presets": ["next/babel"],
"plugins": []
}
2 changes: 2 additions & 0 deletions examples/with-zones/account/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
.next
node_modules
7 changes: 7 additions & 0 deletions examples/with-zones/account/next.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const { NOW_URL } = process.env
const { alias } = require('./now.json')

module.exports = {
// assetPrefix: NOW_URL ? `https://${alias}` : 'http://localhost:3000',
basePath: '/account',
}
3 changes: 3 additions & 0 deletions examples/with-zones/account/now.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"alias": "with-zones-account.now.sh"
}
14 changes: 14 additions & 0 deletions examples/with-zones/account/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"name": "with-zones-account",
"version": "1.0.0",
"scripts": {
"build": "next build",
"start": "next start -p 3000"
},
"dependencies": {
"next": "latest",
"react": "^16.0.0",
"react-dom": "^16.0.0"
},
"license": "ISC"
}
25 changes: 25 additions & 0 deletions examples/with-zones/account/pages/_app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import App, {Container} from 'next/app'
import React from 'react'
import Link from "next/link";

export default class MyApp extends App {
static async getInitialProps ({ Component, router, ctx }) {
let pageProps = {}

if (Component.getInitialProps) {
pageProps = await Component.getInitialProps(ctx)
}

return {pageProps}
}

render () {
const {Component, pageProps} = this.props
return <Container>
<Link href="/account"><a>index</a></Link>
<br />
<Link href="/account/password"><a>password</a></Link>
<Component {...pageProps} />
</Container>
}
}
26 changes: 26 additions & 0 deletions examples/with-zones/account/pages/_document.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// _document is only rendered on the server side and not on the client side
// Event handlers like onClick can't be added to this file

// ./pages/_document.js
import Document, { Head, Main, NextScript } from 'next/document'

export default class MyDocument extends Document {
static async getInitialProps(ctx) {
const initialProps = await Document.getInitialProps(ctx)
return { ...initialProps }
}

render() {
return (
<html>
<Head>
<style>{`body { margin: 0 } /* custom! */`}</style>
</Head>
<body className="custom_class">
<Main />
<NextScript />
</body>
</html>
)
}
}
5 changes: 5 additions & 0 deletions examples/with-zones/account/pages/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export default () => (
<div>
This is your account
</div>
)
11 changes: 11 additions & 0 deletions examples/with-zones/account/pages/password.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import React from 'react';

const password = () => {
return (
<div>
password
</div>
);
};

export default password;
1 change: 1 addition & 0 deletions examples/with-zones/home/pages/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export default () => (
<p>This is our homepage</p>
<div><Link href='/blog'><a>Blog</a></Link></div>
<div><Link href='/about'><a>About us</a></Link></div>
<div><Link href='/account'><a>Account</a></Link></div>
<img width={200} src={asset('/nextjs.png')} />
</div>
)
3 changes: 3 additions & 0 deletions examples/with-zones/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@
"blog": "next blog -p 5000",
"blog-build": "next build blog",
"blog-start": "next start blog -p 5000",
"account": "next account -p 3000",
"account-build": "next build account",
"account-start": "next start account -p 3000",
"proxy": "micro-proxy -r rules-dev.json"
},
"dependencies": {
Expand Down
1 change: 1 addition & 0 deletions examples/with-zones/rules-dev.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
"rules": [
{"pathname": "/blog", "method":["GET", "POST", "OPTIONS"], "dest": "http://localhost:5000"},
{"pathname": "/account", "dest": "http://localhost:3000"},
{"pathname": "/**", "dest": "http://localhost:4000"}
]
}
2 changes: 1 addition & 1 deletion lib/asset.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export default function asset (path) {
}

const pathWithoutSlash = path.replace(/^\//, '')
return `${assetPrefix || ''}/static/${pathWithoutSlash}`
return `${assetPrefix || '/account' || ''}/static/${pathWithoutSlash}`
}

export function setAssetPrefix (url) {
Expand Down
7 changes: 5 additions & 2 deletions lib/page-loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@ import EventEmitter from './EventEmitter'
const webpackModule = module

export default class PageLoader {
constructor (buildId, assetPrefix) {
constructor (buildId, assetPrefix, basePath) {
this.buildId = buildId
this.assetPrefix = assetPrefix
this.basePath = basePath

this.pageCache = {}
this.pageLoadedHandlers = {}
Expand All @@ -25,6 +26,7 @@ export default class PageLoader {
}

loadPage (route) {
console.log('loadPage', route)
route = this.normalizeRoute(route)

return new Promise((resolve, reject) => {
Expand Down Expand Up @@ -69,7 +71,8 @@ export default class PageLoader {
const scriptRoute = route === '/' ? '/index.js' : `${route}.js`

const script = document.createElement('script')
const url = `${this.assetPrefix}/_next/static/${encodeURIComponent(this.buildId)}/pages${scriptRoute}`
const url = `${this.assetPrefix || this.basePath}/_next/static/${encodeURIComponent(this.buildId)}/pages${scriptRoute}`
console.log('loadScript', this.basePath, url);
script.src = url
script.onerror = () => {
const error = new Error(`Error when loading route: ${route}`)
Expand Down
10 changes: 8 additions & 2 deletions lib/router/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,9 @@ const historyMethodWarning = execOnce((method) => {
export default class Router {
static events = new EventEmitter()

constructor (pathname, query, as, { initialProps, pageLoader, App, Component, ErrorComponent, err } = {}) {
constructor (pathname, query, as, { initialProps, pageLoader, App, Component, ErrorComponent, err, basePath } = {}) {
// represents the current component key
console.log('Initializing router', basePath)
this.route = toRoute(pathname)

// set up the component cache (by route keys)
Expand All @@ -44,6 +45,7 @@ export default class Router {
this.asPath = as
this.subscriptions = new Set()
this.componentLoadCancel = null
this.basePath = basePath
this._beforePopState = () => true

if (typeof window !== 'undefined') {
Expand Down Expand Up @@ -255,7 +257,7 @@ export default class Router {
// 3. Internal error while loading the page

// So, doing a hard reload is the proper way to deal with this.
window.location.href = as
// window.location.href = as

// Changing the URL doesn't block executing the current code path.
// So, we need to mark it as a cancelled error and stop the routing logic.
Expand Down Expand Up @@ -355,6 +357,10 @@ export default class Router {
}

async fetchComponent (route, as) {
route = route.replace(this.basePath, '')
if ( route === '') {
route = '/'
}
let cancelled = false
const cancel = this.componentLoadCancel = function () {
cancelled = true
Expand Down
3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,7 @@
"coveralls": "nyc --instrument=false --source-map=false report --temp-directory=./coverage --reporter=text-lcov | coveralls",
"flow": "flow check",
"lint": "standard 'bin/*' 'client/**/*.js' 'examples/**/*.js' 'lib/**/*.js' 'pages/**/*.js' 'server/**/*.js' 'build/**/*.js' 'test/**/*.js'",
"prepublish": "npm run release",
"precommit": "lint-staged"
"prepublish": "npm run release"
},
"standard": {
"parser": "babel-eslint",
Expand Down
Loading