Skip to content

Commit

Permalink
fix: redirect named import (#6061)
Browse files Browse the repository at this point in the history
* fix: redirect named import

* fix: test case

* fix: redirect request

* test: redirect request

* chore: add changeset

* feat: support get exports by target

* fix: type

---------

Co-authored-by: shuilan.cj <[email protected]>
  • Loading branch information
ClarkXia and chenjun1011 authored Mar 17, 2023
1 parent 4671cbe commit 4a73cb2
Show file tree
Hide file tree
Showing 12 changed files with 80 additions and 20 deletions.
5 changes: 5 additions & 0 deletions .changeset/clever-shrimps-sip.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@ice/webpack-config': patch
---

fix: redirect named import
5 changes: 5 additions & 0 deletions .changeset/gorgeous-rice-stare.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@ice/app': patch
---

fix: redirect request for data loader
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 {};
}
});
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
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
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\';');
});
});
});
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 4a73cb2

Please sign in to comment.