Skip to content

Commit

Permalink
Merge pull request #6079 from alibaba/release/next
Browse files Browse the repository at this point in the history
Release 3.1.4
  • Loading branch information
ClarkXia authored Mar 20, 2023
2 parents df3458e + 2f50802 commit 7f7f446
Show file tree
Hide file tree
Showing 20 changed files with 131 additions and 44 deletions.
21 changes: 12 additions & 9 deletions examples/with-request/src/pages/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { Outlet, defineDataLoader } from 'ice';
import { Outlet, defineDataLoader, useData, request } from 'ice';

export default () => {
const data = useData();
console.log(data);

return (
<div>
<h1>ICE 3.0 Layout</h1>
Expand All @@ -21,12 +24,12 @@ export function pageConfig() {
};
}

export const dataLoader = defineDataLoader(() => {
return new Promise((resolve) => {
setTimeout(() => {
resolve({
layout: true,
});
}, 1 * 100);
});
export const dataLoader = defineDataLoader(async () => {
try {
const data = await request('/data');
return data;
} catch (e) {
console.error(e);
return {};
}
});
10 changes: 10 additions & 0 deletions packages/ice/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
# Changelog

## 3.1.4

### Patch Changes

- 4a73cb2a: fix: redirect request for data loader
- 1ef827b1: fix: external node builtin modules
- 4671cbe7: fix: resource should not run document render
- Updated dependencies [4a73cb2a]
- @ice/webpack-config@1.0.10

## 3.1.3

### Patch Changes
Expand Down
4 changes: 2 additions & 2 deletions packages/ice/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@ice/app",
"version": "3.1.3",
"version": "3.1.4",
"description": "provide scripts and configuration used by web framework ice",
"type": "module",
"main": "./esm/index.js",
Expand Down Expand Up @@ -41,7 +41,7 @@
"@ice/bundles": "0.1.6",
"@ice/route-manifest": "1.1.0",
"@ice/runtime": "^1.1.4",
"@ice/webpack-config": "1.0.9",
"@ice/webpack-config": "1.0.10",
"@swc/helpers": "0.4.14",
"@types/express": "^4.17.14",
"address": "^1.1.2",
Expand Down
4 changes: 2 additions & 2 deletions packages/ice/src/commands/start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ import { IMPORT_META_RENDERER, IMPORT_META_TARGET, RUNTIME_TMP_DIR, WEB, DEFAULT
import webpackCompiler from '../service/webpackCompiler.js';
import formatWebpackMessages from '../utils/formatWebpackMessages.js';
import prepareURLs from '../utils/prepareURLs.js';
import createRenderMiddleware from '../middlewares/ssr/renderMiddleware.js';
import createOnDemandMiddleware from '../middlewares/ssr/renderOnDemand.js';
import createRenderMiddleware from '../middlewares/renderMiddleware.js';
import createOnDemandMiddleware from '../middlewares/renderOnDemand.js';
import createMockMiddleware from '../middlewares/mock/createMiddleware.js';
import getRouterBasename from '../utils/getRouterBasename.js';
import { getExpandedEnvs } from '../utils/runtimeEnv.js';
Expand Down
3 changes: 3 additions & 0 deletions packages/ice/src/createService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,9 @@ async function createService({ rootDir, command, commandArgs }: CreateServiceOpt
declarationType: DeclarationType.NORMAL,
});
},
getExportList: (registerKey: string) => {
return generator.getExportList(registerKey);
},
render: generator.render,
};

Expand Down
18 changes: 18 additions & 0 deletions packages/ice/src/esbuild/externalNodeBuiltin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { isNodeBuiltin } from 'mlly';
import type { Plugin, PluginBuild } from 'esbuild';

const externalBuiltinPlugin = (): Plugin => {
return {
name: 'esbuild-external-node-builtin',
setup(build: PluginBuild) {
build.onResolve({ filter: /.*/ }, (args) => {
const id = args.path;
if (isNodeBuiltin(id)) {
return { path: id, external: true };
}
});
},
};
};

export default externalBuiltinPlugin;
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@ import type { ServerContext, RenderMode } from '@ice/runtime';
import matchRoutes from '@ice/runtime/matchRoutes';
import type { TaskConfig } from 'build-scripts';
import type { Config } from '@ice/webpack-config/types';
import type { ExtendsPluginAPI } from '../../types/plugin.js';
import getRouterBasename from '../../utils/getRouterBasename.js';
import dynamicImport from '../../utils/dynamicImport.js';
import warnOnHashRouterEnabled from '../../utils/warnOnHashRouterEnabled.js';
import type { UserConfig } from '../../types/userConfig.js';
import { logger } from '../../utils/logger.js';
import type RouteManifest from '../../utils/routeManifest.js';
import type { ExtendsPluginAPI } from '../types/plugin.js';
import getRouterBasename from '../utils/getRouterBasename.js';
import dynamicImport from '../utils/dynamicImport.js';
import warnOnHashRouterEnabled from '../utils/warnOnHashRouterEnabled.js';
import type { UserConfig } from '../types/userConfig.js';
import { logger } from '../utils/logger.js';
import type RouteManifest from '../utils/routeManifest.js';

const require = createRequire(import.meta.url);

Expand Down Expand Up @@ -43,8 +43,9 @@ export default function createRenderMiddleware(options: Options): Middleware {
}
const basename = getRouterBasename(taskConfig, appConfig);
const matches = matchRoutes(routes, req.path, basename);
const isStaticResources = /\.(js|mjs|map|json|png|jpg|jpeg|gif|svg|eot|woff2|ttf)$/;
// When documentOnly is true, it means that the app is CSR and it should return the html.
if (matches.length || documentOnly) {
if (matches.length || documentOnly || !isStaticResources) {
// Wait for the server compilation to finish
const { serverEntry, error } = await serverCompileTask.get();
if (error) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@ import type { ServerContext, RenderMode } from '@ice/runtime';
import matchRoutes from '@ice/runtime/matchRoutes';
import type { TaskConfig } from 'build-scripts';
import type { Config } from '@ice/webpack-config/types';
import getRouterBasename from '../../utils/getRouterBasename.js';
import warnOnHashRouterEnabled from '../../utils/warnOnHashRouterEnabled.js';
import type { UserConfig } from '../../types/userConfig.js';
import { logger } from '../../utils/logger.js';
import type ServerRunner from '../../service/ServerRunner.js';
import type RouteManifest from '../../utils/routeManifest.js';
import getRouterBasename from '../utils/getRouterBasename.js';
import warnOnHashRouterEnabled from '../utils/warnOnHashRouterEnabled.js';
import type { UserConfig } from '../types/userConfig.js';
import { logger } from '../utils/logger.js';
import type ServerRunner from '../service/ServerRunner.js';
import type RouteManifest from '../utils/routeManifest.js';

interface Options {
routeManifest: RouteManifest;
Expand Down
10 changes: 6 additions & 4 deletions packages/ice/src/service/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import dynamicImport from '../utils/dynamicImport.js';
import formatPath from '../utils/formatPath.js';
import { RUNTIME_TMP_DIR, CACHE_DIR } from '../constant.js';
import { createLogger } from '../utils/logger.js';
import externalBuiltinPlugin from '../esbuild/externalNodeBuiltin.js';

type GetOutfile = (entry: string, exportNames: string[]) => string;

Expand Down Expand Up @@ -45,11 +46,12 @@ class Config {
const { error } = await serverCompiler({
entryPoints: [entry],
format: 'esm',
platform: 'node',
// Don't add banner for config file, it will cause name conflict when bundled by server entry.
banner: undefined,
outfile,
plugins: [removeTopLevelCode(keepExports, transformInclude)],
plugins: [
removeTopLevelCode(keepExports, transformInclude),
// External node builtin modules, such as `fs`, it will be imported by weex document.
externalBuiltinPlugin(),
],
sourcemap: false,
logLevel: 'silent', // The main server compiler process will log it.
}, {});
Expand Down
12 changes: 12 additions & 0 deletions packages/ice/src/service/runtimeGenerator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,18 @@ export default class Generator {
this.contentRegistration[registerKey].push(...content);
};

public getExportList = (registerKey: string, target?: string) => {
const exportList = this.contentRegistration[registerKey] || [];

if (target) {
return exportList.filter(exports => {
return !(exports.target && exports.target !== target);
});
} else {
return exportList;
}
};

private getDeclarations: GetDeclarations = (registerKey, dataKeys) => {
const exportList = this.contentRegistration[registerKey] || [];
const {
Expand Down
13 changes: 11 additions & 2 deletions packages/ice/src/service/webpackCompiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ async function webpackCompiler(options: {
// `commandArgs` doesn't guarantee target exists.
const { target = WEB } = commandArgs;
const { serverCompiler, serverRunner } = hooksAPI;
const { serverCompileTask, dataCache, watch } = context.extendsPluginAPI;
const { serverCompileTask, dataCache, watch, generator } = context.extendsPluginAPI;

await applyHook(`before.${command}.run`, {
urls,
Expand Down Expand Up @@ -121,7 +121,16 @@ async function webpackCompiler(options: {

// Add webpack plugin of data-loader.
if (useDataLoader) {
webpackConfig.plugins.push(new DataLoaderPlugin({ serverCompiler, target, rootDir, dataCache, getAllPlugin }));
const frameworkExports = generator.getExportList('framework', target);

webpackConfig.plugins.push(new DataLoaderPlugin({
serverCompiler,
target,
rootDir,
dataCache,
getAllPlugin,
frameworkExports,
}));
}
}

Expand Down
2 changes: 2 additions & 0 deletions packages/ice/src/types/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ type AddTargetExport = (exportData: TargetDeclarationData) => void;
type AddEntryCode = (callback: (code: string) => string) => void;
type RemoveExport = (removeSource: string | string[]) => void;
type EventName = 'add' | 'addDir' | 'change' | 'unlink' | 'unlinkDir';
type GetExportList = (key: string, target?: string) => (DeclarationData | TargetDeclarationData)[];

type ServerCompilerBuildOptions = Pick<
esbuild.BuildOptions,
Expand Down Expand Up @@ -142,6 +143,7 @@ export interface ExtendsPluginAPI {
render: Render;
addDataLoaderImport: AddDataLoaderImport;
addEntryCode: AddEntryCode;
getExportList: GetExportList;
};
watch: {
addEvent?: (watchEvent: WatchEvent) => void;
Expand Down
10 changes: 7 additions & 3 deletions packages/ice/src/webpack/DataLoaderPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ import type { Compiler } from 'webpack';
import webpack from '@ice/bundles/compiled/webpack/index.js';
import type { Context } from 'build-scripts';
import type { ServerCompiler, PluginData } from '../types/plugin.js';
import { IMPORT_META_RENDERER, IMPORT_META_TARGET, RUNTIME_TMP_DIR, RUNTIME_EXPORTS } from '../constant.js';
import type { DeclarationData } from '../types/generator.js';
import { IMPORT_META_RENDERER, IMPORT_META_TARGET, RUNTIME_TMP_DIR } from '../constant.js';
import { getRoutePathsFromCache } from '../utils/getRoutePaths.js';

const pluginName = 'DataLoaderPlugin';
Expand All @@ -16,20 +17,23 @@ export default class DataLoaderPlugin {
private target: string;
private dataCache: Map<string, string>;
private getAllPlugin: Context['getAllPlugin'];
private frameworkExports: DeclarationData[];

public constructor(options: {
serverCompiler: ServerCompiler;
rootDir: string;
target: string;
dataCache: Map<string, string>;
getAllPlugin?: Context['getAllPlugin'];
frameworkExports: DeclarationData[];
}) {
const { serverCompiler, rootDir, dataCache, getAllPlugin, target } = options;
const { serverCompiler, rootDir, dataCache, getAllPlugin, target, frameworkExports } = options;
this.serverCompiler = serverCompiler;
this.rootDir = rootDir;
this.dataCache = dataCache;
this.getAllPlugin = getAllPlugin;
this.target = target;
this.frameworkExports = frameworkExports;
}

public apply(compiler: Compiler) {
Expand Down Expand Up @@ -74,7 +78,7 @@ export default class DataLoaderPlugin {
transformEnv: false,
enableEnv: true,
// Redirect imports to @ice/runtime to avoid build plugin side effect code.
redirectImports: RUNTIME_EXPORTS,
redirectImports: this.frameworkExports,
isServer: false,
},
);
Expand Down
6 changes: 6 additions & 0 deletions packages/webpack-config/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Changelog

## 1.0.10

### Patch Changes

- 4a73cb2a: fix: redirect named import

## 1.0.9

### Patch Changes
Expand Down
2 changes: 1 addition & 1 deletion packages/webpack-config/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@ice/webpack-config",
"version": "1.0.9",
"version": "1.0.10",
"repository": "alibaba/ice",
"bugs": "https://github.com/alibaba/ice/issues",
"homepage": "https://v3.ice.work",
Expand Down
4 changes: 2 additions & 2 deletions packages/webpack-config/src/unPlugins/redirectImport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,13 +63,13 @@ export function parseRedirectData(data: DeclarationData[]): RedirectData {
}

export function generateImport(matchedImports: MatchedImports): string {
let defaultImport = '';
let namedImports = [];
function parseLocalIdentifier(identifier: string, alias: Record<string, string>): string {
return alias[identifier] ? `${alias[identifier]} as ${identifier}` : identifier;
}
const importStatements = Object.keys(matchedImports).map((source) => {
const importStatements = matchedImports[source];
let defaultImport = '';
const namedImports = [];
importStatements.forEach(({ isDefault, identifier, alias }) => {
if (isDefault) {
defaultImport = parseLocalIdentifier(identifier, alias);
Expand Down
Original file line number Diff line number Diff line change
@@ -1 +1 @@
import { request, store } from 'ice';
import { request, store, test } from 'ice';
6 changes: 3 additions & 3 deletions packages/webpack-config/tests/redirectImport.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ describe('redirect import', () => {
specifier: 'store',
source: '@ice/store',
}, {
specifier: 'request',
specifier: ['request', 'test'],
source: 'axios',
}];

Expand Down Expand Up @@ -52,7 +52,7 @@ describe('redirect import', () => {
it('multiple transform', async () => {
const code = fs.readFileSync(path.join(__dirname, './fixtures/redirectImport/multiple.js'), 'utf-8');
const transformed = await redirectImport(code, { exportData, targetSource: 'ice' });
expect(transformed).toBe('import request from \'axios\';\nimport store from \'@ice/store\';');
expect(transformed).toBe('import { request, test } from \'axios\';\nimport store from \'@ice/store\';');
});
it('matched transform', async () => {
const code = fs.readFileSync(path.join(__dirname, './fixtures/redirectImport/matched.js'), 'utf-8');
Expand All @@ -64,4 +64,4 @@ describe('redirect import', () => {
const transformed = await redirectImport(code, { exportData, targetSource: 'ice' });
expect(transformed).toBe('import { defineDataLoader } from \'ice\';');
});
});
});
2 changes: 1 addition & 1 deletion pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 17 additions & 0 deletions tests/integration/with-request.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { expect, test, describe } from 'vitest';
import { buildFixture } from '../utils/build';

// @ts-ignore
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const example = 'with-request';

describe(`build ${example}`, () => {
test('data-loader build file', async () => {
await buildFixture(example);
const content = fs.readFileSync(path.join(__dirname, `../../examples/${example}/build/js/data-loader.js`), 'utf-8');
expect(content.includes('react.element')).toBe(false);
});
});

0 comments on commit 7f7f446

Please sign in to comment.