From ddab34a55f18dfbcd7246697126e29598b0a2854 Mon Sep 17 00:00:00 2001 From: okoala Date: Tue, 26 Dec 2017 11:58:32 +0800 Subject: [PATCH 01/36] feat: _avet --> _app --- package.json | 3 +- packages/avet-build/lib/createCompiler.js | 30 ++++---- .../lib/plugins/dynamic-chunks-plugin.js | 2 +- .../avet-build/lib/plugins/pages-plugin.js | 2 +- packages/avet-client/src/head-manager.js | 4 +- packages/avet-client/src/index.js | 18 ++--- .../src/on-demand-entries-client.js | 2 +- .../src/webpack-hot-middleware-client.js | 4 +- packages/avet-server/lib/export.js | 20 +++--- .../lib/on-demand-entry-handler.js | 12 ++-- packages/avet-server/lib/render.js | 8 +-- packages/avet-server/lib/server.js | 18 ++--- packages/avet-shared/src/document.js | 72 +++++++++---------- packages/avet-shared/src/head.js | 4 +- packages/avet-shared/src/link.js | 8 +-- packages/avet-shared/src/page-loader.js | 10 +-- packages/avet-shared/src/router/router.js | 12 ++-- packages/avet-shared/test/router.test.js | 10 +-- packages/avet/config/config.default.js | 4 +- 19 files changed, 121 insertions(+), 122 deletions(-) diff --git a/package.json b/package.json index 90718f1..d6837a1 100644 --- a/package.json +++ b/package.json @@ -9,8 +9,7 @@ "debug": "lerna run debug", "release": "npm run changelog && npm run build && npm run publish", "lint": "eslint --ext .js packages", - "doc:start": - "cross-env NODE_ENV=development && bisheng start -c ./site/bisheng.config.js", + "doc:start": "cross-env NODE_ENV=development && bisheng start -c ./site/bisheng.config.js", "doc:build": "bisheng build --ssr -c ./site/bisheng.config.js", "doc:deploy": "bisheng gh-pages --ssr -c ./site/bisheng.config.js", "bench": "loadtest -c 10 -n 50 http://127.0.0.1:3000" diff --git a/packages/avet-build/lib/createCompiler.js b/packages/avet-build/lib/createCompiler.js index ae0172f..221be73 100644 --- a/packages/avet-build/lib/createCompiler.js +++ b/packages/avet-build/lib/createCompiler.js @@ -39,12 +39,12 @@ module.exports = async function createCompiler( const pluginModuleBabelAlias = getPluginModuleBabelAlias(plugins); const documentPage = join('page', '_document.js'); - const defaultPages = [ '_error.js', '_document.js' ]; + const defaultPages = ['_error.js', '_document.js']; const avetPagesDir = join(__dirname, 'page'); const avetNodeModulesDir = join(rootDir, 'node_modules'); const interpolateNames = new Map( defaultPages.map(p => { - return [ join(avetPagesDir, p), `dist/page/${p}` ]; + return [join(avetPagesDir, p), `dist/page/${p}`]; }) ); @@ -63,7 +63,7 @@ module.exports = async function createCompiler( const entry = async () => { const entries = { - 'main.js': [ ...defaultEntries, mainJS ], + 'main.js': [...defaultEntries, mainJS], }; const pages = await glob('page/**/*.js', { cwd: rootDir }); @@ -75,18 +75,18 @@ module.exports = async function createCompiler( // managing pages. if (dev) { for (const p of devPages) { - entries[join('bundles', p)] = [ `./${p}?entry` ]; + entries[join('bundles', p)] = [`./${p}?entry`]; } } else { for (const p of pages) { - entries[join('bundles', p)] = [ `./${p}?entry` ]; + entries[join('bundles', p)] = [`./${p}?entry`]; } } for (const p of defaultPages) { const entryName = join('bundles', 'page', p); if (!entries[entryName]) { - entries[entryName] = [ `${join(avetPagesDir, p)}?entry` ]; + entries[entryName] = [`${join(avetPagesDir, p)}?entry`]; } } @@ -104,7 +104,7 @@ module.exports = async function createCompiler( return interpolateNames.get(this.resourcePath) || url; }, resolve: { - extensions: [ '.ts', '.tsx', '.js' ], + extensions: ['.ts', '.tsx', '.js'], }, }, }), @@ -176,7 +176,7 @@ module.exports = async function createCompiler( webpackPlugins.push(new webpack.IgnorePlugin(/react-hot-loader/)); webpackPlugins.push( new CombineAssetsPlugin({ - input: [ 'manifest.js', 'commons.js', 'main.js' ], + input: ['manifest.js', 'commons.js', 'main.js'], output: 'app.js', }), new UglifyJSPlugin({ @@ -220,7 +220,7 @@ module.exports = async function createCompiler( { test: /\.js(\?[^?]*)?$/, loader: 'hot-self-accept-loader', - include: [ join(rootDir, 'page'), avetPagesDir ], + include: [join(rootDir, 'page'), avetPagesDir], }, { test: /\.js(\?[^?]*)?$/, @@ -237,7 +237,7 @@ module.exports = async function createCompiler( { test: /\.(js|json)(\?[^?]*)?$/, loader: 'emit-file-loader', - include: [ rootDir, avetPagesDir ], + include: [rootDir, avetPagesDir], exclude(str) { return /node_modules/.test(str) && str.indexOf(avetPagesDir) !== 0; }, @@ -323,20 +323,20 @@ module.exports = async function createCompiler( }, { loader: require.resolve('babel-loader'), - include: [ avetPagesDir ], + include: [avetPagesDir], exclude(str) { return /node_modules/.test(str) && str.indexOf(avetPagesDir) !== 0; }, options: { babelrc: false, cacheDirectory: true, - presets: [ require.resolve('./babel/preset') ], + presets: [require.resolve('./babel/preset')], }, }, { test: /\.(js|jsx)(\?[^?]*)?$/, loader: require.resolve('babel-loader'), - include: [ baseDir ], + include: [baseDir], exclude(str) { return ( /core-js/.test(str) || @@ -356,7 +356,7 @@ module.exports = async function createCompiler( path: join(rootDir, buildConfig.distDir), filename: '[name]', libraryTarget: 'commonjs2', - publicPath: '/_avet/webpack/', + publicPath: '/_app/webpack/', strictModuleExceptionHandling: true, devtoolModuleFilenameTemplate({ resourcePath }) { const hash = createHash('sha1'); @@ -370,7 +370,7 @@ module.exports = async function createCompiler( chunkFilename: '[name]', }, resolve: { - modules: [ avetNodeModulesDir, 'node_modules', ...nodePathList ], + modules: [avetNodeModulesDir, 'node_modules', ...nodePathList], }, resolveLoader: { modules: [ diff --git a/packages/avet-build/lib/plugins/dynamic-chunks-plugin.js b/packages/avet-build/lib/plugins/dynamic-chunks-plugin.js index c7cbf07..8bc20d2 100644 --- a/packages/avet-build/lib/plugins/dynamic-chunks-plugin.js +++ b/packages/avet-build/lib/plugins/dynamic-chunks-plugin.js @@ -16,7 +16,7 @@ module.exports = class PagesPlugin { const content = asset.source(); const newContent = ` - window.__AVET_REGISTER_CHUNK('${chunkName}', function() { + window.__APP_REGISTER_CHUNK('${chunkName}', function() { ${content} }) `; diff --git a/packages/avet-build/lib/plugins/pages-plugin.js b/packages/avet-build/lib/plugins/pages-plugin.js index c2f260a..54f56b7 100644 --- a/packages/avet-build/lib/plugins/pages-plugin.js +++ b/packages/avet-build/lib/plugins/pages-plugin.js @@ -26,7 +26,7 @@ module.exports = class PagesPlugin { const content = page.source(); const newContent = ` - window.__AVET_REGISTER_PAGE('${routeName}', function() { + window.__APP_REGISTER_PAGE('${routeName}', function() { var comp = ${content} return { page: comp.default } }) diff --git a/packages/avet-client/src/head-manager.js b/packages/avet-client/src/head-manager.js index e45c195..13e3326 100644 --- a/packages/avet-client/src/head-manager.js +++ b/packages/avet-client/src/head-manager.js @@ -31,7 +31,7 @@ export default class HeadManager { this.updateTitle(tags.title ? tags.title[0] : null); - const types = [ 'meta', 'base', 'link', 'style', 'script' ]; + const types = ['meta', 'base', 'link', 'style', 'script']; types.forEach(type => { this.updateElements(type, tags[type] || []); }); @@ -51,7 +51,7 @@ export default class HeadManager { updateElements(type, components) { const headEl = document.getElementsByTagName('head')[0]; const oldTags = Array.prototype.slice.call( - headEl.querySelectorAll(`${type}.avet-head`) + headEl.querySelectorAll(`${type}.app-head`) ); const newTags = components.map(reactElementToDOM).filter(newTag => { for (let i = 0, len = oldTags.length; i < len; i++) { diff --git a/packages/avet-client/src/index.js b/packages/avet-client/src/index.js index df1ed57..a10da75 100644 --- a/packages/avet-client/src/index.js +++ b/packages/avet-client/src/index.js @@ -18,29 +18,29 @@ if (!window.Promise) { } const { - __AVET_DATA__: { props, err, pathname, query, buildId, chunks, assetPrefix }, + __APP_DATA__: { props, err, pathname, query, buildId, chunks, assetPrefix }, location, } = window; const asPath = getURL(); const pageLoader = new PageLoader(buildId, assetPrefix); -window.__AVET_LOADED_PAGES__.forEach(({ route, fn }) => { +window.__APP_LOADED_PAGES__.forEach(({ route, fn }) => { pageLoader.registerPage(route, fn); }); -delete window.__AVET_LOADED_PAGES__; +delete window.__APP_LOADED_PAGES__; -window.__AVET_LOADED_CHUNKS__.forEach(({ chunkName, fn }) => { +window.__APP_LOADED_CHUNKS__.forEach(({ chunkName, fn }) => { pageLoader.registerChunk(chunkName, fn); }); -delete window.__AVET_LOADED_CHUNKS__; +delete window.__APP_LOADED_CHUNKS__; -window.__AVET_REGISTER_PAGE = pageLoader.registerPage.bind(pageLoader); -window.__AVET_REGISTER_CHUNK = pageLoader.registerChunk.bind(pageLoader); +window.__APP_REGISTER_PAGE = pageLoader.registerPage.bind(pageLoader); +window.__APP_REGISTER_CHUNK = pageLoader.registerChunk.bind(pageLoader); const headManager = new HeadManager(); -const appContainer = document.getElementById('__avet'); -const errorContainer = document.getElementById('__avet-error'); +const appContainer = document.getElementById('__app'); +const errorContainer = document.getElementById('__app-error'); let lastAppProps; export let router; diff --git a/packages/avet-client/src/on-demand-entries-client.js b/packages/avet-client/src/on-demand-entries-client.js index 30fe9f2..83a2f62 100644 --- a/packages/avet-client/src/on-demand-entries-client.js +++ b/packages/avet-client/src/on-demand-entries-client.js @@ -10,7 +10,7 @@ export default () => { async function ping() { try { - const url = `/_avet/on-demand-entries-ping?page=${Router.pathname}`; + const url = `/_app/on-demand-entries-ping?page=${Router.pathname}`; const res = await fetch(url, { credentials: 'same-origin', }); diff --git a/packages/avet-client/src/webpack-hot-middleware-client.js b/packages/avet-client/src/webpack-hot-middleware-client.js index 7a1ea20..dbc2e63 100644 --- a/packages/avet-client/src/webpack-hot-middleware-client.js +++ b/packages/avet-client/src/webpack-hot-middleware-client.js @@ -1,4 +1,4 @@ -import webpackHotMiddlewareClient from 'webpack-hot-middleware/client?overlay=false&reload=true&path=/_avet/webpack-hmr'; +import webpackHotMiddlewareClient from 'webpack-hot-middleware/client?overlay=false&reload=true&path=/_app/webpack-hmr'; import Router from 'avet-shared/lib/router'; export default () => { @@ -60,7 +60,7 @@ export default () => { const data = obj.data || []; fn(...data); } else { - throw new Error(`Unexpected action ${ obj.action}`); + throw new Error(`Unexpected action ${obj.action}`); } }); }; diff --git a/packages/avet-server/lib/export.js b/packages/avet-server/lib/export.js index ccfefa4..13e6ca0 100644 --- a/packages/avet-server/lib/export.js +++ b/packages/avet-server/lib/export.js @@ -7,7 +7,7 @@ const { existsSync, readFileSync, writeFileSync } = require('fs'); const { renderToHTML } = require('./render'); const { getAvailableChunks, printAndExit } = require('avet-utils'); -module.exports = async function(dir, options) { +module.exports = async function (dir, options) { dir = resolve(dir); const avetDir = join(dir, options.distDir); @@ -26,13 +26,13 @@ module.exports = async function(dir, options) { // Initialize the output directory const outDir = options.outdir; await del(join(outDir, '*')); - await mkdirp(join(outDir, '_avet', buildStats['app.js'].hash)); - await mkdirp(join(outDir, '_avet', buildId)); + await mkdirp(join(outDir, '_app', buildStats['app.js'].hash)); + await mkdirp(join(outDir, '_app', buildId)); // Copy files await cp( join(avetDir, 'app.js'), - join(outDir, '_avet', buildStats['app.js'].hash, 'app.js') + join(outDir, '_app', buildStats['app.js'].hash, 'app.js') ); // Copy static directory @@ -45,10 +45,10 @@ module.exports = async function(dir, options) { if (existsSync(join(avetDir, 'chunks'))) { log(' copying dynamic import chunks'); - await mkdirp(join(outDir, '_avet', 'webpack')); + await mkdirp(join(outDir, '_app', 'webpack')); await cp( join(avetDir, 'chunks'), - join(outDir, '_avet', 'webpack', 'chunks') + join(outDir, '_app', 'webpack', 'chunks') ); } @@ -58,7 +58,7 @@ module.exports = async function(dir, options) { if (typeof options.buildConfig.exportPathMap !== 'function') { printAndExit( '> Could not found "exportPathMap" function in config \n' + - '> "avet export" uses that function build html pages.' + '> "avet export" uses that function build html pages.' ); } @@ -79,7 +79,7 @@ module.exports = async function(dir, options) { }; // We need this for server rendering the Link component. - global.__AVET_DATA__ = { + global.__APP_DATA__ = { avetExport: true, }; @@ -130,7 +130,7 @@ function copyPages(avetDir, outDir, buildId) { let destFilePath = null; if (/index\.js$/.test(filename)) { - destFilePath = join(outDir, '_avet', buildId, 'page', relativeFilePath); + destFilePath = join(outDir, '_app', buildId, 'page', relativeFilePath); } else { const newRelativeFilePath = relativeFilePath.replace( /\.js/, @@ -138,7 +138,7 @@ function copyPages(avetDir, outDir, buildId) { ); destFilePath = join( outDir, - '_avet', + '_app', buildId, 'page', newRelativeFilePath diff --git a/packages/avet-server/lib/on-demand-entry-handler.js b/packages/avet-server/lib/on-demand-entry-handler.js index 5fa6e7e..7ea975f 100644 --- a/packages/avet-server/lib/on-demand-entry-handler.js +++ b/packages/avet-server/lib/on-demand-entry-handler.js @@ -56,7 +56,7 @@ module.exports = function onDemandEntryHandler( { dir, reload, maxInactiveAge = 1000 * 25 } ) { const entries = {}; - const lastAccessPages = [ '' ]; + const lastAccessPages = ['']; let doneCallbacks = new EventEmitter(); const invalidator = new Invalidator(devMiddleware); let touchedAPage = false; @@ -64,7 +64,7 @@ module.exports = function onDemandEntryHandler( let stopped = false; let reloadCallbacks = new EventEmitter(); - compiler.plugin('make', function(compilation, done) { + compiler.plugin('make', function (compilation, done) { invalidator.startBuilding(); const allEntries = Object.keys(entries).map(page => { @@ -95,7 +95,7 @@ module.exports = function onDemandEntryHandler( return e.module.dependencies.length === 0; }) .map(e => e.module.chunks) - .reduce((a, b) => [ ...a, ...b ], []) + .reduce((a, b) => [...a, ...b], []) .map(c => { const pageName = MATCH_ROUTE_NAME.exec(c.name)[1]; return normalizePage(`/${pageName}`); @@ -180,7 +180,7 @@ module.exports = function onDemandEntryHandler( const pathname = await resolvePath(pagePath); const name = join('bundles', pathname.substring(dir.length)); - const entry = [ `${pathname}?entry` ]; + const entry = [`${pathname}?entry`]; await new Promise((resolve, reject) => { const entryInfo = entries[page]; @@ -212,7 +212,7 @@ module.exports = function onDemandEntryHandler( }, middleware() { - return function*(next) { + return function* (next) { const ctx = this; if (stopped) { @@ -231,7 +231,7 @@ module.exports = function onDemandEntryHandler( ctx.body = '302'; }); } else { - if (!/^\/_avet\/on-demand-entries-ping/.test(ctx.url)) + if (!/^\/_app\/on-demand-entries-ping/.test(ctx.url)) return yield next; const page = normalizePage(ctx.request.query.page); diff --git a/packages/avet-server/lib/render.js b/packages/avet-server/lib/render.js index 253a93c..87241a6 100644 --- a/packages/avet-server/lib/render.js +++ b/packages/avet-server/lib/render.js @@ -48,7 +48,7 @@ async function renderScriptError(ctx, page, error, customFields = {}, { dev }) { if (error.code === 'ENOENT') { ctx.type = 'text/javascript'; ctx.body = ` - window.__AVET_REGISTER_PAGE('${page}', function() { + window.__APP_REGISTER_PAGE('${page}', function() { var error = new Error('Page does not exist: ${page}'); error.statusCode = 404; @@ -63,7 +63,7 @@ async function renderScriptError(ctx, page, error, customFields = {}, { dev }) { const errorJson = Object.assign({}, serializeError(dev, error), customFields); ctx.body = ` - window.__AVET_REGISTER_PAGE('${page}', function() { + window.__APP_REGISTER_PAGE('${page}', function() { var error = ${JSON.stringify(errorJson)}; return { error: error }; }); @@ -137,7 +137,7 @@ async function doRender( await ensurePage(page, { dir, hotReloader }); - let [ Component, Document ] = await Promise.all([ + let [Component, Document] = await Promise.all([ requireModule(join(dir, dist, 'dist', 'page', page)), requireModule(join(dir, dist, 'dist', 'page', '_document')), ]); @@ -206,7 +206,7 @@ async function doRender( Object.assign( {}, { - __AVET_DATA__: { + __APP_DATA__: { props, pathname: ctx.path, query: ctx.query, diff --git a/packages/avet-server/lib/server.js b/packages/avet-server/lib/server.js index e07e3f8..0f5aa5c 100644 --- a/packages/avet-server/lib/server.js +++ b/packages/avet-server/lib/server.js @@ -14,7 +14,7 @@ const { const { getAvailableChunks } = require('avet-utils'); -const internalPrefixes = [ /^\/_avet\//, /^\/static\// ]; +const internalPrefixes = [ /^\/_app\//, /^\/static\// ]; const blockedPages = { '/_document': true, @@ -83,19 +83,19 @@ class Server { defineRoutes() { const routes = { // This is to support, webpack dynamic imports in production. - '/_avet/webpack/chunks/:name': async (ctx, params) => { + '/_app/webpack/chunks/:name': async (ctx, params) => { ctx.set('cache-control', 'max-age=365000000, immutable'); const p = join(this.dir, this.dist, 'chunks', params.name); await this.serveStatic(ctx, p); }, // This is to support, webpack dynamic import support with HMR - '/_avet/webpack/:id': async (ctx, params) => { + '/_app/webpack/:id': async (ctx, params) => { const p = join(this.dir, this.dist, 'chunks', params.id); await this.serveStatic(ctx, p); }, - '/_avet/:hash/manifest.js': async (ctx, params) => { + '/_app/:hash/manifest.js': async (ctx, params) => { if (!this.dev) return this.send404(ctx); this.handleBuildHash('manifest.js', params.hash, ctx); @@ -103,7 +103,7 @@ class Server { await this.serveStatic(ctx, p); }, - '/_avet/:hash/main.js': async (ctx, params) => { + '/_app/:hash/main.js': async (ctx, params) => { if (!this.dev) return this.send404(ctx); this.handleBuildHash('main.js', params.hash, ctx); @@ -111,7 +111,7 @@ class Server { await this.serveStatic(ctx, p); }, - '/_avet/:hash/commons.js': async (ctx, params) => { + '/_app/:hash/commons.js': async (ctx, params) => { if (!this.dev) return this.send404(ctx); this.handleBuildHash('commons.js', params.hash, ctx); @@ -120,7 +120,7 @@ class Server { await this.serveStatic(ctx, p); }, - '/_avet/:hash/app.js': async (ctx, params) => { + '/_app/:hash/app.js': async (ctx, params) => { if (this.dev) return this.send404(ctx); this.handleBuildHash('app.js', params.hash, ctx); @@ -128,7 +128,7 @@ class Server { await this.serveStatic(ctx, p); }, - '/_avet/:buildId/page/_error*': async (ctx, params) => { + '/_app/:buildId/page/_error*': async (ctx, params) => { if (!this.handleBuildId(params.buildId, ctx.response)) { const error = new Error('INVALID_BUILD_ID'); const customFields = { buildIdMismatched: true }; @@ -146,7 +146,7 @@ class Server { await this.serveStatic(ctx, p); }, - '/_avet/:buildId/page/:path*': async (ctx, params) => { + '/_app/:buildId/page/:path*': async (ctx, params) => { const paths = params.path || [ '' ]; const page = `/${paths.join('/')}`; diff --git a/packages/avet-shared/src/document.js b/packages/avet-shared/src/document.js index 88ffc1f..a2d8e7c 100644 --- a/packages/avet-shared/src/document.js +++ b/packages/avet-shared/src/document.js @@ -39,7 +39,7 @@ export class Html extends Component { let content = isReactComponent(comp) ? comp : comp.content; if (content) { if (!Array.isArray(content)) { - content = [ content ]; + content = [content]; } mixinChild = mixinChild.concat(content); } @@ -67,15 +67,15 @@ export class Head extends Component { }; getChunkPreloadLink(filename) { - const { __AVET_DATA__ } = this.context._documentProps; - const { buildStats, assetPrefix, buildId } = __AVET_DATA__; + const { __APP_DATA__ } = this.context._documentProps; + const { buildStats, assetPrefix, buildId } = __APP_DATA__; const hash = buildStats ? buildStats[filename].hash : buildId; return ( ); @@ -92,25 +92,25 @@ export class Head extends Component { } // In the production mode, we have a single asset with all the JS content. - return [ this.getChunkPreloadLink('app.js') ]; + return [this.getChunkPreloadLink('app.js')]; } getPreloadDynamicChunks() { - const { chunks, __AVET_DATA__ } = this.context._documentProps; - const { assetPrefix } = __AVET_DATA__; + const { chunks, __APP_DATA__ } = this.context._documentProps; + const { assetPrefix } = __APP_DATA__; return chunks.map(chunk => ( )); } render() { - const { head, styles, __AVET_DATA__ } = this.context._documentProps; - const { pathname, buildId, assetPrefix, avetExport } = __AVET_DATA__; + const { head, styles, __APP_DATA__ } = this.context._documentProps; + const { pathname, buildId, assetPrefix, avetExport } = __APP_DATA__; const pagePathname = getPagePathname(pathname, avetExport); let mixinProps = {}; @@ -124,7 +124,7 @@ export class Head extends Component { let content = isReactComponent(comp) ? comp : comp.content; if (content) { if (!Array.isArray(content)) { - content = [ content ]; + content = [content]; } mixinChild = mixinChild.concat(content); } @@ -135,12 +135,12 @@ export class Head extends Component { {this.getPreloadDynamicChunks()} @@ -179,9 +179,9 @@ export class Main extends Component { return (
{mixinMain} -
+
@@ -195,15 +195,15 @@ export class AvetScript extends Component { }; getChunkScript(filename, additionalProps = {}) { - const { __AVET_DATA__ } = this.context._documentProps; - const { buildStats, assetPrefix, buildId } = __AVET_DATA__; + const { __APP_DATA__ } = this.context._documentProps; + const { buildStats, assetPrefix, buildId } = __APP_DATA__; const hash = buildStats ? buildStats[filename].hash : buildId; return (