From 52647b07fb91dd08e026e1a5cf04e9c811f9410a Mon Sep 17 00:00:00 2001 From: fushen Date: Mon, 27 Sep 2021 22:29:45 +0800 Subject: [PATCH 1/7] feat: support harmony --- examples/with-rax-mpa/build.json | 14 +++-- examples/with-rax-mpa/src/app.json | 4 -- .../src/components/Logo/index.tsx | 3 +- .../with-rax-mpa/src/pages/About/app.json | 11 ---- examples/with-rax-mpa/src/pages/About/app.ts | 19 ------- .../with-rax-mpa/src/pages/About/index.css | 16 ------ .../with-rax-mpa/src/pages/About/index.tsx | 16 ------ .../with-rax-mpa/src/pages/Home/index.css | 14 ++--- .../with-rax-mpa/src/pages/Home/index.tsx | 13 +++-- package.json | 3 +- .../platform-loader/src/TraverseImport.js | 1 + packages/plugin-rax-app/src/constants.js | 1 + packages/plugin-rax-app/src/setBuild.js | 11 ++++ packages/plugin-rax-app/src/setDev.js | 19 ++++++- .../src/userConfig/inlineStyle.js | 3 +- packages/plugin-rax-harmony/CHANGELOG.md | 3 ++ packages/plugin-rax-harmony/package.json | 26 +++++++++ packages/plugin-rax-harmony/src/constants.js | 3 ++ packages/plugin-rax-harmony/src/index.js | 53 +++++++++++++++++++ packages/plugin-rax-harmony/src/setEntry.js | 29 ++++++++++ packages/rax-app-renderer/src/renderer.tsx | 5 +- packages/rax-app/src/index.ts | 4 ++ 22 files changed, 177 insertions(+), 94 deletions(-) delete mode 100644 examples/with-rax-mpa/src/pages/About/app.json delete mode 100644 examples/with-rax-mpa/src/pages/About/app.ts delete mode 100644 examples/with-rax-mpa/src/pages/About/index.css delete mode 100644 examples/with-rax-mpa/src/pages/About/index.tsx create mode 100644 packages/plugin-rax-harmony/CHANGELOG.md create mode 100644 packages/plugin-rax-harmony/package.json create mode 100644 packages/plugin-rax-harmony/src/constants.js create mode 100644 packages/plugin-rax-harmony/src/index.js create mode 100644 packages/plugin-rax-harmony/src/setEntry.js diff --git a/examples/with-rax-mpa/build.json b/examples/with-rax-mpa/build.json index 96c9fb06d..4c456142c 100644 --- a/examples/with-rax-mpa/build.json +++ b/examples/with-rax-mpa/build.json @@ -1,13 +1,11 @@ { - "targets": ["web", "weex", "kraken"], - "weex": { + "targets": ["harmony"], + "harmony": { "mpa": true }, - "kraken": { - "mpa": true + "minify": false, + "experiments": { + "exportsField": true }, - "web": { - "mpa": true, - "staticExport": true - } + "inlineStyle": true } diff --git a/examples/with-rax-mpa/src/app.json b/examples/with-rax-mpa/src/app.json index d79356ddf..7796e5b06 100644 --- a/examples/with-rax-mpa/src/app.json +++ b/examples/with-rax-mpa/src/app.json @@ -4,10 +4,6 @@ "name": "home", "source": "pages/Home/index", "spm": "b456" - }, - { - "name": "about", - "source": "pages/About/index" } ], "spm": "a123", diff --git a/examples/with-rax-mpa/src/components/Logo/index.tsx b/examples/with-rax-mpa/src/components/Logo/index.tsx index 0aa5be911..5e911121e 100644 --- a/examples/with-rax-mpa/src/components/Logo/index.tsx +++ b/examples/with-rax-mpa/src/components/Logo/index.tsx @@ -1,5 +1,4 @@ import { createElement, PureComponent } from 'rax'; -import Image from 'rax-image'; import './index.css'; @@ -10,7 +9,7 @@ class Logo extends PureComponent { }; console.log('with router =>', this.props); return ( - diff --git a/examples/with-rax-mpa/src/pages/About/app.json b/examples/with-rax-mpa/src/pages/About/app.json deleted file mode 100644 index 23abfb45d..000000000 --- a/examples/with-rax-mpa/src/pages/About/app.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "routes": [ - { - "path": "/", - "source": "./index" - } - ], - "window": { - "title": "Rax App" - } -} diff --git a/examples/with-rax-mpa/src/pages/About/app.ts b/examples/with-rax-mpa/src/pages/About/app.ts deleted file mode 100644 index 1b97b148c..000000000 --- a/examples/with-rax-mpa/src/pages/About/app.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { runApp } from 'rax-app'; -import staticConfig from './app.json'; - -runApp({ - app: { - onShow() { - console.log('app show...'); - }, - onHide() { - console.log('app hide...'); - }, - getInitialData: async () => { - return { - a: 1, - b: 2, - }; - }, - }, -}, staticConfig); diff --git a/examples/with-rax-mpa/src/pages/About/index.css b/examples/with-rax-mpa/src/pages/About/index.css deleted file mode 100644 index 85ae2d072..000000000 --- a/examples/with-rax-mpa/src/pages/About/index.css +++ /dev/null @@ -1,16 +0,0 @@ -.about { - align-items: center; - margin-top: 200rpx; -} - -.title { - font-size: 45rpx; - font-weight: bold; - margin: 20rpx 0; -} - -.info { - font-size: 36rpx; - margin: 8rpx 0; - color: #555; -} diff --git a/examples/with-rax-mpa/src/pages/About/index.tsx b/examples/with-rax-mpa/src/pages/About/index.tsx deleted file mode 100644 index 497f0c129..000000000 --- a/examples/with-rax-mpa/src/pages/About/index.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createElement, PureComponent } from 'rax'; -import View from 'rax-view'; -import Text from 'rax-text'; -import './index.css'; - -class About extends PureComponent { - render() { - return ( - - About Page - - ); - } -} - -export default About; diff --git a/examples/with-rax-mpa/src/pages/Home/index.css b/examples/with-rax-mpa/src/pages/Home/index.css index a8814796d..ddfdf67f8 100644 --- a/examples/with-rax-mpa/src/pages/Home/index.css +++ b/examples/with-rax-mpa/src/pages/Home/index.css @@ -1,16 +1,18 @@ .home { - align-items: center; - margin-top: 200rpx; + margin-top: 200px; + width: 100px; + height: 100px; + background-color: red; } .title { - font-size: 35rpx; + font-size: 35px; font-weight: bold; - margin: 20rpx 0; + margin: 20px 0; } .info { - font-size: 36rpx; - margin: 8rpx 0; + font-size: 36px; + margin: 8px 0; color: #555; } diff --git a/examples/with-rax-mpa/src/pages/Home/index.tsx b/examples/with-rax-mpa/src/pages/Home/index.tsx index 7febb5b2d..16265778c 100644 --- a/examples/with-rax-mpa/src/pages/Home/index.tsx +++ b/examples/with-rax-mpa/src/pages/Home/index.tsx @@ -1,16 +1,15 @@ import { createElement } from 'rax'; -import View from 'rax-view'; -import Text from 'rax-text'; import Logo from '@/components/Logo'; -import './index.css'; +// @ts-ignore +import styles from './index.css'; export default function Home(props) { return ( - +
- Welcome to Your Rax App - More information about Rax - + Welcome to Your Rax App + More information about Rax +
); } diff --git a/package.json b/package.json index 05c352108..cb1a12deb 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,7 @@ "author": "Rax Team", "license": "MIT", "scripts": { - "setup": "rm -rf node_modules && yarn install --no-lockfile && npm run bootstrap", - "bootstrap": "SASS_BINARY_SITE=https://npm.taobao.org/mirrors/node-sass/ npm run clean && lerna bootstrap && npm run build", + "setup": "rm -rf node_modules && yarn install && npm run build", "watch": "ts-node ./scripts/watch.ts", "build": "ts-node ./scripts/build.ts", "version": "ts-node ./scripts/tag-version.ts", diff --git a/packages/platform-loader/src/TraverseImport.js b/packages/platform-loader/src/TraverseImport.js index 20f85fe3c..6e92cf301 100644 --- a/packages/platform-loader/src/TraverseImport.js +++ b/packages/platform-loader/src/TraverseImport.js @@ -20,6 +20,7 @@ module.exports = function traverseImport(options, inputSource, sourceMapOption) 'bytedance-microapp': ['isByteDanceMicroApp'], 'kuaishou-miniprogram': ['isKuaiShouMiniProgram'], 'baidu-smartprogram': ['isBaiduSmartProgram'], + 'harmony': ['isHarmony'], }; /** diff --git a/packages/plugin-rax-app/src/constants.js b/packages/plugin-rax-app/src/constants.js index 767a743e0..c358321e2 100644 --- a/packages/plugin-rax-app/src/constants.js +++ b/packages/plugin-rax-app/src/constants.js @@ -6,6 +6,7 @@ module.exports = { SSR: 'ssr', WEEX: 'weex', KRAKEN: 'kraken', + HARMONY: 'harmony', MINIAPP, WECHAT_MINIPROGRAM, BYTEDANCE_MICROAPP, diff --git a/packages/plugin-rax-app/src/setBuild.js b/packages/plugin-rax-app/src/setBuild.js index 50ebc671b..e76be9a6a 100644 --- a/packages/plugin-rax-app/src/setBuild.js +++ b/packages/plugin-rax-app/src/setBuild.js @@ -8,6 +8,7 @@ const { WEB, WEEX, KRAKEN, + HARMONY, } = require('./constants'); const highlightPrint = chalk.hex('#F4AF3D'); @@ -74,6 +75,16 @@ module.exports = (api) => { console.log(); } }); + + if (targets.includes(HARMONY)) { + console.log(highlightPrint('[HARMONY] Bundle at:')); + console.log( + ' ', + chalk.underline.white(path.resolve(rootDir, outputDir, HARMONY)), + ); + console.log(); + } + } }); }; diff --git a/packages/plugin-rax-app/src/setDev.js b/packages/plugin-rax-app/src/setDev.js index 71693d1a3..b516b52d1 100644 --- a/packages/plugin-rax-app/src/setDev.js +++ b/packages/plugin-rax-app/src/setDev.js @@ -8,7 +8,7 @@ const chokidar = require('chokidar'); const { platformMap } = require('miniapp-builder-shared'); const logWebpackConfig = require('./utils/logWebpackConfig'); -const { MINIAPP_PLATFORMS, MINIAPP, WEB, WEEX, KRAKEN, DEV_URL_PREFIX } = require('./constants'); +const { MINIAPP_PLATFORMS, MINIAPP, WEB, WEEX, KRAKEN, DEV_URL_PREFIX, HARMONY } = require('./constants'); const generateTempFile = require('./utils/generateTempFile'); const highlightPrint = chalk.hex('#F4AF3D'); @@ -39,9 +39,11 @@ module.exports = function (api) { let webEntryKeys = []; let weexEntryKeys = []; let krakenEntryKeys = []; + let harmonyEntryKeys = []; let webMpa = false; let weexMpa = false; let krakenMpa = false; + let harmonyMpa = false; let isFirstCompile = true; let pha = false; watchAppJson(rootDir, log); @@ -66,16 +68,19 @@ module.exports = function (api) { const webWebpackInfo = getWebpackInfo(configs, 'web'); const weexWebpackInfo = getWebpackInfo(configs, 'weex'); const krakenWebpackInfo = getWebpackInfo(configs, 'kraken'); + const harmonyWebpackInfo = getWebpackInfo(configs, 'harmony'); devInfo.publicPath = webWebpackInfo.publicPath; webEntryKeys = Object.keys(webWebpackInfo.entry); weexEntryKeys = Object.keys(weexWebpackInfo.entry); krakenEntryKeys = Object.keys(krakenWebpackInfo.entry); + harmonyEntryKeys = Object.keys(harmonyWebpackInfo.entry); webMpa = userConfig.web && userConfig.web.mpa; weexMpa = userConfig.weex && userConfig.weex.mpa; krakenMpa = userConfig.kraken && userConfig.kraken.mpa; + harmonyMpa = userConfig.harmony && userConfig.harmony.mpa; pha = userConfig.web && userConfig.web.pha; // Remove outputDir when start devServer @@ -200,6 +205,18 @@ module.exports = function (api) { }); } + if (targets.includes(HARMONY)) { + devInfo.urls.harmony = []; + // Use Weex App to scan ip address (mobile phone can't visit localhost). + console.log(highlightPrint(' [Harmony] Development server at: ')); + weexEntryKeys.forEach((entryKey) => { + const harmonyUrl = `${urlPrefix}/harmony/${harmonyMpa ? entryKey : 'index'}.js`; + devInfo.urls.weex.push(harmonyUrl); + console.log(` ${chalk.underline.white(harmonyUrl)}`); + console.log(); + }); + } + /** * @TODO: Delete it first, and then open it after the PHA supports it */ diff --git a/packages/plugin-rax-app/src/userConfig/inlineStyle.js b/packages/plugin-rax-app/src/userConfig/inlineStyle.js index d24d52f61..db3207da2 100644 --- a/packages/plugin-rax-app/src/userConfig/inlineStyle.js +++ b/packages/plugin-rax-app/src/userConfig/inlineStyle.js @@ -1,11 +1,12 @@ const { resolve } = require('path'); -const { WEB, WEEX, DOCUMENT, SSR, KRAKEN, MINIAPP, WECHAT_MINIPROGRAM, BYTEDANCE_MICROAPP, BAIDU_SMARTPROGRAM, KUAISHOU_MINIPROGRAM } = require('../constants'); +const { WEB, WEEX, DOCUMENT, SSR, KRAKEN, MINIAPP, WECHAT_MINIPROGRAM, BYTEDANCE_MICROAPP, BAIDU_SMARTPROGRAM, KUAISHOU_MINIPROGRAM, HARMONY } = require('../constants'); const { createCSSRule } = require('rax-webpack-config'); const configPath = resolve(__dirname, '../'); const webStandardList = [ WEB, + HARMONY, ]; const inlineStandardList = [ diff --git a/packages/plugin-rax-harmony/CHANGELOG.md b/packages/plugin-rax-harmony/CHANGELOG.md new file mode 100644 index 000000000..ee12962c6 --- /dev/null +++ b/packages/plugin-rax-harmony/CHANGELOG.md @@ -0,0 +1,3 @@ +# Changelog + +## v1.0.0 diff --git a/packages/plugin-rax-harmony/package.json b/packages/plugin-rax-harmony/package.json new file mode 100644 index 000000000..397803073 --- /dev/null +++ b/packages/plugin-rax-harmony/package.json @@ -0,0 +1,26 @@ +{ + "name": "build-plugin-rax-harmony", + "version": "1.0.0", + "description": "rax harmony app plugin", + "main": "lib/index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [ + "plugin", + "rax" + ], + "author": "", + "license": "MIT", + "peerDependencies": { + "@alib/build-scripts": "^0.1.0", + "rax": "^1.0.0" + }, + "dependencies": { + "@builder/mpa-config": "^3.0.0", + "fs-extra": "^9.0.1", + "webpack-sources": "^2.0.0", + "@builder/app-helpers": "^2.1.0", + "react-dev-utils": "^10.0.0" + } +} diff --git a/packages/plugin-rax-harmony/src/constants.js b/packages/plugin-rax-harmony/src/constants.js new file mode 100644 index 000000000..f369bad81 --- /dev/null +++ b/packages/plugin-rax-harmony/src/constants.js @@ -0,0 +1,3 @@ +module.exports = { + GET_RAX_APP_WEBPACK_CONFIG: 'getRaxAppWebpackConfig', +}; diff --git a/packages/plugin-rax-harmony/src/index.js b/packages/plugin-rax-harmony/src/index.js new file mode 100644 index 000000000..a986670c5 --- /dev/null +++ b/packages/plugin-rax-harmony/src/index.js @@ -0,0 +1,53 @@ +const setMPAConfig = require('@builder/mpa-config'); +const { getMpaEntries } = require('@builder/app-helpers'); +const setEntry = require('./setEntry'); +const { GET_RAX_APP_WEBPACK_CONFIG } = require('./constants'); + +module.exports = (api) => { + const { getValue, context, registerTask, onGetWebpackConfig, registerUserConfig } = api; + const { userConfig, command } = context; + + const getWebpackBase = getValue(GET_RAX_APP_WEBPACK_CONFIG); + const tempDir = getValue('TEMP_PATH'); + const target = 'harmony'; + const chainConfig = getWebpackBase(api, { + target: 'harmony', + progressOptions: { + name: 'Harmony', + }, + }); + chainConfig.taskName = target; + + setEntry(chainConfig, context); + + chainConfig.name(target); + registerTask(target, chainConfig); + registerUserConfig({ + name: target, + validation: 'object', + }); + + onGetWebpackConfig(target, (config) => { + const { harmony = {} } = userConfig; + const staticConfig = getValue('staticConfig'); + // set mpa config + if (harmony.mpa) { + setMPAConfig.default(api, config, { + context, + targetDir: tempDir, + type: 'harmony', + entries: getMpaEntries(api, { + target, + appJsonContent: staticConfig, + }), + }); + } + + if (command === 'start') { + // Add webpack hot dev client + Object.keys(config.entryPoints.entries()).forEach((entryName) => { + config.entry(entryName).prepend(require.resolve('react-dev-utils/webpackHotDevClient')); + }); + } + }); +}; diff --git a/packages/plugin-rax-harmony/src/setEntry.js b/packages/plugin-rax-harmony/src/setEntry.js new file mode 100644 index 000000000..711562972 --- /dev/null +++ b/packages/plugin-rax-harmony/src/setEntry.js @@ -0,0 +1,29 @@ +const fs = require('fs-extra'); +const path = require('path'); + +module.exports = (config, context) => { + const { + rootDir, + userConfig: { harmony = {} }, + } = context; + + if (!harmony.mpa) { + // SPA + const appEntry = moduleResolve(formatPath(path.join(rootDir, './src/app'))); + const entryConfig = config.entry('index'); + + entryConfig.add(appEntry); + } +}; + +function moduleResolve(filePath) { + const ext = ['.ts', '.js', '.tsx', '.jsx'].find((extension) => fs.existsSync(`${filePath}${extension}`)); + if (!ext) { + throw new Error(`Cannot find target file ${filePath}.`); + } + return require.resolve(`${filePath}${ext}`); +} + +function formatPath(pathStr) { + return process.platform === 'win32' ? pathStr.split(path.sep).join('/') : pathStr; +} diff --git a/packages/rax-app-renderer/src/renderer.tsx b/packages/rax-app-renderer/src/renderer.tsx index 2d995c414..a31a3f1f1 100644 --- a/packages/rax-app-renderer/src/renderer.tsx +++ b/packages/rax-app-renderer/src/renderer.tsx @@ -7,6 +7,9 @@ import { IInitialContext, IContext } from './types'; import { setInitialData } from './initialData'; import parseSearch from './parseSearch'; +declare const ace: any; + +const isHarmony = typeof ace !== 'undefined'; const useRouter = createUseRouter({ useState, useLayoutEffect }); const tabBarCache = {}; @@ -168,7 +171,7 @@ async function renderInClient(options) { // Emit app launch cycle emitLifeCycles(); - const rootEl = isWeex || isKraken ? null : document.getElementById(rootId); + const rootEl = isWeex || isKraken || isHarmony ? null : document.getElementById(rootId); if (isWeb && rootId === null) console.warn('Error: Can not find #root element, please check which exists in DOM.'); const webConfig = buildConfig.web || {}; return render(appInstance, rootEl, { driver, hydrate: webConfig.hydrate || webConfig.snapshot || webConfig.ssr }); diff --git a/packages/rax-app/src/index.ts b/packages/rax-app/src/index.ts index 8c82ab1af..d74bbb30e 100644 --- a/packages/rax-app/src/index.ts +++ b/packages/rax-app/src/index.ts @@ -44,6 +44,10 @@ const getBuiltInPlugins: IGetBuiltInPlugins = (userConfig: IRaxAppUserConfig) => builtInPlugins.push('build-plugin-rax-weex'); } + if (targets.includes('harmony')) { + builtInPlugins.push('build-plugin-rax-harmony'); + } + if (targets.includes('kraken')) { builtInPlugins.push('build-plugin-rax-kraken'); } From 64f3c86431c665c0b279d9ada37b6be9622096e3 Mon Sep 17 00:00:00 2001 From: fushen Date: Mon, 27 Sep 2021 22:30:20 +0800 Subject: [PATCH 2/7] chore: lint --- packages/platform-loader/src/TraverseImport.js | 2 +- packages/plugin-rax-app/src/setBuild.js | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/packages/platform-loader/src/TraverseImport.js b/packages/platform-loader/src/TraverseImport.js index 6e92cf301..3eff33b1a 100644 --- a/packages/platform-loader/src/TraverseImport.js +++ b/packages/platform-loader/src/TraverseImport.js @@ -20,7 +20,7 @@ module.exports = function traverseImport(options, inputSource, sourceMapOption) 'bytedance-microapp': ['isByteDanceMicroApp'], 'kuaishou-miniprogram': ['isKuaiShouMiniProgram'], 'baidu-smartprogram': ['isBaiduSmartProgram'], - 'harmony': ['isHarmony'], + harmony: ['isHarmony'], }; /** diff --git a/packages/plugin-rax-app/src/setBuild.js b/packages/plugin-rax-app/src/setBuild.js index e76be9a6a..37c5c3d45 100644 --- a/packages/plugin-rax-app/src/setBuild.js +++ b/packages/plugin-rax-app/src/setBuild.js @@ -84,7 +84,6 @@ module.exports = (api) => { ); console.log(); } - } }); }; From 06e1465d2675546b4d33942b5a75a0bc731f2c64 Mon Sep 17 00:00:00 2001 From: fushen Date: Mon, 1 Nov 2021 15:32:43 +0800 Subject: [PATCH 3/7] feat: harmony render --- examples/with-rax-mpa/build.json | 8 ++++--- .../src/components/Logo/index.tsx | 5 +---- .../with-rax-mpa/src/pages/Home/index.css | 22 ++++++++++++------- .../with-rax-mpa/src/pages/Home/index.tsx | 11 +++++----- .../src/userConfig/inlineStyle.js | 5 +++-- packages/plugin-rax-harmony/src/index.js | 1 + 6 files changed, 29 insertions(+), 23 deletions(-) diff --git a/examples/with-rax-mpa/build.json b/examples/with-rax-mpa/build.json index 4c456142c..2ab4a75f3 100644 --- a/examples/with-rax-mpa/build.json +++ b/examples/with-rax-mpa/build.json @@ -1,11 +1,13 @@ { - "targets": ["harmony"], + "targets": ["harmony", "weex"], "harmony": { "mpa": true }, + "weex": { + "mpa": true + }, "minify": false, "experiments": { "exportsField": true - }, - "inlineStyle": true + } } diff --git a/examples/with-rax-mpa/src/components/Logo/index.tsx b/examples/with-rax-mpa/src/components/Logo/index.tsx index 5e911121e..c155515d4 100644 --- a/examples/with-rax-mpa/src/components/Logo/index.tsx +++ b/examples/with-rax-mpa/src/components/Logo/index.tsx @@ -4,14 +4,11 @@ import './index.css'; class Logo extends PureComponent { render() { - const source = { - uri: `${process.env.PUBLIC_URL}/rax.png`, - }; console.log('with router =>', this.props); return ( ); } diff --git a/examples/with-rax-mpa/src/pages/Home/index.css b/examples/with-rax-mpa/src/pages/Home/index.css index ddfdf67f8..419d53f7a 100644 --- a/examples/with-rax-mpa/src/pages/Home/index.css +++ b/examples/with-rax-mpa/src/pages/Home/index.css @@ -1,18 +1,24 @@ .home { - margin-top: 200px; - width: 100px; - height: 100px; - background-color: red; + box-sizing: border-box; + display: flex; + flex-direction: column; + flex-shrink: 0; + align-content: flex-start; + align-items: center; + margin-top: 200rpx; + width: 100%; } .title { - font-size: 35px; + font-size: 35rpx; font-weight: bold; - margin: 20px 0; + margin: 20rpx 0; + display: block; } .info { - font-size: 36px; - margin: 8px 0; + font-size: 36rpx; + margin: 8rpx 0; color: #555; + display: block; } diff --git a/examples/with-rax-mpa/src/pages/Home/index.tsx b/examples/with-rax-mpa/src/pages/Home/index.tsx index 16265778c..394e80a80 100644 --- a/examples/with-rax-mpa/src/pages/Home/index.tsx +++ b/examples/with-rax-mpa/src/pages/Home/index.tsx @@ -1,15 +1,14 @@ import { createElement } from 'rax'; import Logo from '@/components/Logo'; -// @ts-ignore -import styles from './index.css'; +import './index.css'; export default function Home(props) { return ( -
- - Welcome to Your Rax App - More information about Rax +
+ + Welcome to Your Rax App + More information about Rax
); } diff --git a/packages/plugin-rax-app/src/userConfig/inlineStyle.js b/packages/plugin-rax-app/src/userConfig/inlineStyle.js index db3207da2..28f2093f5 100644 --- a/packages/plugin-rax-app/src/userConfig/inlineStyle.js +++ b/packages/plugin-rax-app/src/userConfig/inlineStyle.js @@ -6,11 +6,12 @@ const configPath = resolve(__dirname, '../'); const webStandardList = [ WEB, - HARMONY, ]; const inlineStandardList = [ - WEEX, KRAKEN, + WEEX, + KRAKEN, + HARMONY, ]; const miniappStandardList = [ diff --git a/packages/plugin-rax-harmony/src/index.js b/packages/plugin-rax-harmony/src/index.js index a986670c5..e119bec59 100644 --- a/packages/plugin-rax-harmony/src/index.js +++ b/packages/plugin-rax-harmony/src/index.js @@ -12,6 +12,7 @@ module.exports = (api) => { const target = 'harmony'; const chainConfig = getWebpackBase(api, { target: 'harmony', + babelConfigOptions: { styleSheet: true }, progressOptions: { name: 'Harmony', }, From 840905c69214be24f3820b87e985b5b73b0201d0 Mon Sep 17 00:00:00 2001 From: fushen Date: Mon, 15 Nov 2021 15:35:27 +0800 Subject: [PATCH 4/7] feat: add app worker plugin --- examples/with-rax-mpa/build.json | 4 +- examples/with-rax-mpa/src/app-worker.ts | 5 ++ examples/with-rax-mpa/src/app.json | 4 - .../with-rax-mpa/src/pages/Home/index.tsx | 5 ++ packages/plugin-rax-app/src/base.js | 2 +- packages/plugin-rax-harmony/package.json | 15 ++-- .../src/Loaders/AppWorkerLoader.ts | 48 +++++++++++ .../src/Plugins/RequireModulePlugin.ts | 84 +++++++++++++++++++ .../plugin-rax-harmony/src/addWorkerEntry.ts | 12 +++ packages/plugin-rax-harmony/src/constants.js | 3 - packages/plugin-rax-harmony/src/constants.ts | 6 ++ packages/plugin-rax-harmony/src/index.js | 54 ------------ packages/plugin-rax-harmony/src/index.ts | 79 +++++++++++++++++ packages/plugin-rax-harmony/src/setEntry.js | 29 ------- packages/plugin-rax-harmony/src/setEntry.ts | 23 +++++ .../plugin-rax-harmony/src/types/index.ts | 12 +++ .../src/utils/getFilePath.ts | 9 ++ .../src/utils/getRequireString.ts | 12 +++ .../src/utils/stringifyLoaders.ts | 26 ++++++ packages/plugin-rax-harmony/tsconfig.json | 8 ++ packages/plugin-rax-kraken/src/index.js | 1 - packages/plugin-rax-miniapp/src/index.js | 1 - packages/plugin-rax-web/src/index.ts | 1 - packages/plugin-rax-weex/src/index.js | 1 - packages/rax-app-renderer/src/renderer.tsx | 5 +- .../src/setWebpackLoaders.ts | 4 - tsconfig.json | 1 + 27 files changed, 348 insertions(+), 106 deletions(-) create mode 100644 examples/with-rax-mpa/src/app-worker.ts create mode 100644 packages/plugin-rax-harmony/src/Loaders/AppWorkerLoader.ts create mode 100644 packages/plugin-rax-harmony/src/Plugins/RequireModulePlugin.ts create mode 100644 packages/plugin-rax-harmony/src/addWorkerEntry.ts delete mode 100644 packages/plugin-rax-harmony/src/constants.js create mode 100644 packages/plugin-rax-harmony/src/constants.ts delete mode 100644 packages/plugin-rax-harmony/src/index.js create mode 100644 packages/plugin-rax-harmony/src/index.ts delete mode 100644 packages/plugin-rax-harmony/src/setEntry.js create mode 100644 packages/plugin-rax-harmony/src/setEntry.ts create mode 100644 packages/plugin-rax-harmony/src/types/index.ts create mode 100644 packages/plugin-rax-harmony/src/utils/getFilePath.ts create mode 100644 packages/plugin-rax-harmony/src/utils/getRequireString.ts create mode 100644 packages/plugin-rax-harmony/src/utils/stringifyLoaders.ts create mode 100644 packages/plugin-rax-harmony/tsconfig.json diff --git a/examples/with-rax-mpa/build.json b/examples/with-rax-mpa/build.json index 27d45eec7..d5571ee1d 100644 --- a/examples/with-rax-mpa/build.json +++ b/examples/with-rax-mpa/build.json @@ -6,5 +6,7 @@ "weex": { "mpa": true }, - "minify": false + "minify": false, + "compileDependencies": [], + "webpack5": true } diff --git a/examples/with-rax-mpa/src/app-worker.ts b/examples/with-rax-mpa/src/app-worker.ts new file mode 100644 index 000000000..844159649 --- /dev/null +++ b/examples/with-rax-mpa/src/app-worker.ts @@ -0,0 +1,5 @@ +export default { + onCreate() { + console.info('app created'); + } +} diff --git a/examples/with-rax-mpa/src/app.json b/examples/with-rax-mpa/src/app.json index 88d3d6fed..7796e5b06 100644 --- a/examples/with-rax-mpa/src/app.json +++ b/examples/with-rax-mpa/src/app.json @@ -4,10 +4,6 @@ "name": "home", "source": "pages/Home/index", "spm": "b456" - }, - { - "name": "about", - "source": "pages/About/app" } ], "spm": "a123", diff --git a/examples/with-rax-mpa/src/pages/Home/index.tsx b/examples/with-rax-mpa/src/pages/Home/index.tsx index 394e80a80..b2059d296 100644 --- a/examples/with-rax-mpa/src/pages/Home/index.tsx +++ b/examples/with-rax-mpa/src/pages/Home/index.tsx @@ -3,6 +3,11 @@ import Logo from '@/components/Logo'; import './index.css'; +// @ts-ignore +var a = requireModule('@system/router') + +console.log(a) + export default function Home(props) { return (
diff --git a/packages/plugin-rax-app/src/base.js b/packages/plugin-rax-app/src/base.js index 6ad319217..239d55afc 100644 --- a/packages/plugin-rax-app/src/base.js +++ b/packages/plugin-rax-app/src/base.js @@ -116,7 +116,7 @@ module.exports = (api, { target, babelConfigOptions, progressOptions = {} }) => // Only save target code const keepPlatform = ['ssr', 'document'].includes(target) ? 'node' : target; ['jsx', 'tsx'].forEach((ruleName) => { - enhancedWebpackConfig.module + config.module .rule(ruleName) .use('platform-loader') .loader(require.resolve('rax-platform-loader')) diff --git a/packages/plugin-rax-harmony/package.json b/packages/plugin-rax-harmony/package.json index 397803073..55838d61f 100644 --- a/packages/plugin-rax-harmony/package.json +++ b/packages/plugin-rax-harmony/package.json @@ -6,21 +6,26 @@ "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, + "files": [ + "lib", + "!lib/**/*.map" + ], "keywords": [ "plugin", "rax" ], - "author": "", + "author": "Rax Team", "license": "MIT", "peerDependencies": { - "@alib/build-scripts": "^0.1.0", + "build-scripts": "^1.0.0", "rax": "^1.0.0" }, "dependencies": { - "@builder/mpa-config": "^3.0.0", + "@builder/mpa-config": "^4.0.0", "fs-extra": "^9.0.1", - "webpack-sources": "^2.0.0", "@builder/app-helpers": "^2.1.0", - "react-dev-utils": "^10.0.0" + "react-dev-utils": "^11.0.0", + "loader-utils": "^2.0.0", + "@builder/compat-webpack4": "^1.0.0" } } diff --git a/packages/plugin-rax-harmony/src/Loaders/AppWorkerLoader.ts b/packages/plugin-rax-harmony/src/Loaders/AppWorkerLoader.ts new file mode 100644 index 000000000..07f1fd82a --- /dev/null +++ b/packages/plugin-rax-harmony/src/Loaders/AppWorkerLoader.ts @@ -0,0 +1,48 @@ +import * as loaderUtils from 'loader-utils'; +import { formatPath } from '@builder/app-helpers'; +import { DEVICE_LEVEL } from '../constants'; +import { IAppWorkerLoaderOptions, ILoadAppDefineOptions } from '../types'; + +export default function AppWorkerLoader(code) { + const options: IAppWorkerLoaderOptions = this.getOptions ? this.getOptions() : loaderUtils.getOptions(this); + + return `${loadAppDefine(this, { + ...options, + code, + })}`; +} + +function loadAppDefine(ctx, options: ILoadAppDefineOptions) { + const { appType } = options; + let output = `var $app_script$ = ${getAppScriptAssign(ctx, options)} + `; + + if (appType === DEVICE_LEVEL.RICH) { + output += ` + $app_define$('@app-application/app', [], function(app_require, $app_exports$, $app_module$) { + $app_require$ = app_require; + $app_script$($app_module$, $app_exports$, $app_require$); + if ($app_exports$.__esModule && $app_exports$.default) { + $app_module$.exports = $app_exports$.default; + } + }); + `; + } else if (appType === DEVICE_LEVEL.LITE) { + output += ` + var options=$app_script$; + if ($app_script$.__esModule) { + options = $app_script$.default; + } + module.exports=new ViewModel(options); + `; + } + + return output; +} + +function getAppScriptAssign(ctx, options: ILoadAppDefineOptions) { + return `function(module, exports) { + ${options.code.replace('export default', 'exports.default =')} + exports.manifest = ${JSON.stringify(options.manifest)}; + }`; +} diff --git a/packages/plugin-rax-harmony/src/Plugins/RequireModulePlugin.ts b/packages/plugin-rax-harmony/src/Plugins/RequireModulePlugin.ts new file mode 100644 index 000000000..d8c6d40b3 --- /dev/null +++ b/packages/plugin-rax-harmony/src/Plugins/RequireModulePlugin.ts @@ -0,0 +1,84 @@ +import { processAssets, emitAsset } from '@builder/compat-webpack4'; +import * as webpackSources from 'webpack-sources'; +import * as webpack from 'webpack'; +import { IRequireModulePluginOptions } from '../types'; +import { DEVICE_LEVEL } from '../constants'; + +const PLUGIN_NAME = 'RequireModulePlugin'; +const { RawSource } = webpack.sources || webpackSources; + +const methodForLite = +` +function requireModule(moduleName) { + return requireNative(moduleName.slice(1)); +} +`; +const methodForOthers = +` +let $app_require$; + +function requireModule(moduleName) { + const systemList = ['system.router', 'system.app', 'system.prompt', 'system.configuration', + 'system.image', 'system.device', 'system.mediaquery', 'ohos.animator', 'system.grid', 'system.resource'] + var target = '' + if (systemList.includes(moduleName.replace('@', ''))) { + target = $app_require$('@app-module/' + moduleName.substring(1)); + return target; + } + var shortName = moduleName.replace(/@[^.]+\.([^.]+)/, '$1'); + target = requireNapi(shortName); + if (target !== 'undefined' && /@ohos/.test(moduleName)) { + return target; + } + if (typeof ohosplugin !== 'undefined' && /@ohos/.test(moduleName)) { + target = ohosplugin; + for (let key of shortName.split('.')) { + target = target[key]; + if(!target) { + break; + } + } + if (typeof target !== 'undefined') { + return target; + } + } + if (typeof systemplugin !== 'undefined') { + target = systemplugin; + for (let key of shortName.split('.')) { + target = target[key]; + if(!target) { + break; + } + } + if (typeof target !== 'undefined') { + return target; + } + } + return target; +} +`; + +export default class RequireModulePlugin { + options: IRequireModulePluginOptions = { + appType: 'rich', + }; + constructor(options: IRequireModulePluginOptions) { + this.options = options; + } + apply(compiler) { + processAssets({ + pluginName: PLUGIN_NAME, + compiler, + }, ({ assets, callback, compilation }) => { + const requireMethod = this.options.appType === DEVICE_LEVEL.LITE ? methodForLite : methodForOthers; + Object.keys(assets) + .filter((filename) => /\.js$/.test(filename)) + .forEach((filename) => { + const originalContent = assets[filename].source?.(); + delete assets[filename]; + emitAsset(compilation, filename, new RawSource(`${requireMethod}\n${originalContent}`)); + }); + callback(); + }); + } +} diff --git a/packages/plugin-rax-harmony/src/addWorkerEntry.ts b/packages/plugin-rax-harmony/src/addWorkerEntry.ts new file mode 100644 index 000000000..072406393 --- /dev/null +++ b/packages/plugin-rax-harmony/src/addWorkerEntry.ts @@ -0,0 +1,12 @@ +import * as path from 'path'; +import getFilePath from './utils/getFilePath'; + +export default function addWorkerEntry(config, { rootDir }) { + const workerEntry = getFilePath(path.join(rootDir, 'src/app-worker')); + + if (workerEntry) { + // worker file output name is app.js + const workerEntryConfig = config.entry('app'); + workerEntryConfig.add(workerEntry); + } +} diff --git a/packages/plugin-rax-harmony/src/constants.js b/packages/plugin-rax-harmony/src/constants.js deleted file mode 100644 index f369bad81..000000000 --- a/packages/plugin-rax-harmony/src/constants.js +++ /dev/null @@ -1,3 +0,0 @@ -module.exports = { - GET_RAX_APP_WEBPACK_CONFIG: 'getRaxAppWebpackConfig', -}; diff --git a/packages/plugin-rax-harmony/src/constants.ts b/packages/plugin-rax-harmony/src/constants.ts new file mode 100644 index 000000000..0bb610a9c --- /dev/null +++ b/packages/plugin-rax-harmony/src/constants.ts @@ -0,0 +1,6 @@ +export const GET_RAX_APP_WEBPACK_CONFIG = 'getRaxAppWebpackConfig'; +export const DEVICE_LEVEL = { + RICH: 'rich', + LITE: 'lite', + CARD: 'card', +}; diff --git a/packages/plugin-rax-harmony/src/index.js b/packages/plugin-rax-harmony/src/index.js deleted file mode 100644 index e119bec59..000000000 --- a/packages/plugin-rax-harmony/src/index.js +++ /dev/null @@ -1,54 +0,0 @@ -const setMPAConfig = require('@builder/mpa-config'); -const { getMpaEntries } = require('@builder/app-helpers'); -const setEntry = require('./setEntry'); -const { GET_RAX_APP_WEBPACK_CONFIG } = require('./constants'); - -module.exports = (api) => { - const { getValue, context, registerTask, onGetWebpackConfig, registerUserConfig } = api; - const { userConfig, command } = context; - - const getWebpackBase = getValue(GET_RAX_APP_WEBPACK_CONFIG); - const tempDir = getValue('TEMP_PATH'); - const target = 'harmony'; - const chainConfig = getWebpackBase(api, { - target: 'harmony', - babelConfigOptions: { styleSheet: true }, - progressOptions: { - name: 'Harmony', - }, - }); - chainConfig.taskName = target; - - setEntry(chainConfig, context); - - chainConfig.name(target); - registerTask(target, chainConfig); - registerUserConfig({ - name: target, - validation: 'object', - }); - - onGetWebpackConfig(target, (config) => { - const { harmony = {} } = userConfig; - const staticConfig = getValue('staticConfig'); - // set mpa config - if (harmony.mpa) { - setMPAConfig.default(api, config, { - context, - targetDir: tempDir, - type: 'harmony', - entries: getMpaEntries(api, { - target, - appJsonContent: staticConfig, - }), - }); - } - - if (command === 'start') { - // Add webpack hot dev client - Object.keys(config.entryPoints.entries()).forEach((entryName) => { - config.entry(entryName).prepend(require.resolve('react-dev-utils/webpackHotDevClient')); - }); - } - }); -}; diff --git a/packages/plugin-rax-harmony/src/index.ts b/packages/plugin-rax-harmony/src/index.ts new file mode 100644 index 000000000..3f0fbb9c8 --- /dev/null +++ b/packages/plugin-rax-harmony/src/index.ts @@ -0,0 +1,79 @@ +import * as path from 'path'; +import * as setMPAConfig from '@builder/mpa-config'; +import { getMpaEntries } from '@builder/app-helpers'; +import setEntry from './setEntry'; +import { GET_RAX_APP_WEBPACK_CONFIG } from './constants'; +import RequireModulePlugin from './Plugins/RequireModulePlugin'; +import addWorkerEntry from './addWorkerEntry'; + +export default (api) => { + const { getValue, context, registerTask, onGetWebpackConfig } = api; + const { userConfig, command, rootDir } = context; + + const getWebpackBase = getValue(GET_RAX_APP_WEBPACK_CONFIG); + const tempDir = getValue('TEMP_PATH'); + const target = 'harmony'; + const chainConfig = getWebpackBase(api, { + target: 'harmony', + babelConfigOptions: { styleSheet: true }, + progressOptions: { + name: 'Harmony', + }, + }); + + setEntry(chainConfig, context); + + chainConfig.name(target); + + registerTask(target, chainConfig); + + onGetWebpackConfig(target, (config) => { + const { harmony = {} } = userConfig; + const { mpa, appType = 'rich' } = harmony; + const staticConfig = getValue('staticConfig'); + // set mpa config + if (mpa) { + setMPAConfig.default(api, config, { + targetDir: tempDir, + type: target, + entries: getMpaEntries(api, { + target, + appJsonContent: staticConfig, + }), + }); + + addWorkerEntry(config, { rootDir }); + } + + config.output.merge({ + iife: true, + }); + config.output.devtoolModuleFilenameTemplate('webpack:///[absolute-resource-path]'); + config.devtool('nosources-source-map'); + + config.module + .rule('app-worker') + .test(/src\/app-worker\.(j|t)s$/) + .use('app-worker-loader') + .loader(require.resolve('./Loaders/AppWorkerLoader')) + .options({ + appType, + // TODO: transform staticConfig to manifest.json + // Mock + manifest: '{"appID":"com.example.ace.helloworld","appName":"HelloAce","versionName":"1.0.0","versionCode":1,"minPlatformVersion":"1.0.1","pages":["pages/index/index","pages/detail/detail"],"window":{"designWidth":750,"autoDesignWidth":false}}', + }); + + config.plugin('RequireModulePlugin').use(RequireModulePlugin, [ + { + appType, + }, + ]); + + if (command === 'start') { + // Add webpack hot dev client + Object.keys(config.entryPoints.entries()).forEach((entryName) => { + config.entry(entryName).prepend(require.resolve('react-dev-utils/webpackHotDevClient')); + }); + } + }); +}; diff --git a/packages/plugin-rax-harmony/src/setEntry.js b/packages/plugin-rax-harmony/src/setEntry.js deleted file mode 100644 index 711562972..000000000 --- a/packages/plugin-rax-harmony/src/setEntry.js +++ /dev/null @@ -1,29 +0,0 @@ -const fs = require('fs-extra'); -const path = require('path'); - -module.exports = (config, context) => { - const { - rootDir, - userConfig: { harmony = {} }, - } = context; - - if (!harmony.mpa) { - // SPA - const appEntry = moduleResolve(formatPath(path.join(rootDir, './src/app'))); - const entryConfig = config.entry('index'); - - entryConfig.add(appEntry); - } -}; - -function moduleResolve(filePath) { - const ext = ['.ts', '.js', '.tsx', '.jsx'].find((extension) => fs.existsSync(`${filePath}${extension}`)); - if (!ext) { - throw new Error(`Cannot find target file ${filePath}.`); - } - return require.resolve(`${filePath}${ext}`); -} - -function formatPath(pathStr) { - return process.platform === 'win32' ? pathStr.split(path.sep).join('/') : pathStr; -} diff --git a/packages/plugin-rax-harmony/src/setEntry.ts b/packages/plugin-rax-harmony/src/setEntry.ts new file mode 100644 index 000000000..7b45c098c --- /dev/null +++ b/packages/plugin-rax-harmony/src/setEntry.ts @@ -0,0 +1,23 @@ +import * as path from 'path'; +import addWorkerEntry from './addWorkerEntry'; +import getFilePath from './utils/getFilePath'; + +export default (config, context) => { + const { + rootDir, + userConfig: { harmony = {} }, + } = context; + + if (!harmony.mpa) { + // SPA + const appEntry = getFilePath(path.join(rootDir, './src/app')); + + if (appEntry) { + const entryConfig = config.entry('index'); + entryConfig.add(appEntry); + } + + addWorkerEntry(config, { rootDir }); + } +}; + diff --git a/packages/plugin-rax-harmony/src/types/index.ts b/packages/plugin-rax-harmony/src/types/index.ts new file mode 100644 index 000000000..880793d48 --- /dev/null +++ b/packages/plugin-rax-harmony/src/types/index.ts @@ -0,0 +1,12 @@ +export interface IRequireModulePluginOptions { + appType: string; +} + +export interface IAppWorkerLoaderOptions { + appType: string; + manifest: string; +} + +export interface ILoadAppDefineOptions extends IAppWorkerLoaderOptions { + code: string; +} diff --git a/packages/plugin-rax-harmony/src/utils/getFilePath.ts b/packages/plugin-rax-harmony/src/utils/getFilePath.ts new file mode 100644 index 000000000..d69b4a655 --- /dev/null +++ b/packages/plugin-rax-harmony/src/utils/getFilePath.ts @@ -0,0 +1,9 @@ +import * as fs from 'fs-extra'; + +export default function getFilePath(filePath) { + const ext = ['.ts', '.js', '.tsx', '.jsx'].find((extension) => fs.existsSync(`${filePath}${extension}`)); + if (!ext) { + return; + } + return require.resolve(`${filePath}${ext}`); +} diff --git a/packages/plugin-rax-harmony/src/utils/getRequireString.ts b/packages/plugin-rax-harmony/src/utils/getRequireString.ts new file mode 100644 index 000000000..7886c5be6 --- /dev/null +++ b/packages/plugin-rax-harmony/src/utils/getRequireString.ts @@ -0,0 +1,12 @@ +import * as loaderUtils from 'loader-utils'; + +export default function getRequireString(loaderContext, loader, filepath) { + return `require(${ + loaderUtils.stringifyRequest( + loaderContext, + loader ? + `!!${loader}!${filepath}` : + `${filepath}`, + ) + })\n`; +} diff --git a/packages/plugin-rax-harmony/src/utils/stringifyLoaders.ts b/packages/plugin-rax-harmony/src/utils/stringifyLoaders.ts new file mode 100644 index 000000000..42a6c74bf --- /dev/null +++ b/packages/plugin-rax-harmony/src/utils/stringifyLoaders.ts @@ -0,0 +1,26 @@ +export default function stringifyLoaders(loaders) { + return loaders.map((loader) => { + if (typeof loader === 'string') { + return loader; + } else { + const { name } = loader; + const query = []; + if (loader.query) { + // eslint-disable-next-line guard-for-in + for (const k in loader.query) { + const v = loader.query[k]; + if (v != null) { + if (v === true) { + query.push(k); + } else if (v instanceof Array) { + query.push(`${k}[]=${v.join(',')}`); + } else { + query.push(`${k}=${v}`); + } + } + } + } + return `${name}${query.length ? (`?${ query.join('&')}`) : ''}`; + } + }).join('!'); +} diff --git a/packages/plugin-rax-harmony/tsconfig.json b/packages/plugin-rax-harmony/tsconfig.json new file mode 100644 index 000000000..1ba6ca74d --- /dev/null +++ b/packages/plugin-rax-harmony/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../../tsconfig.settings.json", + "compilerOptions": { + "baseUrl": "./", + "rootDir": "src", + "outDir": "lib" + }, +} diff --git a/packages/plugin-rax-kraken/src/index.js b/packages/plugin-rax-kraken/src/index.js index 06e785e0d..1cb67b098 100644 --- a/packages/plugin-rax-kraken/src/index.js +++ b/packages/plugin-rax-kraken/src/index.js @@ -17,7 +17,6 @@ module.exports = (api) => { }, }); chainConfig.name(target); - chainConfig.taskName = target; setEntry(chainConfig, context); diff --git a/packages/plugin-rax-miniapp/src/index.js b/packages/plugin-rax-miniapp/src/index.js index c82129f5e..32acfc5fe 100644 --- a/packages/plugin-rax-miniapp/src/index.js +++ b/packages/plugin-rax-miniapp/src/index.js @@ -38,7 +38,6 @@ module.exports = (api) => { }, }); chainConfig.name(target); - chainConfig.taskName = target; // Register task registerTask(target, chainConfig); diff --git a/packages/plugin-rax-web/src/index.ts b/packages/plugin-rax-web/src/index.ts index 0f3de4220..8bc1c4f01 100644 --- a/packages/plugin-rax-web/src/index.ts +++ b/packages/plugin-rax-web/src/index.ts @@ -30,7 +30,6 @@ export default (api) => { }, }); chainConfig.name(target); - chainConfig.taskName = target; // Set Entry setEntry(chainConfig, context); diff --git a/packages/plugin-rax-weex/src/index.js b/packages/plugin-rax-weex/src/index.js index 4bfd0115d..7eb6f0fc2 100644 --- a/packages/plugin-rax-weex/src/index.js +++ b/packages/plugin-rax-weex/src/index.js @@ -33,7 +33,6 @@ module.exports = (api) => { // set mpa config if (weex.mpa) { setMPAConfig.default(api, config, { - context, targetDir: tempDir, type: 'weex', entries: getMpaEntries(api, { diff --git a/packages/rax-app-renderer/src/renderer.tsx b/packages/rax-app-renderer/src/renderer.tsx index f8ac0b1e3..78edeabbd 100644 --- a/packages/rax-app-renderer/src/renderer.tsx +++ b/packages/rax-app-renderer/src/renderer.tsx @@ -7,6 +7,9 @@ import { setInitialData } from './initialData'; import parseSearch from './parseSearch'; import type { RuntimeModule } from 'create-app-shared'; +//@ts-ignore +const isHarmony = typeof ace !== 'undefined'; + let driver = UniversalDriver; async function raxAppRenderer(options) { @@ -72,7 +75,7 @@ function _render(runtime: RuntimeModule, context: IContext, options: RenderOptio } function _getAppMountNode(mountNode: HTMLElement, rootId: string) { - if (isWeex || isKraken) return null; + if (isWeex || isKraken || isHarmony) return null; return mountNode || document.getElementById(rootId) || document.getElementById('root'); } diff --git a/packages/rax-webpack-config/src/setWebpackLoaders.ts b/packages/rax-webpack-config/src/setWebpackLoaders.ts index 520746c8d..fda2fe2dd 100644 --- a/packages/rax-webpack-config/src/setWebpackLoaders.ts +++ b/packages/rax-webpack-config/src/setWebpackLoaders.ts @@ -131,10 +131,6 @@ export default (config, { rootDir, babelConfig }: IOptions) => { if (request.indexOf('@weex-module') !== -1) { return callback(null, `commonjs ${request}`); } - // compatible with @system for quickapp - if (request.indexOf('@system') !== -1) { - return callback(null, `commonjs ${request}`); - } // compatible with plugin with miniapp plugin if (/^plugin\:\/\//.test(request)) { return callback(null, `commonjs ${request}`); diff --git a/tsconfig.json b/tsconfig.json index 4c00f1035..8c751df10 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -10,6 +10,7 @@ { "path": "packages/rax-app-renderer" }, { "path": "packages/exports-field-webpack-plugin" }, { "path": "packages/plugin-rax-router" }, + { "path": "packages/plugin-rax-harmony" }, { "path": "packages/plugin-rax-app" }, { "path": "packages/plugin-rax-web" }, { "path": "packages/plugin-rax-miniapp" }, From 714553eef385acd2f2193c16730de2c66768f504 Mon Sep 17 00:00:00 2001 From: fushen Date: Wed, 24 Nov 2021 00:40:13 +0800 Subject: [PATCH 5/7] feat: support page build --- examples/with-rax-mpa/build.json | 5 +- .../with-rax-mpa/src/pages/Home/index.tsx | 4 +- .../src/BundleShellPlugin/LiteShell.ts | 17 ++++ .../src/BundleShellPlugin/RichShell.ts | 90 +++++++++++++++++++ .../src/BundleShellPlugin/Shell.ts | 31 +++++++ .../src/BundleShellPlugin/index.ts | 72 +++++++++++++++ .../src/Loaders/AppWorkerLoader.ts | 48 ---------- .../src/Plugins/RequireModulePlugin.ts | 84 ----------------- packages/plugin-rax-harmony/src/index.ts | 68 ++++++++------ packages/plugin-rax-harmony/src/setEntry.ts | 23 ----- .../plugin-rax-harmony/src/setupAppEntry.ts | 22 +++++ .../plugin-rax-harmony/src/types/index.ts | 14 +-- .../src/utils/getManifest.ts | 22 +++++ .../src/utils/getPageName.ts | 3 + .../src/utils/getRequireString.ts | 12 --- .../src/utils/stringifyLoaders.ts | 26 ------ 16 files changed, 306 insertions(+), 235 deletions(-) create mode 100644 packages/plugin-rax-harmony/src/BundleShellPlugin/LiteShell.ts create mode 100644 packages/plugin-rax-harmony/src/BundleShellPlugin/RichShell.ts create mode 100644 packages/plugin-rax-harmony/src/BundleShellPlugin/Shell.ts create mode 100644 packages/plugin-rax-harmony/src/BundleShellPlugin/index.ts delete mode 100644 packages/plugin-rax-harmony/src/Loaders/AppWorkerLoader.ts delete mode 100644 packages/plugin-rax-harmony/src/Plugins/RequireModulePlugin.ts delete mode 100644 packages/plugin-rax-harmony/src/setEntry.ts create mode 100644 packages/plugin-rax-harmony/src/setupAppEntry.ts create mode 100644 packages/plugin-rax-harmony/src/utils/getManifest.ts create mode 100644 packages/plugin-rax-harmony/src/utils/getPageName.ts delete mode 100644 packages/plugin-rax-harmony/src/utils/getRequireString.ts delete mode 100644 packages/plugin-rax-harmony/src/utils/stringifyLoaders.ts diff --git a/examples/with-rax-mpa/build.json b/examples/with-rax-mpa/build.json index d5571ee1d..54274f427 100644 --- a/examples/with-rax-mpa/build.json +++ b/examples/with-rax-mpa/build.json @@ -1,11 +1,8 @@ { - "targets": ["harmony", "weex"], + "targets": ["harmony"], "harmony": { "mpa": true }, - "weex": { - "mpa": true - }, "minify": false, "compileDependencies": [], "webpack5": true diff --git a/examples/with-rax-mpa/src/pages/Home/index.tsx b/examples/with-rax-mpa/src/pages/Home/index.tsx index b2059d296..781ef3a32 100644 --- a/examples/with-rax-mpa/src/pages/Home/index.tsx +++ b/examples/with-rax-mpa/src/pages/Home/index.tsx @@ -3,10 +3,8 @@ import Logo from '@/components/Logo'; import './index.css'; -// @ts-ignore -var a = requireModule('@system/router') -console.log(a) +console.log(11111); export default function Home(props) { return ( diff --git a/packages/plugin-rax-harmony/src/BundleShellPlugin/LiteShell.ts b/packages/plugin-rax-harmony/src/BundleShellPlugin/LiteShell.ts new file mode 100644 index 000000000..5f5acf5fd --- /dev/null +++ b/packages/plugin-rax-harmony/src/BundleShellPlugin/LiteShell.ts @@ -0,0 +1,17 @@ +import BaseShell from './Shell'; + +const requireModuleMethod = ` +function requireModule(moduleName) { + return requireNative(moduleName.slice(1)); +} +`; + +export default class LiteShell extends BaseShell { + generateApp() { + return `${requireModuleMethod} + var options = ${this.content}; + + new ViewModule(options); + `; + } +} diff --git a/packages/plugin-rax-harmony/src/BundleShellPlugin/RichShell.ts b/packages/plugin-rax-harmony/src/BundleShellPlugin/RichShell.ts new file mode 100644 index 000000000..a841cad28 --- /dev/null +++ b/packages/plugin-rax-harmony/src/BundleShellPlugin/RichShell.ts @@ -0,0 +1,90 @@ +import getPageName from '../utils/getPageName'; +import BaseShell from './Shell'; + +const requireModuleMethod = ` +function requireModule(moduleName) { + const systemList = ['system.router', 'system.app', 'system.prompt', 'system.configuration', + 'system.image', 'system.device', 'system.mediaquery', 'ohos.animator', 'system.grid', 'system.resource'] + var target = '' + if (systemList.includes(moduleName.replace('@', ''))) { + target = $app_require$('@app-module/' + moduleName.substring(1)); + return target; + } + var shortName = moduleName.replace(/@[^.]+\.([^.]+)/, '$1'); + target = requireNapi(shortName); + if (target !== 'undefined' && /@ohos/.test(moduleName)) { + return target; + } + if (typeof ohosplugin !== 'undefined' && /@ohos/.test(moduleName)) { + target = ohosplugin; + for (let key of shortName.split('.')) { + target = target[key]; + if(!target) { + break; + } + } + if (typeof target !== 'undefined') { + return target; + } + } + if (typeof systemplugin !== 'undefined') { + target = systemplugin; + for (let key of shortName.split('.')) { + target = target[key]; + if(!target) { + break; + } + } + if (typeof target !== 'undefined') { + return target; + } + } + return target; +} +`; + +export default class RichShell extends BaseShell { + generateApp() { + return ` + $app_define$('@app-application/app', [], function($app_require$, $app_exports$, $app_module$) { + ${requireModuleMethod} + + ${this.content}; + + $app_exports$.default = result.default; + $app_exports$.manifest = ${JSON.stringify(this.pluginOptions.manifest)}; + $app_module$.exports = $app_exports$.default; + + $app_bootstrap$('@app-application/app', undefined, undefined) + }); + `; + } + + generatePage() { + const pageName = getPageName(this.options.filename); + return ` + $app_define$('@app-component/${pageName}', [], function($app_require$, $app_exports$, $app_module$) { + ${requireModuleMethod} + + $app_exports$.default = { + onReady() { + var document = this.app.doc; + document.body.__rendered = true; + ${this.content} + } + }; + + $app_module$.exports = $app_exports$.default; + + $app_module$.exports.template = { + type: 'div', + children: [], + }; + + $app_module$.exports.style = {}; + + $app_bootstrap$('@app-component/${pageName}', undefined, undefined) + }); + `; + } +} diff --git a/packages/plugin-rax-harmony/src/BundleShellPlugin/Shell.ts b/packages/plugin-rax-harmony/src/BundleShellPlugin/Shell.ts new file mode 100644 index 000000000..824579d4a --- /dev/null +++ b/packages/plugin-rax-harmony/src/BundleShellPlugin/Shell.ts @@ -0,0 +1,31 @@ +import type { IBundleShellPluginOptions, IShellOptions } from '../types'; + +export default class BaseShell { + content: string; + pluginOptions: IBundleShellPluginOptions; + options: IShellOptions; + isPageFile: boolean; + constructor(content: string, pluginOptions: IBundleShellPluginOptions, options: IShellOptions) { + this.content = content; + this.pluginOptions = pluginOptions; + this.options = options; + + this.isPageFile = options.filename !== 'app.js'; + } + + generate(): string { + // In harmony app, app.js is different from page js file + if (this.isPageFile) return this.generatePage(); + return this.generateApp(); + } + + generatePage(): string { + // Default return + return this.content; + } + + generateApp(): string { + // Default return + return this.content; + } +} diff --git a/packages/plugin-rax-harmony/src/BundleShellPlugin/index.ts b/packages/plugin-rax-harmony/src/BundleShellPlugin/index.ts new file mode 100644 index 000000000..066fbcc28 --- /dev/null +++ b/packages/plugin-rax-harmony/src/BundleShellPlugin/index.ts @@ -0,0 +1,72 @@ +import { processAssets, emitAsset } from '@builder/compat-webpack4'; +import * as webpackSources from 'webpack-sources'; +import * as webpack from 'webpack'; +import { IBundleShellPluginOptions } from '../types'; +import { DEVICE_LEVEL } from '../constants'; +import LiteShell from './LiteShell'; +import RichShell from './RichShell'; +import getPageName from '../utils/getPageName'; + +const PLUGIN_NAME = 'BundleShell'; +const { RawSource } = webpack.sources || webpackSources; + + +export default class BundleShell { + pluginOptions: IBundleShellPluginOptions = { + appType: 'rich', + manifest: {}, + }; + options: any; + constructor(options: IBundleShellPluginOptions) { + this.pluginOptions = options; + } + apply(compiler) { + processAssets({ + pluginName: PLUGIN_NAME, + compiler, + }, ({ assets, callback, compilation }) => { + Object.keys(assets) + .forEach((filename) => { + let outputFileName = filename.replace(/\.js$/, ''); + if (!/^app\.js(\.map)?$/.test(filename)) { + outputFileName = `pages/${getPageName(filename)}`; + } + if (/\.js$/.test(filename)) { + transformJSFile(filename, { compilation, assets, pluginOptions: this.pluginOptions, outputFileName: `${outputFileName}.js` }); + } + + if (/\.js\.map$/.test(filename)) { + moveMapFile(filename, { compilation, assets, outputFileName: `${outputFileName}.js.map` }); + } + }); + + // Generate manifest.json + emitAsset(compilation, 'manifest.json', + new RawSource( + JSON.stringify(this.pluginOptions.manifest, null, compiler.options.mode === 'production' ? 0 : 2), + )); + callback(); + }); + } +} + +function transformJSFile(filename: string, { compilation, assets, pluginOptions, outputFileName }) { + const originalContent = assets[filename].source?.(); + delete assets[filename]; + + const shellOptions = { + filename, + }; + const shell = pluginOptions.appType === DEVICE_LEVEL.LITE + ? new LiteShell(originalContent, pluginOptions, shellOptions) + : new RichShell(originalContent, pluginOptions, shellOptions); + + emitAsset(compilation, outputFileName, new RawSource(shell.generate())); +} + +function moveMapFile(filename: string, { compilation, assets, outputFileName }) { + const originalContent = assets[filename]; + delete assets[filename]; + + emitAsset(compilation, outputFileName, originalContent); +} diff --git a/packages/plugin-rax-harmony/src/Loaders/AppWorkerLoader.ts b/packages/plugin-rax-harmony/src/Loaders/AppWorkerLoader.ts deleted file mode 100644 index 07f1fd82a..000000000 --- a/packages/plugin-rax-harmony/src/Loaders/AppWorkerLoader.ts +++ /dev/null @@ -1,48 +0,0 @@ -import * as loaderUtils from 'loader-utils'; -import { formatPath } from '@builder/app-helpers'; -import { DEVICE_LEVEL } from '../constants'; -import { IAppWorkerLoaderOptions, ILoadAppDefineOptions } from '../types'; - -export default function AppWorkerLoader(code) { - const options: IAppWorkerLoaderOptions = this.getOptions ? this.getOptions() : loaderUtils.getOptions(this); - - return `${loadAppDefine(this, { - ...options, - code, - })}`; -} - -function loadAppDefine(ctx, options: ILoadAppDefineOptions) { - const { appType } = options; - let output = `var $app_script$ = ${getAppScriptAssign(ctx, options)} - `; - - if (appType === DEVICE_LEVEL.RICH) { - output += ` - $app_define$('@app-application/app', [], function(app_require, $app_exports$, $app_module$) { - $app_require$ = app_require; - $app_script$($app_module$, $app_exports$, $app_require$); - if ($app_exports$.__esModule && $app_exports$.default) { - $app_module$.exports = $app_exports$.default; - } - }); - `; - } else if (appType === DEVICE_LEVEL.LITE) { - output += ` - var options=$app_script$; - if ($app_script$.__esModule) { - options = $app_script$.default; - } - module.exports=new ViewModel(options); - `; - } - - return output; -} - -function getAppScriptAssign(ctx, options: ILoadAppDefineOptions) { - return `function(module, exports) { - ${options.code.replace('export default', 'exports.default =')} - exports.manifest = ${JSON.stringify(options.manifest)}; - }`; -} diff --git a/packages/plugin-rax-harmony/src/Plugins/RequireModulePlugin.ts b/packages/plugin-rax-harmony/src/Plugins/RequireModulePlugin.ts deleted file mode 100644 index d8c6d40b3..000000000 --- a/packages/plugin-rax-harmony/src/Plugins/RequireModulePlugin.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { processAssets, emitAsset } from '@builder/compat-webpack4'; -import * as webpackSources from 'webpack-sources'; -import * as webpack from 'webpack'; -import { IRequireModulePluginOptions } from '../types'; -import { DEVICE_LEVEL } from '../constants'; - -const PLUGIN_NAME = 'RequireModulePlugin'; -const { RawSource } = webpack.sources || webpackSources; - -const methodForLite = -` -function requireModule(moduleName) { - return requireNative(moduleName.slice(1)); -} -`; -const methodForOthers = -` -let $app_require$; - -function requireModule(moduleName) { - const systemList = ['system.router', 'system.app', 'system.prompt', 'system.configuration', - 'system.image', 'system.device', 'system.mediaquery', 'ohos.animator', 'system.grid', 'system.resource'] - var target = '' - if (systemList.includes(moduleName.replace('@', ''))) { - target = $app_require$('@app-module/' + moduleName.substring(1)); - return target; - } - var shortName = moduleName.replace(/@[^.]+\.([^.]+)/, '$1'); - target = requireNapi(shortName); - if (target !== 'undefined' && /@ohos/.test(moduleName)) { - return target; - } - if (typeof ohosplugin !== 'undefined' && /@ohos/.test(moduleName)) { - target = ohosplugin; - for (let key of shortName.split('.')) { - target = target[key]; - if(!target) { - break; - } - } - if (typeof target !== 'undefined') { - return target; - } - } - if (typeof systemplugin !== 'undefined') { - target = systemplugin; - for (let key of shortName.split('.')) { - target = target[key]; - if(!target) { - break; - } - } - if (typeof target !== 'undefined') { - return target; - } - } - return target; -} -`; - -export default class RequireModulePlugin { - options: IRequireModulePluginOptions = { - appType: 'rich', - }; - constructor(options: IRequireModulePluginOptions) { - this.options = options; - } - apply(compiler) { - processAssets({ - pluginName: PLUGIN_NAME, - compiler, - }, ({ assets, callback, compilation }) => { - const requireMethod = this.options.appType === DEVICE_LEVEL.LITE ? methodForLite : methodForOthers; - Object.keys(assets) - .filter((filename) => /\.js$/.test(filename)) - .forEach((filename) => { - const originalContent = assets[filename].source?.(); - delete assets[filename]; - emitAsset(compilation, filename, new RawSource(`${requireMethod}\n${originalContent}`)); - }); - callback(); - }); - } -} diff --git a/packages/plugin-rax-harmony/src/index.ts b/packages/plugin-rax-harmony/src/index.ts index 3f0fbb9c8..feb0e3897 100644 --- a/packages/plugin-rax-harmony/src/index.ts +++ b/packages/plugin-rax-harmony/src/index.ts @@ -1,10 +1,18 @@ -import * as path from 'path'; import * as setMPAConfig from '@builder/mpa-config'; import { getMpaEntries } from '@builder/app-helpers'; -import setEntry from './setEntry'; +import setEntry from './setupAppEntry'; import { GET_RAX_APP_WEBPACK_CONFIG } from './constants'; -import RequireModulePlugin from './Plugins/RequireModulePlugin'; +import BundleShellPlugin from './BundleShellPlugin'; import addWorkerEntry from './addWorkerEntry'; +import type { IBundleShellPluginOptions } from './types'; +import { isWebpack4 } from '@builder/compat-webpack4'; +import getManifest from './utils/getManifest'; +import setupAppEntry from './setupAppEntry'; + +/* +TODO: +- 鸿蒙应用 vendors 为 false,不可配置 + */ export default (api) => { const { getValue, context, registerTask, onGetWebpackConfig } = api; @@ -21,7 +29,7 @@ export default (api) => { }, }); - setEntry(chainConfig, context); + let entries = [setupAppEntry(chainConfig, context)]; chainConfig.name(target); @@ -31,43 +39,45 @@ export default (api) => { const { harmony = {} } = userConfig; const { mpa, appType = 'rich' } = harmony; const staticConfig = getValue('staticConfig'); + + // base config + if (isWebpack4) { + config.output.libraryTarget('var'); + config.output.libraryExport('result'); + } else { + config.output.merge({ + library: { + name: 'result', + type: 'var', + }, + }); + } + // set mpa config if (mpa) { + entries = getMpaEntries(api, { + target, + appJsonContent: staticConfig, + }); + setMPAConfig.default(api, config, { targetDir: tempDir, type: target, - entries: getMpaEntries(api, { - target, - appJsonContent: staticConfig, - }), + entries, }); - - addWorkerEntry(config, { rootDir }); } - config.output.merge({ - iife: true, - }); + addWorkerEntry(config, { rootDir }); + config.output.devtoolModuleFilenameTemplate('webpack:///[absolute-resource-path]'); config.devtool('nosources-source-map'); - config.module - .rule('app-worker') - .test(/src\/app-worker\.(j|t)s$/) - .use('app-worker-loader') - .loader(require.resolve('./Loaders/AppWorkerLoader')) - .options({ - appType, - // TODO: transform staticConfig to manifest.json - // Mock - manifest: '{"appID":"com.example.ace.helloworld","appName":"HelloAce","versionName":"1.0.0","versionCode":1,"minPlatformVersion":"1.0.1","pages":["pages/index/index","pages/detail/detail"],"window":{"designWidth":750,"autoDesignWidth":false}}', - }); + const bundleShellPluginOptions: IBundleShellPluginOptions = { + appType, + manifest: getManifest(entries, { staticConfig, nativeConfig: harmony.nativeConfig }), + }; - config.plugin('RequireModulePlugin').use(RequireModulePlugin, [ - { - appType, - }, - ]); + config.plugin('BundleShellPlugin').use(BundleShellPlugin, [bundleShellPluginOptions]); if (command === 'start') { // Add webpack hot dev client diff --git a/packages/plugin-rax-harmony/src/setEntry.ts b/packages/plugin-rax-harmony/src/setEntry.ts deleted file mode 100644 index 7b45c098c..000000000 --- a/packages/plugin-rax-harmony/src/setEntry.ts +++ /dev/null @@ -1,23 +0,0 @@ -import * as path from 'path'; -import addWorkerEntry from './addWorkerEntry'; -import getFilePath from './utils/getFilePath'; - -export default (config, context) => { - const { - rootDir, - userConfig: { harmony = {} }, - } = context; - - if (!harmony.mpa) { - // SPA - const appEntry = getFilePath(path.join(rootDir, './src/app')); - - if (appEntry) { - const entryConfig = config.entry('index'); - entryConfig.add(appEntry); - } - - addWorkerEntry(config, { rootDir }); - } -}; - diff --git a/packages/plugin-rax-harmony/src/setupAppEntry.ts b/packages/plugin-rax-harmony/src/setupAppEntry.ts new file mode 100644 index 000000000..790662f77 --- /dev/null +++ b/packages/plugin-rax-harmony/src/setupAppEntry.ts @@ -0,0 +1,22 @@ +import * as path from 'path'; +import getFilePath from './utils/getFilePath'; + +export default (config, context) => { + const { + rootDir, + } = context; + + // SPA + const appEntry = getFilePath(path.join(rootDir, './src/app')); + + if (appEntry) { + const entryConfig = config.entry('index'); + entryConfig.add(appEntry); + } + + return { + entryName: 'index', + entryPath: appEntry, + }; +}; + diff --git a/packages/plugin-rax-harmony/src/types/index.ts b/packages/plugin-rax-harmony/src/types/index.ts index 880793d48..eaad80bc2 100644 --- a/packages/plugin-rax-harmony/src/types/index.ts +++ b/packages/plugin-rax-harmony/src/types/index.ts @@ -1,12 +1,14 @@ -export interface IRequireModulePluginOptions { +export interface IBundleShellPluginOptions { appType: string; + manifest: IManifest; } -export interface IAppWorkerLoaderOptions { - appType: string; - manifest: string; +export interface IManifest { + appID?: string; + pages?: string[]; + [key: string]: unknown; } -export interface ILoadAppDefineOptions extends IAppWorkerLoaderOptions { - code: string; +export interface IShellOptions { + filename: string; } diff --git a/packages/plugin-rax-harmony/src/utils/getManifest.ts b/packages/plugin-rax-harmony/src/utils/getManifest.ts new file mode 100644 index 000000000..91f3b9a98 --- /dev/null +++ b/packages/plugin-rax-harmony/src/utils/getManifest.ts @@ -0,0 +1,22 @@ +import { merge } from '@builder/pack/deps/lodash'; +import type { IManifest } from '../types'; + +const DEFAULT_MANIFEST = { + appID: 'com.example.ace.helloworld', + appName: 'HelloAce', + versionName: '1.0.0', + versionCode: 1, + minPlatformVersion: '1.0.1', + window: { + designWidth: 750, autoDesignWidth: false, + }, +}; + +export default function getManifest(entries, { staticConfig, nativeConfig }): IManifest { + const manifest: IManifest = { + pages: entries.map(({ entryName }) => `pages/${entryName}`), + window: staticConfig.window, + }; + + return merge(DEFAULT_MANIFEST, manifest, nativeConfig); +} diff --git a/packages/plugin-rax-harmony/src/utils/getPageName.ts b/packages/plugin-rax-harmony/src/utils/getPageName.ts new file mode 100644 index 000000000..6cfa34ec3 --- /dev/null +++ b/packages/plugin-rax-harmony/src/utils/getPageName.ts @@ -0,0 +1,3 @@ +export default function getPageName(filename: string) { + return filename.split('.')[0]; +} diff --git a/packages/plugin-rax-harmony/src/utils/getRequireString.ts b/packages/plugin-rax-harmony/src/utils/getRequireString.ts deleted file mode 100644 index 7886c5be6..000000000 --- a/packages/plugin-rax-harmony/src/utils/getRequireString.ts +++ /dev/null @@ -1,12 +0,0 @@ -import * as loaderUtils from 'loader-utils'; - -export default function getRequireString(loaderContext, loader, filepath) { - return `require(${ - loaderUtils.stringifyRequest( - loaderContext, - loader ? - `!!${loader}!${filepath}` : - `${filepath}`, - ) - })\n`; -} diff --git a/packages/plugin-rax-harmony/src/utils/stringifyLoaders.ts b/packages/plugin-rax-harmony/src/utils/stringifyLoaders.ts deleted file mode 100644 index 42a6c74bf..000000000 --- a/packages/plugin-rax-harmony/src/utils/stringifyLoaders.ts +++ /dev/null @@ -1,26 +0,0 @@ -export default function stringifyLoaders(loaders) { - return loaders.map((loader) => { - if (typeof loader === 'string') { - return loader; - } else { - const { name } = loader; - const query = []; - if (loader.query) { - // eslint-disable-next-line guard-for-in - for (const k in loader.query) { - const v = loader.query[k]; - if (v != null) { - if (v === true) { - query.push(k); - } else if (v instanceof Array) { - query.push(`${k}[]=${v.join(',')}`); - } else { - query.push(`${k}=${v}`); - } - } - } - } - return `${name}${query.length ? (`?${ query.join('&')}`) : ''}`; - } - }).join('!'); -} From 20d7efafbb02aabc0019b655b434eb967f4dc6a2 Mon Sep 17 00:00:00 2001 From: fushen Date: Wed, 24 Nov 2021 00:40:56 +0800 Subject: [PATCH 6/7] feat: support page build --- packages/plugin-rax-harmony/src/index.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/plugin-rax-harmony/src/index.ts b/packages/plugin-rax-harmony/src/index.ts index feb0e3897..24c76d807 100644 --- a/packages/plugin-rax-harmony/src/index.ts +++ b/packages/plugin-rax-harmony/src/index.ts @@ -1,6 +1,5 @@ import * as setMPAConfig from '@builder/mpa-config'; import { getMpaEntries } from '@builder/app-helpers'; -import setEntry from './setupAppEntry'; import { GET_RAX_APP_WEBPACK_CONFIG } from './constants'; import BundleShellPlugin from './BundleShellPlugin'; import addWorkerEntry from './addWorkerEntry'; From b7fc05b492ae13e14aacc1d95991b3f1cf9ab982 Mon Sep 17 00:00:00 2001 From: fushen Date: Thu, 25 Nov 2021 14:38:51 +0800 Subject: [PATCH 7/7] fix: app bootstrap --- .../with-rax-mpa/src/pages/Home/index.tsx | 3 --- .../src/BundleShellPlugin/RichShell.ts | 8 +++---- .../plugin-rax-harmony/src/setupAppEntry.ts | 1 - packages/rax-app-renderer/src/renderer.tsx | 24 ++++++++++--------- 4 files changed, 17 insertions(+), 19 deletions(-) diff --git a/examples/with-rax-mpa/src/pages/Home/index.tsx b/examples/with-rax-mpa/src/pages/Home/index.tsx index 781ef3a32..394e80a80 100644 --- a/examples/with-rax-mpa/src/pages/Home/index.tsx +++ b/examples/with-rax-mpa/src/pages/Home/index.tsx @@ -3,9 +3,6 @@ import Logo from '@/components/Logo'; import './index.css'; - -console.log(11111); - export default function Home(props) { return (
diff --git a/packages/plugin-rax-harmony/src/BundleShellPlugin/RichShell.ts b/packages/plugin-rax-harmony/src/BundleShellPlugin/RichShell.ts index a841cad28..96f622a08 100644 --- a/packages/plugin-rax-harmony/src/BundleShellPlugin/RichShell.ts +++ b/packages/plugin-rax-harmony/src/BundleShellPlugin/RichShell.ts @@ -54,9 +54,9 @@ export default class RichShell extends BaseShell { $app_exports$.default = result.default; $app_exports$.manifest = ${JSON.stringify(this.pluginOptions.manifest)}; $app_module$.exports = $app_exports$.default; - - $app_bootstrap$('@app-application/app', undefined, undefined) }); + + $app_bootstrap$('@app-application/app', undefined, undefined); `; } @@ -82,9 +82,9 @@ export default class RichShell extends BaseShell { }; $app_module$.exports.style = {}; - - $app_bootstrap$('@app-component/${pageName}', undefined, undefined) }); + + $app_bootstrap$('@app-component/${pageName}', undefined, undefined); `; } } diff --git a/packages/plugin-rax-harmony/src/setupAppEntry.ts b/packages/plugin-rax-harmony/src/setupAppEntry.ts index 790662f77..6c2d6353e 100644 --- a/packages/plugin-rax-harmony/src/setupAppEntry.ts +++ b/packages/plugin-rax-harmony/src/setupAppEntry.ts @@ -19,4 +19,3 @@ export default (config, context) => { entryPath: appEntry, }; }; - diff --git a/packages/rax-app-renderer/src/renderer.tsx b/packages/rax-app-renderer/src/renderer.tsx index 78edeabbd..f59709896 100644 --- a/packages/rax-app-renderer/src/renderer.tsx +++ b/packages/rax-app-renderer/src/renderer.tsx @@ -22,17 +22,19 @@ async function raxAppRenderer(options) { const context: IContext = {}; // ssr enabled and the server has returned data - if ((window as any)?.__INITIAL_DATA__) { - context.initialData = (window as any).__INITIAL_DATA__.initialData; - context.pageInitialProps = (window as any).__INITIAL_DATA__.pageInitialProps; - } else if (isWeb && appConfig?.app?.getInitialData) { - const { pathname, search } = window.location; - const query = parseSearch(search); - const initialContext = { - pathname, - query, - }; - context.initialData = await appConfig.app.getInitialData(initialContext); + if (isWeb) { + if ((window as any).__INITIAL_DATA__) { + context.initialData = (window as any).__INITIAL_DATA__.initialData; + context.pageInitialProps = (window as any).__INITIAL_DATA__.pageInitialProps; + } else if (appConfig?.app?.getInitialData) { + const { pathname, search } = window.location; + const query = parseSearch(search); + const initialContext = { + pathname, + query, + }; + context.initialData = await appConfig.app.getInitialData(initialContext); + } } setInitialData(context.initialData);