Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

chore: optimize bundle size #3750

Merged
merged 4 commits into from
Nov 2, 2020
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions examples/with-rax-lite/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# with rax
Copy link
Collaborator

Choose a reason for hiding this comment

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

后面可能需要考虑一下示例的维护和测试问题,需要有个策略,防止无限制的增加示例带来的冗余。


https://github.com/ice-lab/icejs/tree/master/examples
4 changes: 4 additions & 0 deletions examples/with-rax-lite/build.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"targets": ["web"],
"inlineStyle": true
}
22 changes: 22 additions & 0 deletions examples/with-rax-lite/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"name": "with-rax",
"description": "rax example",
"dependencies": {
"rax": "^1.1.0",
"rax-document": "^0.1.0",
"rax-image": "^2.0.0",
"rax-link": "^1.0.1",
"rax-text": "^1.0.0",
"rax-view": "^1.0.0"
},
"devDependencies": {
"@types/rax": "^1.0.0"
},
"scripts": {
"start": "rax-app start",
"build": "rax-app build"
},
"engines": {
"node": ">=8.0.0"
}
}
15 changes: 15 additions & 0 deletions examples/with-rax-lite/src/app.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"routes": [
{
"path": "/",
"source": "pages/Home/index"
},
{
"path": "/about",
"source": "pages/About/index"
}
],
"window": {
"title": "Rax App"
}
}
6 changes: 6 additions & 0 deletions examples/with-rax-lite/src/app.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { createElement, render } from 'rax';
import DriverUniversal from 'driver-universal';

render(<div>123</div>, document.body, {
driver: DriverUniversal
});
22 changes: 22 additions & 0 deletions examples/with-rax-lite/src/document/index.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { createElement } from 'rax';
import { Root, Style, Script, Data } from 'rax-document';

function Document(props) {
return (
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no,viewport-fit=cover" />
<title>@ali/demo-app</title>
<Style />
</head>
<body>
{/* root container */}
<Root />
<Data />
<Script />
</body>
</html>
);
}
export default Document;
20 changes: 20 additions & 0 deletions examples/with-rax-lite/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"module": "esNext",
"target": "es2015",
"outDir": "build",
"jsx": "preserve",
"jsxFactory": "createElement",
"moduleResolution": "node",
"sourceMap": true,
"alwaysStrict": true,
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"],
"rax-app": [".rax/index.ts"],
"rax": ["node_modules/@types/rax"]
}
},
"include": ["src/*", ".rax"],
"exclude": ["build"]
}
5 changes: 3 additions & 2 deletions packages/plugin-app-base/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "build-plugin-app-base",
"version": "1.0.8",
"version": "1.0.9-0",
"description": "rax app base plugin",
"main": "lib/index.js",
"scripts": {
Expand Down Expand Up @@ -60,6 +60,7 @@
"webpack-plugin-import": "^0.2.6",
"webpack-sources": "^1.3.0",
"webpackbar": "^4.0.0",
"copy-webpack-plugin": "^5.0.0"
"copy-webpack-plugin": "^5.0.0",
"build-app-helpers": "^1.0.1"
}
}
15 changes: 0 additions & 15 deletions packages/plugin-app-base/src/loaders/AppConfigLoader/getDepPath.js

This file was deleted.

26 changes: 5 additions & 21 deletions packages/plugin-app-base/src/loaders/AppConfigLoader/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const { getOptions } = require('loader-utils');
const { join } = require('path');
const { formatPath } = require('build-app-helpers');
const getRouteName = require('../../utils/getRouteName');
const getDepPath = require('./getDepPath');

/**
* universal-app-config-loader
Expand All @@ -11,11 +12,7 @@ const getDepPath = require('./getDepPath');
"source": "pages/Home/index",
"component": fn,
}
],
"shell": {
"source": "shell/index",
"component": fn
},
]
"hydrate": false
}
*/
Expand Down Expand Up @@ -53,7 +50,7 @@ module.exports = function (appJSON) {
// Second level function to support rax-use-router rule autorun function type component.
const dynamicImportComponent =
`(routeProps) =>
import(/* webpackChunkName: "${getRouteName(route, this.rootContext).toLocaleLowerCase()}.chunk" */ '${getDepPath(route.source, this.rootContext)}')
import(/* webpackChunkName: "${getRouteName(route, this.rootContext).toLocaleLowerCase()}.chunk" */ '${route.pageSource || formatPath(join(this.rootContext, 'src', route.source))}')
.then((mod) => () => {
const reference = interopRequire(mod);
function Component(props) {
Expand All @@ -64,7 +61,7 @@ module.exports = function (appJSON) {
return Component;
})
`;
const importComponent = `() => () => interopRequire(require('${getDepPath(route.source, this.rootContext)}'))`;
const importComponent = `() => () => interopRequire(require('${route.pageSource || formatPath(join(this.rootContext, 'src', route.source))}'))`;

return `routes.push(
{
Expand All @@ -74,18 +71,6 @@ module.exports = function (appJSON) {
);`;
}).join('\n');

let processShell;
if (appConfig.shell) {
processShell = `
import Shell from "${getDepPath(appConfig.shell.source, this.rootContext)}";
appConfig.shell = {
source: '${appConfig.shell.source}',
component: Shell
};
`;
} else {
processShell = '';
}

return `
import { createElement } from 'rax';
Expand All @@ -96,7 +81,6 @@ module.exports = function (appJSON) {
...${appJSON},
routes
};
${processShell}
export default appConfig;
`;
};
7 changes: 6 additions & 1 deletion packages/plugin-app-base/src/registerUserConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,12 @@ const CONFIG = [
name: 'modeConfig',
validation: 'object',
defaultValue: {},
}
},
{
name: 'lite',
Copy link
Collaborator

Choose a reason for hiding this comment

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

没看出 lite 模式的作用是做了什么

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

去掉了,测试了一下 src/app.tsx 里不调用 runApp 就不会把框架运行时的依赖打进来

validation: 'boolean',
defaultValue: false
},
];

module.exports = (api) => {
Expand Down
6 changes: 3 additions & 3 deletions packages/plugin-app-base/src/userConfig/babelPresets.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const formatWinPath = require('../utils/formatWinPath');
const { formatPath } = require('build-app-helpers');

module.exports = (config, babelPresets) => {
['jsx', 'tsx'].forEach((rule) => {
Expand All @@ -11,7 +11,7 @@ module.exports = (config, babelPresets) => {
const [presetPath] = Array.isArray(preset) ? preset : [preset];
let matchedPreset = null;
extraPresets = extraPresets.filter((babelPreset) => {
const matched = formatWinPath(presetPath).indexOf(Array.isArray(babelPreset) ? babelPreset[0] : babelPreset) > -1;
const matched = formatPath(presetPath).indexOf(Array.isArray(babelPreset) ? babelPreset[0] : babelPreset) > -1;
if (matched) {
matchedPreset = babelPreset;
}
Expand All @@ -30,4 +30,4 @@ module.exports = (config, babelPresets) => {
};
});
});
};
};
4 changes: 2 additions & 2 deletions packages/plugin-app-base/src/userConfig/browserslist.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const formatWinPath = require('../utils/formatWinPath');
const { formatPath } = require('build-app-helpers');

module.exports = (config, browserslist) => {
['jsx', 'tsx'].forEach((rule) => {
Expand All @@ -8,7 +8,7 @@ module.exports = (config, browserslist) => {
.tap((options) => {
const babelPresets = options.presets || [];
const presets = babelPresets.map((preset) => {
if (Array.isArray(preset) && formatWinPath(preset[0]).indexOf(formatWinPath('@babel/preset-env')) > -1) {
if (Array.isArray(preset) && formatPath(preset[0]).indexOf(formatPath('@babel/preset-env')) > -1) {
return [
preset[0],
Object.assign(preset[1], { targets: browserslist }),
Expand Down
6 changes: 3 additions & 3 deletions packages/plugin-app-base/src/userConfig/hash.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const path = require('path');
const formatWinPath = require('../utils/formatWinPath');
const { formatPath } = require('build-app-helpers');

module.exports = (config, hash, context) => {
const { command } = context;
Expand All @@ -12,10 +12,10 @@ module.exports = (config, hash, context) => {
pathArray.pop(); // pop filename
pathArray = pathArray.filter((v) => v);
const outputPath = pathArray.length ? pathArray.join('/') : '';
config.output.filename(formatWinPath(path.join(outputPath, `[name].[${hashStr}].js`)));
config.output.filename(formatPath(path.join(outputPath, `[name].[${hashStr}].js`)));
if (config.plugins.get('MiniCssExtractPlugin')) {
config.plugin('MiniCssExtractPlugin').tap((args) => [Object.assign(...args, {
filename: formatWinPath(path.join(outputPath, `[name].[${hashStr}].css`)),
filename: formatPath(path.join(outputPath, `[name].[${hashStr}].css`)),
})]);
}
}
Expand Down
8 changes: 4 additions & 4 deletions packages/plugin-app-base/src/userConfig/injectBabel.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const formatWinPath = require('../utils/formatWinPath');
const { formatPath } = require('build-app-helpers');
const addBablePlugins = require('./babelPlugins');

module.exports = (config, injectBabel, context) => {
Expand All @@ -14,16 +14,16 @@ module.exports = (config, injectBabel, context) => {
.tap((options) => {
// get @babel/plugin-transform-runtime
const babelPlugins = options.plugins || [];
const targetPlugin = formatWinPath('@babel/plugin-transform-runtime');
const targetPlugin = formatPath('@babel/plugin-transform-runtime');
const plguinOption = {
corejs: false,
helpers: true,
regenerator: true,
useESModules: false,
};
const plugins = babelPlugins.map((plugin) => {
if (typeof plugin === 'string' && formatWinPath(plugin).indexOf(targetPlugin) > -1
|| Array.isArray(plugin) && formatWinPath(plugin[0]).indexOf(targetPlugin) > -1 ) {
if (typeof plugin === 'string' && formatPath(plugin).indexOf(targetPlugin) > -1
|| Array.isArray(plugin) && formatPath(plugin[0]).indexOf(targetPlugin) > -1 ) {
return [Array.isArray(plugin) ? plugin[0] : plugin, plguinOption];
} else {
return [require.resolve('@babel/plugin-transform-runtime'), plguinOption];
Expand Down
6 changes: 3 additions & 3 deletions packages/plugin-app-base/src/userConfig/outputAssetsPath.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
const path = require('path');
const { last } = require('lodash');
const formatWinPath = require('../utils/formatWinPath');
const { formatPath } = require('build-app-helpers');

function getFilename(filePath) {
return last((filePath || '').split('/'));
}
module.exports = (config, outputAssetsPath) => {
const filename = getFilename(config.output.get('filename'));
config.output.filename(formatWinPath(path.join(outputAssetsPath.js || '', filename)));
config.output.filename(formatPath(path.join(outputAssetsPath.js || '', filename)));

if (config.plugins.get('MiniCssExtractPlugin')) {
const options = config.plugin('MiniCssExtractPlugin').get('args')[0];
config.plugin('MiniCssExtractPlugin').tap((args) => [Object.assign(...args, {
filename: formatWinPath(path.join(outputAssetsPath.css || '', getFilename(options.filename))),
filename: formatPath(path.join(outputAssetsPath.css || '', getFilename(options.filename))),
})]);
}
};
5 changes: 0 additions & 5 deletions packages/plugin-app-base/src/utils/formatWinPath.js

This file was deleted.

12 changes: 9 additions & 3 deletions packages/plugin-app-core/src/generator/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,9 @@ export default class Generator {

private showPrettierError: boolean;

constructor({ rootDir, targetDir, templatesDir, appTemplateDir, commonTemplateDir, defaultData, log}) {
public lite: boolean;

constructor({ rootDir, targetDir, templatesDir, appTemplateDir, commonTemplateDir, defaultData, log, lite}) {
this.rootDir = rootDir;
this.templatesDir = templatesDir;
this.appTemplateDir = appTemplateDir;
Expand All @@ -55,6 +57,7 @@ export default class Generator {
this.rerender = false;
this.log = log;
this.showPrettierError = true;
this.lite = lite;
}

public addExport = (registerKey, exportData: IExportData | IExportData[]) => {
Expand Down Expand Up @@ -103,7 +106,6 @@ export default class Generator {
}

public parseRenderData() {
const staticConfig = globby.sync(['src/app.json'], { cwd: this.rootDir });
const globalStyles = globby.sync(['src/global.@(scss|less|css)'], { cwd: this.rootDir });
let exportsData = {};
EXPORT_API_MPA.forEach(item => {
Expand All @@ -115,13 +117,17 @@ export default class Generator {
this.renderData = {
...this.renderData,
...exportsData,
staticConfig: staticConfig.length && staticConfig[0],
globalStyle: globalStyles.length && globalStyles[0],
entryImportsBefore: this.generateImportStr('addEntryImports_before'),
entryImportsAfter: this.generateImportStr('addEntryImports_after'),
entryCodeBefore: this.contentRegistration.addEntryCode_before || '',
entryCodeAfter: this.contentRegistration.addEntryCode_after || '',
};
// If it's lite mode, it needn't generate staticConfig
if (!this.lite) {
const staticConfig = globby.sync(['src/app.json'], { cwd: this.rootDir });
this.renderData.staticConfig = staticConfig.length && staticConfig[0];
}
}

public generateImportStr(apiName) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import createShareAPI, { history } from 'create-app-shared';
import loadRuntimeModules from './loadRuntimeModules';
import loadStaticModules from './loadStaticModules';
import defaultStaticConfig from './staticConfig';

import { setAppConfig } from './appConfig';
import { mount, unmount } from './render';
import ErrorBoundary from './ErrorBoundary';
Expand Down
7 changes: 4 additions & 3 deletions packages/plugin-app-core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,8 @@ function initGenerator(api, options) {
const { framework } = options;
const plugins = getAllPlugin();
const templatesDir = path.join(__dirname, './generator/templates');
const { targets = [] } = userConfig;
const isMiniapp = targets.includes('miniapp') || targets.includes('wechat-miniprogram');
const { targets = [], lite } = userConfig;
const isMiniapp = targets.includes('miniapp') || targets.includes('wechat-miniprogram') || targets.includes('bytedance-microapp');
return new Generator({
rootDir,
targetDir: getValue(TEMP_PATH),
Expand All @@ -77,7 +77,8 @@ function initGenerator(api, options) {
runtimeModules: getRuntimeModules(plugins),
buildConfig: JSON.stringify(userConfig)
},
log
log,
lite,
});
}

Expand Down
Loading