diff --git a/.eslintrc.js b/.eslintrc.js
index d12a18f..c0b883a 100644
--- a/.eslintrc.js
+++ b/.eslintrc.js
@@ -2,11 +2,10 @@ const { eslint, tslint, deepmerge } = require('@ice/spec');
const commonRules = {
"react/jsx-filename-extension": 0,
- "semi": 0,
"no-underscore-dangle": 0,
"class-methods-use-this": 0,
"no-param-reassign": 0,
- "comma-dangle": 0,
+ "comma-dangle": 0
};
const jsRules = deepmerge(eslint, {
diff --git a/examples/basic-mpa/src/pages/Dashboard/app.ts b/examples/basic-mpa/src/pages/Dashboard/app.ts
index c0fea3e..7c75c56 100644
--- a/examples/basic-mpa/src/pages/Dashboard/app.ts
+++ b/examples/basic-mpa/src/pages/Dashboard/app.ts
@@ -1,10 +1,10 @@
-import { createApp, IAppConfig } from 'ice'
-import Dashboard from './index'
+import { createApp, IAppConfig } from 'ice';
+import Dashboard from './index';
const appConfig: IAppConfig = {
router: {
routes: [{ path: '/', component: Dashboard }],
},
-}
+};
-createApp(appConfig)
+createApp(appConfig);
diff --git a/examples/basic-mpa/src/pages/Dashboard/index.tsx b/examples/basic-mpa/src/pages/Dashboard/index.tsx
index b73ddd4..f704186 100644
--- a/examples/basic-mpa/src/pages/Dashboard/index.tsx
+++ b/examples/basic-mpa/src/pages/Dashboard/index.tsx
@@ -1,8 +1,8 @@
-import * as React from 'react'
-import { store } from 'ice/Dashboard'
+import * as React from 'react';
+import { store } from 'ice/Dashboard';
const Dashboard = () => {
- const [pageState, pageActions] = store.useModel('counter')
+ const [pageState, pageActions] = store.useModel('counter');
return (
<>
Dashboard Page...
@@ -12,7 +12,7 @@ const Dashboard = () => {
>
- )
-}
+ );
+};
-export default Dashboard
+export default Dashboard;
diff --git a/examples/basic-mpa/src/pages/Dashboard/models/counter.ts b/examples/basic-mpa/src/pages/Dashboard/models/counter.ts
index 8c45dfa..f4c259e 100644
--- a/examples/basic-mpa/src/pages/Dashboard/models/counter.ts
+++ b/examples/basic-mpa/src/pages/Dashboard/models/counter.ts
@@ -7,10 +7,10 @@ export default {
reducers: {
increment (prevState) {
- return { count: prevState.count + 1 }
+ return { count: prevState.count + 1 };
},
decrement (prevState) {
- return { count: prevState.count - 1 }
+ return { count: prevState.count - 1 };
}
},
diff --git a/examples/basic-mpa/src/pages/Home/app.ts b/examples/basic-mpa/src/pages/Home/app.ts
index fe34387..650e813 100644
--- a/examples/basic-mpa/src/pages/Home/app.ts
+++ b/examples/basic-mpa/src/pages/Home/app.ts
@@ -1,10 +1,10 @@
-import { createApp, IAppConfig } from 'ice'
-import Home from './index'
+import { createApp, IAppConfig } from 'ice';
+import Home from './index';
const appConfig: IAppConfig = {
router: {
routes: [{ path: '/', component: Home }],
},
-}
+};
-createApp(appConfig)
+createApp(appConfig);
diff --git a/examples/basic-mpa/src/pages/Home/index.tsx b/examples/basic-mpa/src/pages/Home/index.tsx
index 8e04766..3198926 100644
--- a/examples/basic-mpa/src/pages/Home/index.tsx
+++ b/examples/basic-mpa/src/pages/Home/index.tsx
@@ -1,4 +1,4 @@
-import React from 'react'
+import React from 'react';
const Home = () => {
return (
@@ -6,10 +6,10 @@ const Home = () => {
Home Page
>
);
-}
+};
Home.pageConfig = {
title: 'Home Page',
};
-export default Home
+export default Home;
diff --git a/examples/basic-request/src/pages/Home/index.tsx b/examples/basic-request/src/pages/Home/index.tsx
index d971634..d5cf79e 100644
--- a/examples/basic-request/src/pages/Home/index.tsx
+++ b/examples/basic-request/src/pages/Home/index.tsx
@@ -1,26 +1,29 @@
-import React, { useEffect } from 'react'
-import { useRequest, request } from 'ice'
+import React, { useEffect } from 'react';
+import { useRequest, request } from 'ice';
+
+// 1. request in outside
+request('/user').then(res => console.log('request in outside:', res));
const Home = () => {
- // 1. useRequest hook
- const { data, loading, request: fetchRepo } = useRequest({ url: '/repo' })
+ // 2. useRequest hook
+ const { data, loading, request: fetchRepo } = useRequest({ url: '/repo' });
useEffect(() => {
- fetchRepo()
-
- request('/user').then(res => console.log('get:', res))
- // 2. requse.get alias
- request.get('/user').then(res => console.log('get:', res))
+ fetchRepo();
+
+ // 3. requse.get alias
+ request.get('/user').then(res => console.log('get:', res));
- // 3. requse.post alias
- request.post('/users/123').then(res => console.log('post:', res))
+ // 4. requse.post alias
+ request.post('/users/123').then(res => console.log('post:', res));
- // 4. requse.delete alias
- request.delete('/user/123').then(res => console.log('delete:', res))
+ // 5. requse.delete alias
+ request.delete('/user/123').then(res => console.log('delete:', res));
- // 5. request method
- request({ url: '/user'}).then((res) => {console.log('request:', res)})
- }, [])
+ // 6. request method
+ request({ url: '/user'}).then((res) => {console.log('request:', res);});
+ // eslint-disable-next-line
+ }, []);
return (
@@ -35,7 +38,7 @@ const Home = () => {
>
}
- )
+ );
};
export default Home;
diff --git a/examples/basic-request/src/routes.ts b/examples/basic-request/src/routes.ts
index b358072..0ca6964 100644
--- a/examples/basic-request/src/routes.ts
+++ b/examples/basic-request/src/routes.ts
@@ -1,10 +1,10 @@
-import Home from '@/pages/Home'
+import Home from '@/pages/Home';
const routerConfig = [
{
path: '/',
component: Home
}
-]
+];
-export default routerConfig
\ No newline at end of file
+export default routerConfig;
\ No newline at end of file
diff --git a/examples/basic-spa/mock/index.js b/examples/basic-spa/mock/index.js
index 96421c4..22d2c66 100644
--- a/examples/basic-spa/mock/index.js
+++ b/examples/basic-spa/mock/index.js
@@ -35,7 +35,7 @@ const projects = [
description: 'A universal framework based on React.js.',
logo: 'https://avatars1.githubusercontent.com/u/1961952',
},
-]
+];
// mock/index.js
module.exports = {
diff --git a/examples/basic-spa/src/app.ts b/examples/basic-spa/src/app.tsx
similarity index 62%
rename from examples/basic-spa/src/app.ts
rename to examples/basic-spa/src/app.tsx
index a1e0765..e747732 100644
--- a/examples/basic-spa/src/app.ts
+++ b/examples/basic-spa/src/app.tsx
@@ -1,4 +1,5 @@
-import { createApp, APP_MODE, IAppConfig } from 'ice'
+import React from 'react';
+import { createApp, APP_MODE, IAppConfig } from 'ice';
const appConfig: IAppConfig = {
app: {
@@ -8,7 +9,8 @@ const appConfig: IAppConfig = {
level: APP_MODE === 'build' ? 'error' : 'debug',
},
router: {
- type: 'hash'
+ type: 'hash',
+ fallback: 加载中...
},
request: {
timeout: 5000,
@@ -16,11 +18,11 @@ const appConfig: IAppConfig = {
interceptors: {
request: {
onConfig: (config) => {
- return config
+ return config;
}
}
}
}
};
-createApp(appConfig)
+createApp(appConfig);
diff --git a/examples/basic-spa/src/config.ts b/examples/basic-spa/src/config.ts
index 3cc9f2e..d5bfabf 100644
--- a/examples/basic-spa/src/config.ts
+++ b/examples/basic-spa/src/config.ts
@@ -1,7 +1,11 @@
+// config runtime APP_MODE
+// eslint-disable-next-line @typescript-eslint/camelcase
+window.__app_mode__ = 'build';
+
const config = {
dev: {
appId: 'dev-id',
- API_URL: 'http://localhost:3333'
+ API_URL: `http://localhost:${process.env.SERVER_PORT}`,
},
build: {
API_URL: 'http://github.com/api'
diff --git a/examples/basic-spa/src/pages/About/index.tsx b/examples/basic-spa/src/pages/About/index.tsx
index 0d43685..6e84fa5 100644
--- a/examples/basic-spa/src/pages/About/index.tsx
+++ b/examples/basic-spa/src/pages/About/index.tsx
@@ -1,13 +1,13 @@
-import React from 'react'
-import { Link } from 'ice'
+import React from 'react';
+import { Link } from 'ice';
const Child = () => {
return (
Child
- )
-}
+ );
+};
const About = () => {
return (
@@ -17,7 +17,7 @@ const About = () => {
dashboard
Home
>
- )
-}
+ );
+};
-export default About
+export default About;
diff --git a/examples/basic-spa/src/pages/Dashboard/index.tsx b/examples/basic-spa/src/pages/Dashboard/index.tsx
index 0c9e916..170e486 100644
--- a/examples/basic-spa/src/pages/Dashboard/index.tsx
+++ b/examples/basic-spa/src/pages/Dashboard/index.tsx
@@ -1,5 +1,5 @@
-import React from 'react'
-import { Link } from 'ice'
+import React from 'react';
+import { Link } from 'ice';
const Dashboard = () => {
return (
@@ -7,7 +7,7 @@ const Dashboard = () => {
Dashboard Page...
About
>
- )
-}
+ );
+};
-export default Dashboard
+export default Dashboard;
diff --git a/examples/basic-spa/src/pages/Home/index.tsx b/examples/basic-spa/src/pages/Home/index.tsx
index b6ca9df..9df6057 100644
--- a/examples/basic-spa/src/pages/Home/index.tsx
+++ b/examples/basic-spa/src/pages/Home/index.tsx
@@ -1,5 +1,5 @@
-import React from 'react'
-import { Link, helpers, logger, config } from 'ice'
+import React from 'react';
+import { Link, helpers, logger, config } from 'ice';
logger.debug('helpers from ice', helpers.urlParse);
logger.debug('logger from ice', logger.debug);
@@ -15,18 +15,9 @@ export default function Home(props) {
logger.info('Home props', props);
logger.info('render home config.appId', config.appId);
- // const { data, error, loading, request: fetchRepo } = useRequest({ url: '/api/repo' })
- // logger.info('useRequest:', { data, error, loading, fetchRepo })
-
- // useEffect(() => {
- // (async function () {
- // await fetchRepo()
- // }())
- // }, [])
-
return (
<>
- Home Page...{props.a}
+ Home Page...{props.count}
About
Dashboard
>
@@ -34,7 +25,7 @@ export default function Home(props) {
}
Home.getInitialProps = async () => {
- return {a: 1}
+ return { count: 1 };
};
Home.pageConfig = {
diff --git a/examples/basic-spa/src/pages/NotFound/index.tsx b/examples/basic-spa/src/pages/NotFound/index.tsx
index 3cd0089..2621d2b 100644
--- a/examples/basic-spa/src/pages/NotFound/index.tsx
+++ b/examples/basic-spa/src/pages/NotFound/index.tsx
@@ -1,5 +1,5 @@
-import React from 'react'
-import { Link } from 'ice'
+import React from 'react';
+import { Link } from 'ice';
const Home = (props) => {
console.log('render 404', props);
@@ -12,6 +12,6 @@ const Home = (props) => {
Dashboard
>
);
-}
+};
-export default Home
+export default Home;
diff --git a/examples/basic-ssr/mock/index.ts b/examples/basic-ssr/mock/index.ts
index 33055ad..2b8ce09 100644
--- a/examples/basic-ssr/mock/index.ts
+++ b/examples/basic-ssr/mock/index.ts
@@ -1,11 +1,22 @@
module.exports = {
+ 'GET /api/user': {
+ status: 'SUCCESS',
+ data: {
+ user: {
+ name: 'Jack Ma',
+ id: 10001,
+ }
+ },
+ },
'GET /api/profile': {
status: 'SUCCESS',
data: {
- name: '淘小宝',
- department: '技术部',
- avatar: 'https://img.alicdn.com/tfs/TB1L6tBXQyWBuNjy0FpXXassXXa-80-80.png',
- userid: 10001,
+ profile: {
+ id: 10001,
+ name: 'Jack Ma',
+ edu: 'Hangzhou Normal University',
+ address: 'Hangzhou'
+ }
},
},
-};
\ No newline at end of file
+};
diff --git a/examples/basic-ssr/package.json b/examples/basic-ssr/package.json
index 86dfcf9..149b217 100644
--- a/examples/basic-ssr/package.json
+++ b/examples/basic-ssr/package.json
@@ -11,7 +11,7 @@
"@types/react-dom": "^16.9.4"
},
"scripts": {
- "start": "icejs start",
+ "start": "icejs start --mode dev",
"build": "icejs build --mode prod"
},
"engines": {
diff --git a/examples/basic-ssr/src/app.ts b/examples/basic-ssr/src/app.ts
index 2848955..4313968 100644
--- a/examples/basic-ssr/src/app.ts
+++ b/examples/basic-ssr/src/app.ts
@@ -1,19 +1,23 @@
-import { createApp, IAppConfig } from 'ice'
+import { createApp, IAppConfig, config, request } from 'ice';
const appConfig: IAppConfig = {
app: {
getInitialData: async () => {
- return { user: { name: 'Jack Ma', id: '01' } }
+ const res = await request('/user');
+ return res;
}
},
router: {
type: 'browser'
},
+ request: {
+ baseURL: config.baseURL
+ },
store: {
getInitialStates: (initialData) => {
- return initialData
+ return initialData.data;
}
}
};
-createApp(appConfig)
+createApp(appConfig);
diff --git a/examples/basic-ssr/src/config.ts b/examples/basic-ssr/src/config.ts
index c12768f..75793bf 100644
--- a/examples/basic-ssr/src/config.ts
+++ b/examples/basic-ssr/src/config.ts
@@ -1,3 +1,10 @@
-const config = {}
+const config = {
+ dev: {
+ baseURL: 'http://localhost:3333/api'
+ },
+ prod: {
+ baseURL: 'http://example.com/api'
+ }
+};
-export default config
+export default config;
diff --git a/examples/basic-ssr/src/layouts/index.tsx b/examples/basic-ssr/src/layouts/index.tsx
index 7acae72..aa011c8 100644
--- a/examples/basic-ssr/src/layouts/index.tsx
+++ b/examples/basic-ssr/src/layouts/index.tsx
@@ -1,5 +1,5 @@
-import * as React from 'react'
-import styles from './index.module.scss'
+import * as React from 'react';
+import styles from './index.module.scss';
const Layout = ({ children }) => {
return (
@@ -7,9 +7,9 @@ const Layout = ({ children }) => {
SSR
{children}
-
+
);
-}
+};
export default Layout;
\ No newline at end of file
diff --git a/examples/basic-ssr/src/pages/About/index.tsx b/examples/basic-ssr/src/pages/About/index.tsx
index 3c7c3c1..b112ce0 100644
--- a/examples/basic-ssr/src/pages/About/index.tsx
+++ b/examples/basic-ssr/src/pages/About/index.tsx
@@ -1,5 +1,5 @@
-import React from 'react'
-import { Link, logger } from 'ice'
+import React from 'react';
+import { Link, logger } from 'ice';
const About = (props) => {
logger.info('About props', props);
@@ -9,11 +9,11 @@ const About = (props) => {
dashboard
home
>
- )
-}
+ );
+};
About.getInitialProps = async () => {
- return { title: 'About Page...' }
-}
+ return { title: 'About Page...' };
+};
-export default About
+export default About;
diff --git a/examples/basic-ssr/src/pages/Dashboard/index.tsx b/examples/basic-ssr/src/pages/Dashboard/index.tsx
index 0d27413..fcdd52a 100644
--- a/examples/basic-ssr/src/pages/Dashboard/index.tsx
+++ b/examples/basic-ssr/src/pages/Dashboard/index.tsx
@@ -1,5 +1,5 @@
-import React from 'react'
-import { Link, logger } from 'ice'
+import React from 'react';
+import { Link, logger } from 'ice';
const Dashboard = (props) => {
logger.info('Dashboard props', props);
@@ -8,16 +8,16 @@ const Dashboard = (props) => {
{props.title}
about
>
- )
-}
+ );
+};
Dashboard.getInitialProps = async () => {
return new Promise((resolve) => {
setTimeout(() => {
resolve({ title: 'Dashboard Page xxxx...' });
}, 1 * 1000);
- })
+ });
// return { title: 'Dashboard Page...' }
-}
+};
-export default Dashboard
+export default Dashboard;
diff --git a/examples/basic-ssr/src/pages/Home/index.tsx b/examples/basic-ssr/src/pages/Home/index.tsx
index db37a39..581be0c 100644
--- a/examples/basic-ssr/src/pages/Home/index.tsx
+++ b/examples/basic-ssr/src/pages/Home/index.tsx
@@ -1,6 +1,6 @@
-import React, { useState, useEffect } from 'react'
-import { Link, logger, store as appStore } from 'ice'
-import styles from './index.module.scss'
+import React, { useState, useEffect } from 'react';
+import { request, Link, logger, store as appStore } from 'ice';
+import styles from './index.module.scss';
export default function Home(props) {
logger.info('Home props', props);
@@ -18,8 +18,9 @@ export default function Home(props) {
<>
{props.title}
-
Name:{userState.name}
+
name:{userState.name}
id:{userState.id}
+
address:{props.profile && props.profile.address}
data:{dataSource.join(' ')}
@@ -30,5 +31,6 @@ export default function Home(props) {
}
Home.getInitialProps = async () => {
- return { title: 'Home Page...' }
+ const res = await request('/profile');
+ return { ...res.data, title: 'Home Page...' };
};
diff --git a/examples/basic-ssr/src/pages/NotFound/index.tsx b/examples/basic-ssr/src/pages/NotFound/index.tsx
index 17f3241..656a3b6 100644
--- a/examples/basic-ssr/src/pages/NotFound/index.tsx
+++ b/examples/basic-ssr/src/pages/NotFound/index.tsx
@@ -1,5 +1,5 @@
-import React from 'react'
-import { Link, logger } from 'ice'
+import React from 'react';
+import { Link, logger } from 'ice';
const Home = (props) => {
logger.info('render 404', props);
@@ -12,6 +12,6 @@ const Home = (props) => {
dashboard
>
);
-}
+};
-export default Home
+export default Home;
diff --git a/examples/basic-ssr/src/routes.ts b/examples/basic-ssr/src/routes.ts
index ba6e030..f72a2bf 100644
--- a/examples/basic-ssr/src/routes.ts
+++ b/examples/basic-ssr/src/routes.ts
@@ -1,8 +1,8 @@
import Layout from '@/layouts';
-import Dashboard from '@/pages/Dashboard'
-import Home from '@/pages/Home'
-import About from '@/pages/About'
-import Notfound from '@/pages/NotFound'
+import Dashboard from '@/pages/Dashboard';
+import Home from '@/pages/Home';
+import About from '@/pages/About';
+import Notfound from '@/pages/NotFound';
export default [
{
diff --git a/examples/basic-store/src/models/counter.ts b/examples/basic-store/src/models/counter.ts
index 8c45dfa..f4c259e 100644
--- a/examples/basic-store/src/models/counter.ts
+++ b/examples/basic-store/src/models/counter.ts
@@ -7,10 +7,10 @@ export default {
reducers: {
increment (prevState) {
- return { count: prevState.count + 1 }
+ return { count: prevState.count + 1 };
},
decrement (prevState) {
- return { count: prevState.count - 1 }
+ return { count: prevState.count - 1 };
}
},
diff --git a/examples/basic-store/src/pages/About/index.tsx b/examples/basic-store/src/pages/About/index.tsx
index 1aaf23f..13dc7c6 100644
--- a/examples/basic-store/src/pages/About/index.tsx
+++ b/examples/basic-store/src/pages/About/index.tsx
@@ -11,10 +11,10 @@ const About = () => {
const fetchData = async () => {
await pageActions.getPageTitle();
await userActions.getUserInfo();
- }
+ };
- fetchData()
- }, [])
+ fetchData();
+ }, [pageActions, userActions]);
return (
<>
@@ -31,7 +31,7 @@ const About = () => {
home
>
- )
+ );
};
export default About;
diff --git a/examples/basic-store/src/pages/Home/index.tsx b/examples/basic-store/src/pages/Home/index.tsx
index 5fc396d..b1719ce 100644
--- a/examples/basic-store/src/pages/Home/index.tsx
+++ b/examples/basic-store/src/pages/Home/index.tsx
@@ -1,10 +1,10 @@
-import React from 'react'
-import { Link, store as appStore } from 'ice'
-import { store as pageStore } from 'ice/Home'
+import React from 'react';
+import { Link, store as appStore } from 'ice';
+import { store as pageStore } from 'ice/Home';
const Home = () => {
- const [counterState, counterActions] = appStore.useModel('counter')
- const [pageState] = pageStore.useModel('default')
+ const [counterState, counterActions] = appStore.useModel('counter');
+ const [pageState] = pageStore.useModel('default');
return (
<>
@@ -18,7 +18,7 @@ const Home = () => {
about
>
- )
+ );
};
export default Home;
diff --git a/examples/basic-store/src/routes.ts b/examples/basic-store/src/routes.ts
index 7c74eb0..a648ce5 100644
--- a/examples/basic-store/src/routes.ts
+++ b/examples/basic-store/src/routes.ts
@@ -11,4 +11,4 @@ export default [
path: '/about',
component: About
}
-]
+];
diff --git a/examples/hello-world/src/pages/Home/index.tsx b/examples/hello-world/src/pages/Home/index.tsx
index eaa9bdb..c57aed1 100644
--- a/examples/hello-world/src/pages/Home/index.tsx
+++ b/examples/hello-world/src/pages/Home/index.tsx
@@ -2,7 +2,7 @@ import React from 'react';
import Guide from '@/components/Guide';
const Home = () => {
- return
+ return ;
};
export default Home;
diff --git a/examples/hello-world/src/routes.ts b/examples/hello-world/src/routes.ts
index b358072..0ca6964 100644
--- a/examples/hello-world/src/routes.ts
+++ b/examples/hello-world/src/routes.ts
@@ -1,10 +1,10 @@
-import Home from '@/pages/Home'
+import Home from '@/pages/Home';
const routerConfig = [
{
path: '/',
component: Home
}
-]
+];
-export default routerConfig
\ No newline at end of file
+export default routerConfig;
\ No newline at end of file
diff --git a/examples/icestark-child/src/app.ts b/examples/icestark-child/src/app.ts
index d5192a2..a83eac4 100644
--- a/examples/icestark-child/src/app.ts
+++ b/examples/icestark-child/src/app.ts
@@ -1,4 +1,4 @@
-import { createApp, IAppConfig } from 'ice'
+import { createApp, IAppConfig } from 'ice';
const appConfig: IAppConfig = {
app: {
@@ -12,4 +12,4 @@ const appConfig: IAppConfig = {
},
};
-createApp(appConfig)
+createApp(appConfig);
diff --git a/examples/icestark-child/src/pages/About/_layout.tsx b/examples/icestark-child/src/pages/About/_layout.tsx
index 94234d1..cc82746 100644
--- a/examples/icestark-child/src/pages/About/_layout.tsx
+++ b/examples/icestark-child/src/pages/About/_layout.tsx
@@ -1,4 +1,4 @@
-import React from 'react'
+import React from 'react';
export default function BasicLayout({
children,
diff --git a/examples/icestark-child/src/pages/About/index.tsx b/examples/icestark-child/src/pages/About/index.tsx
index e0698aa..46c42ec 100644
--- a/examples/icestark-child/src/pages/About/index.tsx
+++ b/examples/icestark-child/src/pages/About/index.tsx
@@ -1,13 +1,13 @@
-import React from 'react'
-import { Link } from 'ice'
+import React from 'react';
+import { Link } from 'ice';
const Child = () => {
return (
Child
- )
-}
+ );
+};
const About = () => {
return (
@@ -17,7 +17,7 @@ const About = () => {
About
Home
>
- )
-}
+ );
+};
-export default About
+export default About;
diff --git a/examples/icestark-child/src/pages/Dashboard/index.tsx b/examples/icestark-child/src/pages/Dashboard/index.tsx
index d088726..e84ee92 100644
--- a/examples/icestark-child/src/pages/Dashboard/index.tsx
+++ b/examples/icestark-child/src/pages/Dashboard/index.tsx
@@ -1,5 +1,5 @@
-import React from 'react'
-import { Link } from 'ice'
+import React from 'react';
+import { Link } from 'ice';
const Dashboard = () => {
return (
@@ -7,7 +7,7 @@ const Dashboard = () => {
Dashboard Page...
About
>
- )
-}
+ );
+};
-export default Dashboard
+export default Dashboard;
diff --git a/examples/icestark-child/src/pages/index.tsx b/examples/icestark-child/src/pages/index.tsx
index 4f05890..504799b 100644
--- a/examples/icestark-child/src/pages/index.tsx
+++ b/examples/icestark-child/src/pages/index.tsx
@@ -1,5 +1,5 @@
-import React from 'react'
-import { Link } from 'ice'
+import React from 'react';
+import { Link } from 'ice';
const Home = (props) => {
return (
@@ -9,14 +9,14 @@ const Home = (props) => {
Dashboard
>
);
-}
+};
Home.getInitialProps = async () => {
- return { a: 1 }
+ return { a: 1 };
};
Home.pageConfig = {
title: 'Home Page'
};
-export default Home
+export default Home;
diff --git a/examples/icestark-layout/src/app.tsx b/examples/icestark-layout/src/app.tsx
index 0807ee7..5fe843e 100644
--- a/examples/icestark-layout/src/app.tsx
+++ b/examples/icestark-layout/src/app.tsx
@@ -1,4 +1,4 @@
-import { createApp, IAppConfig } from 'ice'
+import { createApp, IAppConfig } from 'ice';
import * as React from 'react';
import { ConfigProvider } from '@alifd/next';
@@ -50,4 +50,4 @@ const appConfig: IAppConfig = {
},
};
-createApp(appConfig)
+createApp(appConfig);
diff --git a/examples/icestark-layout/src/pages/404.tsx b/examples/icestark-layout/src/pages/404.tsx
index 21da91c..6161206 100644
--- a/examples/icestark-layout/src/pages/404.tsx
+++ b/examples/icestark-layout/src/pages/404.tsx
@@ -1,5 +1,5 @@
-import React from 'react'
-import { Link } from 'ice'
+import React from 'react';
+import { Link } from 'ice';
const Home = (props) => {
console.log('render home', props);
@@ -12,6 +12,6 @@ const Home = (props) => {
Dashboard
>
);
-}
+};
-export default Home
+export default Home;
diff --git a/examples/with-fusion-design/src/app.ts b/examples/with-fusion-design/src/app.ts
index d8bef5f..81bad3f 100644
--- a/examples/with-fusion-design/src/app.ts
+++ b/examples/with-fusion-design/src/app.ts
@@ -1,9 +1,9 @@
-import { createApp, IAppConfig } from 'ice'
+import { createApp, IAppConfig } from 'ice';
const appConfig: IAppConfig = {
app: {
rootId: 'ice-container'
}
-}
+};
-createApp(appConfig)
+createApp(appConfig);
diff --git a/examples/with-fusion-design/src/pages/Home/index.tsx b/examples/with-fusion-design/src/pages/Home/index.tsx
index 66fada3..1ecd13d 100644
--- a/examples/with-fusion-design/src/pages/Home/index.tsx
+++ b/examples/with-fusion-design/src/pages/Home/index.tsx
@@ -1,5 +1,5 @@
-import React from 'react'
-import { Button } from '@alifd/next'
+import React from 'react';
+import { Button } from '@alifd/next';
const Dashboard = () => {
return (
@@ -9,7 +9,7 @@ const Dashboard = () => {
>
- )
-}
+ );
+};
-export default Dashboard
+export default Dashboard;
diff --git a/examples/with-fusion-design/src/routes.ts b/examples/with-fusion-design/src/routes.ts
index badd54d..26f6aed 100644
--- a/examples/with-fusion-design/src/routes.ts
+++ b/examples/with-fusion-design/src/routes.ts
@@ -1,4 +1,4 @@
-import Home from '@/pages/Home'
+import Home from '@/pages/Home';
export default [
{
@@ -6,4 +6,4 @@ export default [
exact: true,
component: Home
}
-]
+];
diff --git a/examples/with-rematch/src/app.ts b/examples/with-rematch/src/app.ts
index 935f11a..2461c15 100644
--- a/examples/with-rematch/src/app.ts
+++ b/examples/with-rematch/src/app.ts
@@ -1,4 +1,4 @@
-import { createApp } from 'ice'
+import { createApp } from 'ice';
const appConfig = {
app: {
@@ -6,4 +6,4 @@ const appConfig = {
}
};
-createApp(appConfig)
+createApp(appConfig);
diff --git a/examples/with-rematch/src/pages/404.tsx b/examples/with-rematch/src/pages/404.tsx
index 21da91c..6161206 100644
--- a/examples/with-rematch/src/pages/404.tsx
+++ b/examples/with-rematch/src/pages/404.tsx
@@ -1,5 +1,5 @@
-import React from 'react'
-import { Link } from 'ice'
+import React from 'react';
+import { Link } from 'ice';
const Home = (props) => {
console.log('render home', props);
@@ -12,6 +12,6 @@ const Home = (props) => {
Dashboard
>
);
-}
+};
-export default Home
+export default Home;
diff --git a/examples/with-rematch/src/pages/Rematch/Child.tsx b/examples/with-rematch/src/pages/Rematch/Child.tsx
index 16de1f0..9d0c807 100644
--- a/examples/with-rematch/src/pages/Rematch/Child.tsx
+++ b/examples/with-rematch/src/pages/Rematch/Child.tsx
@@ -1,5 +1,5 @@
-import * as React from 'react'
-import { connect } from 'ice'
+import * as React from 'react';
+import { connect } from 'ice';
const Home = (props) => {
const { userState, userAction } = props;
@@ -13,7 +13,7 @@ const Home = (props) => {
>
);
-}
+};
const mapState = models => ({
userState: models.user,
diff --git a/examples/with-rematch/src/pages/Rematch/index.tsx b/examples/with-rematch/src/pages/Rematch/index.tsx
index f01555a..310648c 100644
--- a/examples/with-rematch/src/pages/Rematch/index.tsx
+++ b/examples/with-rematch/src/pages/Rematch/index.tsx
@@ -1,5 +1,5 @@
-import React from 'react'
-import { connect } from 'ice'
+import React from 'react';
+import { connect } from 'ice';
import Child from './Child';
// import Child2 from './Child2';
@@ -12,7 +12,7 @@ const Home = (props) => {
{/* */}
>
);
-}
+};
const mapState = state => ({
userState: state.user,
diff --git a/examples/with-rematch/src/pages/index.tsx b/examples/with-rematch/src/pages/index.tsx
index 3778f0f..1541c37 100644
--- a/examples/with-rematch/src/pages/index.tsx
+++ b/examples/with-rematch/src/pages/index.tsx
@@ -1,5 +1,5 @@
-import React from 'react'
-import { Link, helpers } from 'ice'
+import React from 'react';
+import { Link, helpers } from 'ice';
console.log('helpers from ice', helpers);
@@ -12,14 +12,14 @@ const Home = (props) => {
Dashboard
>
);
-}
+};
Home.getInitialProps = async () => {
- return {a: 1}
+ return {a: 1};
};
Home.pageConfig = {
title: 'hahah',
};
-export default Home
+export default Home;
diff --git a/examples/with-rematch/src/stores/user.ts b/examples/with-rematch/src/stores/user.ts
index e2d54d1..aa0de9c 100644
--- a/examples/with-rematch/src/stores/user.ts
+++ b/examples/with-rematch/src/stores/user.ts
@@ -9,8 +9,8 @@ export default {
},
effects: (dispatch) => ({
async updateStarsAsync(count) {
- await new Promise(resolve => setTimeout(resolve, 1000))
- dispatch.user.updateStars(count)
+ await new Promise(resolve => setTimeout(resolve, 1000));
+ dispatch.user.updateStars(count);
},
}),
};
diff --git a/lerna.json b/lerna.json
index 74cd65b..39d21e2 100644
--- a/lerna.json
+++ b/lerna.json
@@ -1,5 +1,5 @@
{
- "version": "1.1.2",
+ "version": "1.1.3",
"npmClient": "yarn",
"useWorkspaces": true,
"packages": [
diff --git a/package.json b/package.json
index 45cd0a5..8005a12 100644
--- a/package.json
+++ b/package.json
@@ -15,7 +15,7 @@
"sync": "ts-node ./scripts/sync.ts",
"owner": "ts-node ./scripts/owner.ts",
"clean": "lerna clean --yes && rimraf packages/*/lib",
- "lint": "eslint --cache --ext .js,.jsx,.ts ./",
+ "lint": "eslint --cache --ext .js,.jsx,.ts,.tsx ./",
"lint:fix": "npm run lint -- --fix"
},
"husky": {
diff --git a/packages/create-ice/package.json b/packages/create-ice/package.json
index 1319062..ad554cc 100644
--- a/packages/create-ice/package.json
+++ b/packages/create-ice/package.json
@@ -1,6 +1,6 @@
{
"name": "create-ice",
- "version": "1.1.2",
+ "version": "1.1.3",
"description": "npm init ice",
"author": "ice-admin@alibaba-inc.com",
"homepage": "",
diff --git a/packages/create-ice/src/index.ts b/packages/create-ice/src/index.ts
index c67f4dc..5ddd402 100644
--- a/packages/create-ice/src/index.ts
+++ b/packages/create-ice/src/index.ts
@@ -1,10 +1,10 @@
#!/usr/bin/env node
import * as path from 'path';
import { log } from 'ice-npm-utils';
-import * as fs from 'fs-extra'
+import * as fs from 'fs-extra';
import create from './create';
-const pkgContent = fs.readJSONSync(path.join(__dirname, '..', 'package.json'))
+const pkgContent = fs.readJSONSync(path.join(__dirname, '..', 'package.json'));
console.log('create-ice version:', pkgContent.version);
(async function() {
diff --git a/packages/icejs/package.json b/packages/icejs/package.json
index e4e647b..c4377fe 100644
--- a/packages/icejs/package.json
+++ b/packages/icejs/package.json
@@ -1,6 +1,6 @@
{
"name": "ice.js",
- "version": "1.1.2",
+ "version": "1.1.3",
"description": "command line interface and builtin plugin for icejs",
"author": "ice-admin@alibaba-inc.com",
"homepage": "",
@@ -21,16 +21,16 @@
},
"dependencies": {
"@alib/build-scripts": "^0.1.13",
- "build-plugin-ice-config": "1.1.2",
- "build-plugin-ice-core": "1.1.2",
- "build-plugin-ice-helpers": "1.1.2",
- "build-plugin-ice-logger": "1.1.2",
- "build-plugin-ice-mpa": "1.1.2",
- "build-plugin-ice-request": "1.1.2",
- "build-plugin-ice-router": "1.1.2",
- "build-plugin-ice-ssr": "1.1.2",
- "build-plugin-ice-store": "1.1.2",
- "build-plugin-react-app": "1.1.2",
+ "build-plugin-ice-config": "1.1.3",
+ "build-plugin-ice-core": "1.1.3",
+ "build-plugin-ice-helpers": "1.1.3",
+ "build-plugin-ice-logger": "1.1.3",
+ "build-plugin-ice-mpa": "1.1.3",
+ "build-plugin-ice-request": "1.1.3",
+ "build-plugin-ice-router": "1.1.3",
+ "build-plugin-ice-ssr": "1.1.3",
+ "build-plugin-ice-store": "1.1.3",
+ "build-plugin-react-app": "1.1.3",
"inquirer": "^7.1.0"
},
"engines": {
diff --git a/packages/icejs/src/index.ts b/packages/icejs/src/index.ts
index 63c4262..89a0ac3 100644
--- a/packages/icejs/src/index.ts
+++ b/packages/icejs/src/index.ts
@@ -9,17 +9,17 @@ const getBuiltInPlugins = (userConfig) => {
'build-plugin-ice-config',
'build-plugin-ice-request',
'build-plugin-ice-mpa'
- ]
+ ];
if (userConfig.ssr) {
- builtInPlugins.push('build-plugin-ice-ssr')
+ builtInPlugins.push('build-plugin-ice-ssr');
}
if (!Object.prototype.hasOwnProperty.call(userConfig, 'store') || userConfig.store !== false) {
- builtInPlugins.push('build-plugin-ice-store')
+ builtInPlugins.push('build-plugin-ice-store');
}
- return builtInPlugins
-}
+ return builtInPlugins;
+};
export = getBuiltInPlugins
diff --git a/packages/plugin-config/config/index.ts b/packages/plugin-config/config/index.ts
index 045408a..944e363 100644
--- a/packages/plugin-config/config/index.ts
+++ b/packages/plugin-config/config/index.ts
@@ -1,4 +1,4 @@
-import config from '@/config'
+import config from '@/config';
interface Config {
readonly [propName: string]: any;
@@ -6,7 +6,7 @@ interface Config {
const userConfig: Config = {
...(config.default || {}),
- ...(config[process.env.APP_MODE] || {}),
-}
+ ...(config[((typeof window !== 'undefined') && window.__app_mode__) || process.env.APP_MODE] || {}),
+};
-export default userConfig
+export default userConfig;
diff --git a/packages/plugin-config/package.json b/packages/plugin-config/package.json
index 9c2ded0..6612085 100644
--- a/packages/plugin-config/package.json
+++ b/packages/plugin-config/package.json
@@ -1,6 +1,6 @@
{
"name": "build-plugin-ice-config",
- "version": "1.1.2",
+ "version": "1.1.3",
"description": "Define application config in icejs",
"author": "ice-admin@alibaba-inc.com",
"homepage": "",
diff --git a/packages/plugin-config/src/_config.ts b/packages/plugin-config/src/_config.ts
index 22376e7..5294d46 100644
--- a/packages/plugin-config/src/_config.ts
+++ b/packages/plugin-config/src/_config.ts
@@ -1,5 +1,5 @@
const config = {
default: {},
-}
+};
-export default config
+export default config;
diff --git a/packages/plugin-config/src/index.ts b/packages/plugin-config/src/index.ts
index 6c8d8a9..4225af4 100644
--- a/packages/plugin-config/src/index.ts
+++ b/packages/plugin-config/src/index.ts
@@ -1,39 +1,39 @@
-import * as path from 'path'
-import * as fse from 'fs-extra'
-import { IPlugin } from '@alib/build-scripts'
+import * as path from 'path';
+import * as fse from 'fs-extra';
+import { IPlugin } from '@alib/build-scripts';
const plugin: IPlugin = async (api): Promise => {
- const { context, getValue, applyMethod } = api
- const { command, rootDir } = context
+ const { context, getValue, applyMethod } = api;
+ const { command, rootDir } = context;
- const configFile = `src/config.${getValue('PROJECT_TYPE')}`
+ const configFile = `src/config.${getValue('PROJECT_TYPE')}`;
async function generateConfig() {
- const exportName = 'config'
- const filePath = path.join(rootDir,configFile)
- const distPath = path.join(getValue('ICE_TEMP'), 'config.ts')
+ const exportName = 'config';
+ const filePath = path.join(rootDir,configFile);
+ const distPath = path.join(getValue('ICE_TEMP'), 'config.ts');
if (fse.existsSync(filePath)) {
- const srcPath = path.join(__dirname, '..', 'config', 'index.ts')
+ const srcPath = path.join(__dirname, '..', 'config', 'index.ts');
- await fse.copy(srcPath, distPath)
+ await fse.copy(srcPath, distPath);
// add to ice exports
- applyMethod('addIceExport', { source: `./config`, exportName })
+ applyMethod('addIceExport', { source: `./config`, exportName });
} else {
// remove config file
- applyMethod('removeIceExport', exportName)
- fse.removeSync(distPath)
+ applyMethod('removeIceExport', exportName);
+ fse.removeSync(distPath);
}
}
- generateConfig()
+ generateConfig();
if (command === 'start') {
// watch folder config file is remove or added
applyMethod('watchFileChange', configFile, async (event: string) => {
if (event === 'unlink' || event === 'add') {
- await generateConfig()
+ await generateConfig();
}
- })
+ });
}
};
-export default plugin
+export default plugin;
diff --git a/packages/plugin-core/package.json b/packages/plugin-core/package.json
index 9251281..6995bdb 100644
--- a/packages/plugin-core/package.json
+++ b/packages/plugin-core/package.json
@@ -1,6 +1,6 @@
{
"name": "build-plugin-ice-core",
- "version": "1.1.2",
+ "version": "1.1.3",
"description": "the core plugin for icejs.",
"author": "ice-admin@alibaba-inc.com",
"homepage": "",
diff --git a/packages/plugin-core/src/generator/index.ts b/packages/plugin-core/src/generator/index.ts
index 91c8d0a..3565cbb 100644
--- a/packages/plugin-core/src/generator/index.ts
+++ b/packages/plugin-core/src/generator/index.ts
@@ -1,7 +1,7 @@
-import * as path from 'path'
-import * as fse from 'fs-extra'
-import * as globby from 'globby'
-import * as ejs from 'ejs'
+import * as path from 'path';
+import * as fse from 'fs-extra';
+import * as globby from 'globby';
+import * as ejs from 'ejs';
import generateExports from '../utils/generateExports';
import checkExportData from '../utils/checkExportData';
import removeExportData from '../utils/removeExportData';
@@ -84,7 +84,7 @@ export default class Generator {
return {
[importStrKey]: importStr,
[exportStrKey]: exportStr,
- }
+ };
}
public parseRenderData() {
diff --git a/packages/plugin-core/src/generator/pageGenerator.ts b/packages/plugin-core/src/generator/pageGenerator.ts
index ac464ef..61fbe9f 100644
--- a/packages/plugin-core/src/generator/pageGenerator.ts
+++ b/packages/plugin-core/src/generator/pageGenerator.ts
@@ -1,4 +1,4 @@
-import * as path from 'path'
+import * as path from 'path';
import Generator from './index';
import getPages from '../utils/getPages';
import generateExports from '../utils/generateExports';
@@ -40,7 +40,7 @@ export default class UsePageGenerator {
return {
pageImports: importStr,
pageExports: exportStr,
- }
+ };
}
public addPageExport = (pageName: string, exportData: IExportData|IExportData[]) => {
diff --git a/packages/plugin-core/src/generator/templates/app/components/index.ts.ejs b/packages/plugin-core/src/generator/templates/app/components/index.ts.ejs
index 7785db7..72ec1e3 100644
--- a/packages/plugin-core/src/generator/templates/app/components/index.ts.ejs
+++ b/packages/plugin-core/src/generator/templates/app/components/index.ts.ejs
@@ -21,4 +21,4 @@ export {
useLocation,
useParams,
useRouteMatch
-} from 'react-router-dom'
+} from 'react-router-dom';
diff --git a/packages/plugin-core/src/generator/templates/app/createApp.tsx.ejs b/packages/plugin-core/src/generator/templates/app/createApp.tsx.ejs
index 7e03382..7fa1c82 100644
--- a/packages/plugin-core/src/generator/templates/app/createApp.tsx.ejs
+++ b/packages/plugin-core/src/generator/templates/app/createApp.tsx.ejs
@@ -1,9 +1,9 @@
-import * as React from 'react'
-import * as ReactDOM from 'react-dom'
+import * as React from 'react';
+import * as ReactDOM from 'react-dom';
import * as ReactDOMServer from 'react-dom/server';
-import * as deepmerge from 'deepmerge'
-import RuntimeModule from './runtimeModule'
-import { IAppConfig } from './types'
+import * as deepmerge from 'deepmerge';
+import RuntimeModule from './runtimeModule';
+import { IAppConfig } from './types';
<% if (globalStyle) {%>import '../<%= globalStyle %>'<% } %>
export interface IContext {
@@ -14,57 +14,57 @@ export interface IContext {
const defaultAppConfig = {
app: {
- rootId: 'ice-container',
+ rootId: 'ice-container'
},
router: {
- type: 'hash',
+ type: 'hash'
}
}
function createAppWithSSR(customConfig: IAppConfig, context: IContext) {
- const appConfig = deepmerge(defaultAppConfig, customConfig)
- appConfig.router.type = 'static'
- return renderApp(appConfig, context)
+ const appConfig = deepmerge(defaultAppConfig, customConfig);
+ appConfig.router.type = 'static';
+ return renderApp(appConfig, context);
}
-let appConfigData = {}
+let appConfigData = {};
function createApp(customConfig: IAppConfig) {
- const appConfig = deepmerge(defaultAppConfig, customConfig)
+ const appConfig = deepmerge(defaultAppConfig, customConfig);
// pass appConfig to the server
if (process.env.__IS_SERVER__) {
- appConfigData = appConfig
- return
+ appConfigData = appConfig;
+ return;
}
// client side rendering
+ // load module to run before createApp ready
+ loadStaticModules(appConfig)
+
let initialData = {}
let pageInitialProps = {}
// ssr enabled and the server has returned data
if (window.__ICE_APP_DATA__) {
- initialData = window.__ICE_APP_DATA__
- pageInitialProps = window.__ICE_PAGE_PROPS__
- renderApp(appConfig, { initialData, pageInitialProps })
+ initialData = window.__ICE_APP_DATA__;
+ pageInitialProps = window.__ICE_PAGE_PROPS__;
+ renderApp(appConfig, { initialData, pageInitialProps });
} else {
// ssr not enabled, or SSR is enabled but the server does not return data
if (appConfig.app.getInitialData) {
(async() => {
- initialData = await appConfig.app.getInitialData()
- renderApp(appConfig, { initialData, pageInitialProps })
- })()
+ initialData = await appConfig.app.getInitialData();
+ renderApp(appConfig, { initialData, pageInitialProps });
+ })();
} else {
- renderApp(appConfig)
+ renderApp(appConfig);
}
}
}
function renderApp(config: IAppConfig, context: IContext) {
const runtime = new RuntimeModule(config, <%- buildConfig %>, context)
- <% if (runtimeModules.length) {%>
- runtime.loadModlues([<% runtimeModules.forEach((modulePath) => { %>require('<%= modulePath %>'),<% }); %>])
- <% } %>
-
+ loadModlues(runtime);
const { appConfig, modifyDOMRender } = runtime
const { rootId, mountNode } = appConfig.app
const AppProvider = runtime.composeAppProvider();
@@ -78,19 +78,44 @@ function renderApp(config: IAppConfig, context: IContext) {
}
if (process.env.__IS_SERVER__) {
- return ReactDOMServer.renderToString()
+ return ReactDOMServer.renderToString();
} else {
- const appMountNode = mountNode || document.getElementById(rootId)
+ const appMountNode = mountNode || document.getElementById(rootId);
if (modifyDOMRender) {
- return modifyDOMRender({ App, appMountNode })
+ return modifyDOMRender({ App, appMountNode });
} else {
- return ReactDOM[process.env.__SSR_ENABLED__ ? 'hydrate' : 'render'](, appMountNode)
+ return ReactDOM[window.__ICE_SSR_ENABLED__ ? 'hydrate' : 'render'](, appMountNode);
}
}
}
+function loadModlues(runtime) {
+ <% if (runtimeModules.length) {%>
+ <% runtimeModules.forEach((runtimeModule) => { %>
+ <% if(!runtimeModule.staticModule){ %>
+ runtime.loadModlue(require('<%= runtimeModule.path %>'));
+ <% } %>
+ <% }) %>
+ <% } %>
+}
+
+function loadStaticModules(appConfig: IAppConfig) {
+ <% if (runtimeModules.length) {%>
+ <% runtimeModules.forEach((runtimeModule) => { %>
+ <% if(runtimeModule.staticModule){ %>
+ require('<%= runtimeModule.path %>').default({appConfig});
+ <% } %>
+ <% }) %>
+ <% } %>
+}
+
function getAppConfig() {
- return appConfigData
+ return appConfigData;
}
-export { createApp, getAppConfig, createAppWithSSR }
+export {
+ createApp,
+ createAppWithSSR,
+ getAppConfig,
+ loadStaticModules
+}
diff --git a/packages/plugin-core/src/generator/templates/app/index.ts.ejs b/packages/plugin-core/src/generator/templates/app/index.ts.ejs
index a71067f..605fd88 100644
--- a/packages/plugin-core/src/generator/templates/app/index.ts.ejs
+++ b/packages/plugin-core/src/generator/templates/app/index.ts.ejs
@@ -1,15 +1,15 @@
<%- iceImports %>
-export * from './components'
-export * from './createApp'
-export * from './types'
+export * from './components';
+export * from './createApp';
+export * from './types';
-export const APP_MODE = process.env.APP_MODE;
+export const APP_MODE = (typeof window !== 'undefined' && window.__app_mode__) || process.env.APP_MODE;
export function lazy(dynamicImport) {
return {
'__LAZY__': true,
- dynamicImport,
+ dynamicImport
};
}
diff --git a/packages/plugin-core/src/generator/templates/app/runtimeModule.tsx.ejs b/packages/plugin-core/src/generator/templates/app/runtimeModule.tsx.ejs
index 6b6959a..7de0041 100644
--- a/packages/plugin-core/src/generator/templates/app/runtimeModule.tsx.ejs
+++ b/packages/plugin-core/src/generator/templates/app/runtimeModule.tsx.ejs
@@ -69,7 +69,7 @@ class RuntimeModule {
this.wrapperRouteRegistration = [];
}
- public loadModlues(modules) {
+ public loadModlue(module) {
const runtimeAPI = {
setRenderRouter: this.setRenderRouter,
addProvider: this.addProvider,
@@ -78,16 +78,12 @@ class RuntimeModule {
wrapperRouteComponent: this.wrapperRouteComponent,
}
- if (modules && modules.length) {
- modules.forEach((module) => {
- if (module) module.default({
- ...runtimeAPI,
- appConfig: this.appConfig,
- buildConfig: this.buildConfig,
- context: this.context
- });
- })
- }
+ if (module) module.default({
+ ...runtimeAPI,
+ appConfig: this.appConfig,
+ buildConfig: this.buildConfig,
+ context: this.context
+ });
}
public setRenderRouter = (renderRouter) => {
diff --git a/packages/plugin-core/src/generator/templates/app/types.ts.ejs b/packages/plugin-core/src/generator/templates/app/types.ts.ejs
index f1b45b5..05212ae 100644
--- a/packages/plugin-core/src/generator/templates/app/types.ts.ejs
+++ b/packages/plugin-core/src/generator/templates/app/types.ts.ejs
@@ -1,4 +1,4 @@
-import React from 'react'
+import React from 'react';
<%- iceTypesImports %>
export interface IApp {
diff --git a/packages/plugin-core/src/index.ts b/packages/plugin-core/src/index.ts
index 0b3cc96..b0acc21 100644
--- a/packages/plugin-core/src/index.ts
+++ b/packages/plugin-core/src/index.ts
@@ -1,14 +1,14 @@
-import * as path from 'path'
-import * as fse from 'fs-extra'
+import * as path from 'path';
+import * as fse from 'fs-extra';
import * as chokidar from 'chokidar';
-import * as globby from 'globby'
-import Generator from './generator'
-import PageGenerator from './generator/pageGenerator'
-import getPages from './utils/getPages'
-import formatPath from './utils/formatPath'
+import * as globby from 'globby';
+import Generator from './generator';
+import PageGenerator from './generator/pageGenerator';
+import getPages from './utils/getPages';
+import formatPath from './utils/formatPath';
export default (api) => {
- const { onHook, onGetWebpackConfig, registerMethod, registerUserConfig, context, getAllPlugin, setValue, modifyUserConfig } = api
+ const { onHook, onGetWebpackConfig, registerMethod, registerUserConfig, context, getAllPlugin, setValue, modifyUserConfig } = api;
const { rootDir, command, userConfig } = context;
const iceTempPath = path.join(rootDir, '.ice');
@@ -25,7 +25,17 @@ export default (api) => {
const runtimeModules = plugins.map(({ pluginPath }) => {
const modulePath = path.join(path.dirname(pluginPath), 'module.js');
return fse.existsSync(modulePath) ? formatPath(modulePath) : false;
- }).filter(Boolean);
+ })
+ .filter(Boolean)
+ .map(pluginPath => {
+ const pkgPath = path.join(pluginPath, '../../package.json');
+ const { pluginConfig } = fse.readJSONSync(pkgPath);
+ const staticModule = (pluginConfig && pluginConfig.staticModule) || false;
+ return {
+ staticModule,
+ path: pluginPath
+ };
+ });
if (!userConfig.entry) {
// modify default entry to src/app
@@ -40,8 +50,7 @@ export default (api) => {
config.resolve.alias.set('@', path.join(rootDir, 'src'));
const defineVariables = {
- 'process.env.__IS_SERVER__': false,
- 'process.env.__SSR_ENABLED__': userConfig.ssr
+ 'process.env.__IS_SERVER__': false
};
config
.plugin('DefinePlugin')
@@ -63,10 +72,10 @@ export default (api) => {
// add babel exclude for node_modules module file
const matchExclude = (filepath) => {
- const excludes = runtimeModules.map(modulePath => {
+ const excludes = runtimeModules.map(runtimeModule => {
// add default node_modules
- if (modulePath.includes('node_modules')) {
- return formatPath(modulePath);
+ if (runtimeModule.path.includes('node_modules')) {
+ return formatPath(runtimeModule.path);
}
return false;
@@ -84,15 +93,15 @@ export default (api) => {
.exclude.clear()
.add(matchExclude);
});
- })
+ });
- const buildConfig = {}
- const BUILD_CONFIG_MAP = ['router', 'store', 'ssr']
+ const buildConfig = {};
+ const BUILD_CONFIG_MAP = ['router', 'store', 'ssr'];
Object.keys(userConfig).forEach(key => {
if (BUILD_CONFIG_MAP.includes(key)) {
- buildConfig[key] = userConfig[key]
+ buildConfig[key] = userConfig[key];
}
- })
+ });
// check global style file
const generator = new Generator({
@@ -103,7 +112,7 @@ export default (api) => {
runtimeModules,
buildConfig: JSON.stringify(buildConfig)
}
- })
+ });
const pageGenerator = new PageGenerator({
rootDir,
@@ -146,7 +155,7 @@ export default (api) => {
});
registerMethod(registerKey.replace('add', 'remove'), (removeExportName) => {
generator.removeExport(registerKey, removeExportName);
- })
+ });
});
// watch src folder
@@ -192,10 +201,10 @@ export default (api) => {
registerMethod(apiName, (code, position = 'after') => {
const { apiKey } = registerAPIs[apiName];
generator[apiKey](apiName, code, position);
- })
+ });
});
onHook(`before.${command}.run`, async () => {
await renderIce();
- })
-}
+ });
+};
diff --git a/packages/plugin-core/src/module.ts b/packages/plugin-core/src/module.ts
index e7429e0..27f79ce 100644
--- a/packages/plugin-core/src/module.ts
+++ b/packages/plugin-core/src/module.ts
@@ -1,7 +1,7 @@
const module = ({ addProvider, appConfig }) => {
if (appConfig.app && appConfig.app.addProvider) {
- addProvider(appConfig.app.addProvider)
+ addProvider(appConfig.app.addProvider);
}
-}
+};
export default module;
diff --git a/packages/plugin-core/src/utils/checkExportData.ts b/packages/plugin-core/src/utils/checkExportData.ts
index 96b3b3c..1406300 100644
--- a/packages/plugin-core/src/utils/checkExportData.ts
+++ b/packages/plugin-core/src/utils/checkExportData.ts
@@ -9,7 +9,7 @@ function checkExportData(currentList, exportData, apiName) {
`);
}
});
- })
+ });
}
export default checkExportData;
\ No newline at end of file
diff --git a/packages/plugin-core/src/utils/formatPath.ts b/packages/plugin-core/src/utils/formatPath.ts
index 6121f27..458619f 100644
--- a/packages/plugin-core/src/utils/formatPath.ts
+++ b/packages/plugin-core/src/utils/formatPath.ts
@@ -1,7 +1,7 @@
-import * as path from 'path'
+import * as path from 'path';
function formatPath(pathStr: string): string {
- return process.platform === 'win32' ? pathStr.split(path.sep).join('/') : pathStr
+ return process.platform === 'win32' ? pathStr.split(path.sep).join('/') : pathStr;
}
-export default formatPath
+export default formatPath;
diff --git a/packages/plugin-core/src/utils/generateExports.ts b/packages/plugin-core/src/utils/generateExports.ts
index 72031f2..4da88dc 100644
--- a/packages/plugin-core/src/utils/generateExports.ts
+++ b/packages/plugin-core/src/utils/generateExports.ts
@@ -6,11 +6,11 @@ function generateExports(exportList: IExportData[]) {
exportList.forEach(data => {
const { specifier, source, exportName } = data;
if (exportName && source) {
- const symbol = source.includes('types') ? ';' : ','
- importStatements.push(`import ${specifier || exportName} from '${source}';`)
+ const symbol = source.includes('types') ? ';' : ',';
+ importStatements.push(`import ${specifier || exportName} from '${source}';`);
exportStatements.push(`${exportName}${symbol}`);
} else if(source) {
- importStatements.push(`export * from '${source}';`)
+ importStatements.push(`export * from '${source}';`);
}
});
return {
diff --git a/packages/plugin-core/src/utils/getPages.ts b/packages/plugin-core/src/utils/getPages.ts
index 1946472..9d972fe 100644
--- a/packages/plugin-core/src/utils/getPages.ts
+++ b/packages/plugin-core/src/utils/getPages.ts
@@ -1,5 +1,5 @@
-import * as path from 'path'
-import * as fse from 'fs-extra'
+import * as path from 'path';
+import * as fse from 'fs-extra';
function getPages(rootDir: string): string[] {
const pagesPath = path.join(rootDir, 'src/pages');
diff --git a/packages/plugin-helpers/package.json b/packages/plugin-helpers/package.json
index 0bae063..6c48802 100644
--- a/packages/plugin-helpers/package.json
+++ b/packages/plugin-helpers/package.json
@@ -1,6 +1,6 @@
{
"name": "build-plugin-ice-helpers",
- "version": "1.1.2",
+ "version": "1.1.3",
"description": "builtin helpers in icejs",
"author": "ice-admin@alibaba-inc.com",
"homepage": "",
diff --git a/packages/plugin-icestark/package.json b/packages/plugin-icestark/package.json
index a7fe787..beae49f 100644
--- a/packages/plugin-icestark/package.json
+++ b/packages/plugin-icestark/package.json
@@ -1,6 +1,6 @@
{
"name": "build-plugin-icestark",
- "version": "1.1.2",
+ "version": "1.1.3",
"description": "Easy use `icestark` in icejs.",
"author": "ice-admin@alibaba-inc.com",
"homepage": "",
diff --git a/packages/plugin-icestark/src/module.tsx b/packages/plugin-icestark/src/module.tsx
index d689fd3..cf625eb 100644
--- a/packages/plugin-icestark/src/module.tsx
+++ b/packages/plugin-icestark/src/module.tsx
@@ -11,7 +11,7 @@ import {
import { Router } from '$ice/Router';
import DefaultLayout from '$ice/Layout';
import removeRootLayout from './runtime/removeLayout';
-import { IIceStark } from './types'
+import { IIceStark } from './types';
const { useEffect, useState } = React;
@@ -37,7 +37,7 @@ const module = ({ appConfig, addDOMRender, setRenderRouter, modifyRoutes }) => {
} else {
ReactDOM.render(, appMountNode, resolve);
}
- })
+ });
});
setRenderRouter((routes) => () => {
const routerProps = {
@@ -120,9 +120,9 @@ const module = ({ appConfig, addDOMRender, setRenderRouter, modifyRoutes }) => {
)}
);
- }
+ };
setRenderRouter(frameworkRouter);
}
-}
+};
export default module;
diff --git a/packages/plugin-icestark/src/runtime/_Router.tsx b/packages/plugin-icestark/src/runtime/_Router.tsx
index 2097660..2f8fb1e 100644
--- a/packages/plugin-icestark/src/runtime/_Router.tsx
+++ b/packages/plugin-icestark/src/runtime/_Router.tsx
@@ -1,7 +1,8 @@
import * as React from 'react';
+// eslint-disable-next-line
const Router = ({ type, routes, basename }) => {
return ();
};
-export { Router };
\ No newline at end of file
+export { Router };
diff --git a/packages/plugin-logger/package.json b/packages/plugin-logger/package.json
index fb35b71..f0f0c93 100644
--- a/packages/plugin-logger/package.json
+++ b/packages/plugin-logger/package.json
@@ -1,6 +1,6 @@
{
"name": "build-plugin-ice-logger",
- "version": "1.1.2",
+ "version": "1.1.3",
"description": "builtin logger in icejs",
"author": "ice-admin@alibaba-inc.com",
"homepage": "",
diff --git a/packages/plugin-logger/src/module.ts b/packages/plugin-logger/src/module.ts
index e3f6eae..1204d1f 100644
--- a/packages/plugin-logger/src/module.ts
+++ b/packages/plugin-logger/src/module.ts
@@ -2,8 +2,8 @@ import logger from '$ice/logger';
const module = ({ appConfig }) => {
if (appConfig.logger && appConfig.logger.level) {
- logger.setLevel(appConfig.logger.level)
+ logger.setLevel(appConfig.logger.level);
}
-}
+};
export default module;
diff --git a/packages/plugin-mpa/package.json b/packages/plugin-mpa/package.json
index 79bfa66..822c66d 100644
--- a/packages/plugin-mpa/package.json
+++ b/packages/plugin-mpa/package.json
@@ -1,6 +1,6 @@
{
"name": "build-plugin-ice-mpa",
- "version": "1.1.2",
+ "version": "1.1.3",
"description": "enable mpa project for icejs framework",
"author": "ice-admin@alibaba-inc.com",
"homepage": "",
diff --git a/packages/plugin-react-app/package.json b/packages/plugin-react-app/package.json
index 3bbd867..350143f 100644
--- a/packages/plugin-react-app/package.json
+++ b/packages/plugin-react-app/package.json
@@ -1,6 +1,6 @@
{
"name": "build-plugin-react-app",
- "version": "1.1.2",
+ "version": "1.1.3",
"description": "The basic webpack configuration for ice project",
"author": "ice-admin@alibaba-inc.com",
"main": "src/index.js",
diff --git a/packages/plugin-react-app/src/index.js b/packages/plugin-react-app/src/index.js
index 0ac7a15..ddc1a33 100644
--- a/packages/plugin-react-app/src/index.js
+++ b/packages/plugin-react-app/src/index.js
@@ -53,10 +53,14 @@ module.exports = ({
const mode = command === 'start' ? 'development' : 'production';
const config = getWebpackConfig(mode);
+ // setup DefinePlugin, HtmlWebpackPlugin and CopyWebpackPlugin out of onGetWebpackConfig
+ // in case of registerUserConfig will be excute before onGetWebpackConfig
+
// DefinePlugin
const defineVariables = {
'process.env.NODE_ENV': JSON.stringify(mode || 'development'),
'process.env.APP_MODE': JSON.stringify(appMode),
+ 'process.env.SERVER_PORT': JSON.stringify(commandArgs.port),
};
config
.plugin('DefinePlugin')
diff --git a/packages/plugin-react-app/src/userConfig/babelPlugins.js b/packages/plugin-react-app/src/userConfig/babelPlugins.js
index 711d549..1d3a588 100644
--- a/packages/plugin-react-app/src/userConfig/babelPlugins.js
+++ b/packages/plugin-react-app/src/userConfig/babelPlugins.js
@@ -14,4 +14,4 @@ module.exports = (config, babelPlugins) => {
};
});
});
-}
\ No newline at end of file
+};
\ No newline at end of file
diff --git a/packages/plugin-react-app/src/userConfig/babelPresets.js b/packages/plugin-react-app/src/userConfig/babelPresets.js
index ec6cf78..846c0d8 100644
--- a/packages/plugin-react-app/src/userConfig/babelPresets.js
+++ b/packages/plugin-react-app/src/userConfig/babelPresets.js
@@ -30,4 +30,4 @@ module.exports = (config, babelPresets) => {
};
});
});
-}
\ No newline at end of file
+};
\ No newline at end of file
diff --git a/packages/plugin-react-app/src/userConfig/entry.js b/packages/plugin-react-app/src/userConfig/entry.js
index f1b4045..ed73c57 100644
--- a/packages/plugin-react-app/src/userConfig/entry.js
+++ b/packages/plugin-react-app/src/userConfig/entry.js
@@ -15,7 +15,7 @@ const resolveEntryPath = (entry, rootDir) => {
// entry : { [name]: string | array }
module.exports = (config, value, context) => {
const { rootDir, command, userConfig } = context;
- const ignoreHtmlTemplate = command === 'build' && userConfig.ignoreHtmlTemplate
+ const ignoreHtmlTemplate = command === 'build' && userConfig.ignoreHtmlTemplate;
let entry;
if (Array.isArray(value) || typeof value === 'string') {
entry = {
diff --git a/packages/plugin-react-app/src/userConfig/ignoreHtmlTemplate.js b/packages/plugin-react-app/src/userConfig/ignoreHtmlTemplate.js
index 360854b..ceabda6 100644
--- a/packages/plugin-react-app/src/userConfig/ignoreHtmlTemplate.js
+++ b/packages/plugin-react-app/src/userConfig/ignoreHtmlTemplate.js
@@ -6,7 +6,7 @@ module.exports = (config, ignoreHtmlTemplate, context) => {
// delete multi HtmlWebpackPlugin
Object.keys(entry).forEach((entryKey) => {
config.plugins.delete(`HtmlWebpackPlugin_${entryKey}`);
- })
+ });
} else {
config.plugins.delete('HtmlWebpackPlugin');
}
diff --git a/packages/plugin-react-app/src/userConfig/injectBabel.js b/packages/plugin-react-app/src/userConfig/injectBabel.js
index c1f7177..2e70571 100644
--- a/packages/plugin-react-app/src/userConfig/injectBabel.js
+++ b/packages/plugin-react-app/src/userConfig/injectBabel.js
@@ -1,5 +1,5 @@
-const path = require('path');
const formatWinPath = require('../utils/formatWinPath');
+const addBablePlugins = require('./babelPlugins');
module.exports = (config, injectBabel) => {
if (injectBabel === 'runtime') {
@@ -31,6 +31,7 @@ module.exports = (config, injectBabel) => {
} else if (injectBabel === 'polyfill') {
const entries = config.toConfig().entry;
const rule = config.module.rule('polyfill').test(/\.jsx?|\.tsx?$/);
+ const fileList = [];
Object.keys(entries).forEach((key) => {
let addPolyfill = false;
// only include entry path
@@ -38,20 +39,17 @@ module.exports = (config, injectBabel) => {
// filter node_modules file add by plugin
if (!/node_modules/.test(entries[key][i])) {
rule.include.add(entries[key][i]);
+ fileList.push(entries[key][i]);
addPolyfill = true;
break;
}
}
if (!addPolyfill) {
rule.include.add(entries[key][0]);
+ fileList.push(entries[key][0]);
}
});
rule.use('polyfill-loader').loader(require.resolve('../utils/polyfillLoader')).options({});
-
- // add resolve modules for get core-js and regenerator-runtime
- const modulePath = require.resolve('core-js');
- const pathArr = modulePath.split('node_modules');
- pathArr.pop(); // pop file path
- config.resolve.modules.prepend(path.join(pathArr.join('node_modules'), 'node_modules'));
+ addBablePlugins(config, [[require.resolve('../utils/babelPluginCorejsLock.js'), { fileList }]]);
}
};
diff --git a/packages/plugin-react-app/src/utils/babelPluginCorejsLock.js b/packages/plugin-react-app/src/utils/babelPluginCorejsLock.js
new file mode 100644
index 0000000..85792f4
--- /dev/null
+++ b/packages/plugin-react-app/src/utils/babelPluginCorejsLock.js
@@ -0,0 +1,22 @@
+const path = require('path');
+
+const coreJSPath = path.dirname(require.resolve('core-js/package.json'));
+// eslint-disable-next-line no-unused-vars
+module.exports = ({ types }, { fileList }) => {
+ return {
+ visitor: {
+ ImportDeclaration(nodePath, state) {
+ const entryFile = fileList.find((filePath) => {
+ // filePath may not have an extension
+ return filePath.includes((state.filename || '').replace(/\.[^/.]+$/, ''));
+ });
+ if (entryFile) {
+ const { node } = nodePath;
+ if (node.source.value.startsWith('core-js/')) {
+ node.source.value = node.source.value.replace('core-js/', `${coreJSPath}/`);
+ }
+ }
+ },
+ },
+ };
+};
diff --git a/packages/plugin-rematch/package.json b/packages/plugin-rematch/package.json
index eef31df..ee52b0e 100644
--- a/packages/plugin-rematch/package.json
+++ b/packages/plugin-rematch/package.json
@@ -1,6 +1,6 @@
{
"name": "build-plugin-ice-rematch",
- "version": "1.1.2",
+ "version": "1.1.3",
"description": "Easy use `rematch` in icejs",
"author": "ice-admin@alibaba-inc.com",
"homepage": "",
diff --git a/packages/plugin-rematch/src/_store.ts b/packages/plugin-rematch/src/_store.ts
index 59f6267..a40605a 100644
--- a/packages/plugin-rematch/src/_store.ts
+++ b/packages/plugin-rematch/src/_store.ts
@@ -2,4 +2,4 @@ const stores = {};
export {
stores,
-}
+};
diff --git a/packages/plugin-rematch/src/module.tsx b/packages/plugin-rematch/src/module.tsx
index 0d97e8e..8d1a14d 100644
--- a/packages/plugin-rematch/src/module.tsx
+++ b/packages/plugin-rematch/src/module.tsx
@@ -1,6 +1,6 @@
import * as React from 'react';
import { Provider } from 'react-redux';
-import { init } from '@rematch/core'
+import { init } from '@rematch/core';
import { stores } from '$ice/store';
export default ({ addProvider, appConfig }) => {
@@ -18,6 +18,6 @@ export default ({ addProvider, appConfig }) => {
const StoreProvider = ({children}) => {
return {children};
- }
+ };
addProvider(StoreProvider);
-}
+};
diff --git a/packages/plugin-request/package.json b/packages/plugin-request/package.json
index f264f82..03b9041 100644
--- a/packages/plugin-request/package.json
+++ b/packages/plugin-request/package.json
@@ -1,6 +1,6 @@
{
"name": "build-plugin-ice-request",
- "version": "1.1.2",
+ "version": "1.1.3",
"description": "request for build-plugin-ice-request",
"author": "ice-admin@alibaba-inc.com",
"homepage": "",
@@ -18,6 +18,9 @@
"axios": "^0.19.2",
"fs-extra": "^8.1.0"
},
+ "pluginConfig": {
+ "staticModule": true
+ },
"publishConfig": {
"registry": "http://registry.npmjs.com/"
},
diff --git a/packages/plugin-request/request/axiosInstance.ts b/packages/plugin-request/request/axiosInstance.ts
index 56e977c..69f70e0 100644
--- a/packages/plugin-request/request/axiosInstance.ts
+++ b/packages/plugin-request/request/axiosInstance.ts
@@ -1,9 +1,9 @@
-import axios from 'axios'
+import axios from 'axios';
// https://github.com/axios/axios#request-config
const DEFAULE_CONFIG = {
-}
+};
-const axiosInstance = axios.create(DEFAULE_CONFIG)
+const axiosInstance = axios.create(DEFAULE_CONFIG);
-export default axiosInstance
+export default axiosInstance;
diff --git a/packages/plugin-request/request/request.ts b/packages/plugin-request/request/request.ts
index c5ecdd3..9e97beb 100644
--- a/packages/plugin-request/request/request.ts
+++ b/packages/plugin-request/request/request.ts
@@ -1,6 +1,6 @@
-import { AxiosRequestConfig, AxiosResponse } from 'axios'
-import * as utils from 'axios/lib/utils'
-import axiosInstance from './axiosInstance'
+import { AxiosRequestConfig, AxiosResponse } from 'axios';
+import * as utils from 'axios/lib/utils';
+import axiosInstance from './axiosInstance';
export interface IRequestProps {
get: (url: string, config?: AxiosRequestConfig) => Promise>;
@@ -19,13 +19,13 @@ interface IRequest extends IRequestProps {
const request = async function (options) {
try {
- const response = await axiosInstance(options)
- return response.data
+ const response = await axiosInstance(options);
+ return response.data;
} catch (error) {
- console.error(error)
- throw error
+ console.error(error);
+ throw error;
}
-}
+};
// Provide aliases for supported request methods
utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
@@ -47,4 +47,4 @@ utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
};
});
-export default request as IRequest
+export default request as IRequest;
diff --git a/packages/plugin-request/request/types.ts b/packages/plugin-request/request/types.ts
index dfaa741..bb488db 100644
--- a/packages/plugin-request/request/types.ts
+++ b/packages/plugin-request/request/types.ts
@@ -1,4 +1,4 @@
-import { AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios'
+import { AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios';
export interface IInterceptorRequest {
onConfig?: (config: AxiosRequestConfig) => AxiosRequestConfig;
diff --git a/packages/plugin-request/request/useRequest.ts b/packages/plugin-request/request/useRequest.ts
index ae5cdbe..2f14de8 100644
--- a/packages/plugin-request/request/useRequest.ts
+++ b/packages/plugin-request/request/useRequest.ts
@@ -1,6 +1,6 @@
-import { useReducer } from 'react'
-import { AxiosRequestConfig } from 'axios'
-import axiosInstance from './axiosInstance'
+import { useReducer } from 'react';
+import { AxiosRequestConfig } from 'axios';
+import axiosInstance from './axiosInstance';
/**
* Hooks to make ajax request
@@ -18,7 +18,7 @@ function useRequest(options: AxiosRequestConfig) {
loading: false,
error: null
};
- const [state, dispatch] = useReducer(requestReducer, initialState)
+ const [state, dispatch] = useReducer(requestReducer, initialState);
/**
* Method to make request manually
@@ -33,19 +33,19 @@ function useRequest(options: AxiosRequestConfig) {
const response = await axiosInstance({
...options,
...config
- })
+ });
dispatch({
type: 'success',
data: response.data
- })
- return response.data
+ });
+ return response.data;
} catch (error) {
dispatch({
type: 'error',
error
- })
- throw error
+ });
+ throw error;
}
}
@@ -68,13 +68,13 @@ function requestReducer(state, action) {
data: null,
error: null,
loading: true
- }
+ };
case 'success':
return {
data: action.data,
error: null,
loading: false
- }
+ };
case 'error':
return {
data: null,
@@ -86,8 +86,8 @@ function requestReducer(state, action) {
data: null,
error: null,
loading: false
- }
+ };
}
}
-export default useRequest
+export default useRequest;
diff --git a/packages/plugin-request/src/_axiosInstance.ts b/packages/plugin-request/src/_axiosInstance.ts
index 90709f7..71616cd 100644
--- a/packages/plugin-request/src/_axiosInstance.ts
+++ b/packages/plugin-request/src/_axiosInstance.ts
@@ -1,7 +1,7 @@
-import axios from 'axios'
+import axios from 'axios';
-const DEFAULE_CONFIG = {}
+const DEFAULE_CONFIG = {};
-const axiosInstance = axios.create(DEFAULE_CONFIG)
+const axiosInstance = axios.create(DEFAULE_CONFIG);
-export default axiosInstance
+export default axiosInstance;
diff --git a/packages/plugin-request/src/index.ts b/packages/plugin-request/src/index.ts
index 01dab9b..cddc5a2 100644
--- a/packages/plugin-request/src/index.ts
+++ b/packages/plugin-request/src/index.ts
@@ -1,24 +1,24 @@
-import * as path from 'path'
-import * as fse from 'fs-extra'
+import * as path from 'path';
+import * as fse from 'fs-extra';
export default async function (api) {
- const { getValue, applyMethod, onGetWebpackConfig } = api
- const srcPath = path.join(__dirname, '..', 'request')
- const distPath = path.join(getValue('ICE_TEMP'), 'request')
+ const { getValue, applyMethod, onGetWebpackConfig } = api;
+ const srcPath = path.join(__dirname, '..', 'request');
+ const distPath = path.join(getValue('ICE_TEMP'), 'request');
// move requst to .ice/request
- await fse.copy(srcPath, distPath)
+ await fse.copy(srcPath, distPath);
// .ice/index.ts:
// export * from './request';
- applyMethod('addIceExport', { source: './request/request', exportName: 'request' })
- applyMethod('addIceExport', { source: './request/useRequest', exportName: 'useRequest' })
+ applyMethod('addIceExport', { source: './request/request', exportName: 'request' });
+ applyMethod('addIceExport', { source: './request/useRequest', exportName: 'useRequest' });
// add iceTypes exports
applyMethod('addIceTypesExport', { source: './request/types', specifier: '{ IRequest }', exportName: 'request?: IRequest' });
onGetWebpackConfig((config) => {
// add alias for module.ts use $ice/axiosInstance
- config.resolve.alias.set('$ice/axiosInstance', path.join(distPath, 'axiosInstance.ts'))
- })
+ config.resolve.alias.set('$ice/axiosInstance', path.join(distPath, 'axiosInstance.ts'));
+ });
}
diff --git a/packages/plugin-request/src/module.ts b/packages/plugin-request/src/module.ts
index 672d6cb..9c2937e 100644
--- a/packages/plugin-request/src/module.ts
+++ b/packages/plugin-request/src/module.ts
@@ -1,13 +1,13 @@
-import axiosInstance from '$ice/axiosInstance'
+import axiosInstance from '$ice/axiosInstance';
const module = ({ appConfig }) => {
if (appConfig.request) {
- const { request = {} } = appConfig
- const { interceptors = {}, ...requestOptions } = request
+ const { request = {} } = appConfig;
+ const { interceptors = {}, ...requestOptions } = request;
Object.keys(requestOptions).forEach(key => {
- axiosInstance.defaults[key] = requestOptions[key]
- })
+ axiosInstance.defaults[key] = requestOptions[key];
+ });
// Add a request interceptor
if (interceptors.request) {
@@ -25,6 +25,6 @@ const module = ({ appConfig }) => {
);
}
}
-}
+};
-export default module
+export default module;
diff --git a/packages/plugin-router/package.json b/packages/plugin-router/package.json
index e1bc505..0cddf96 100644
--- a/packages/plugin-router/package.json
+++ b/packages/plugin-router/package.json
@@ -1,6 +1,6 @@
{
"name": "build-plugin-ice-router",
- "version": "1.1.2",
+ "version": "1.1.3",
"description": "build-plugin-ice-router",
"author": "ice-admin@alibaba-inc.com",
"homepage": "",
diff --git a/packages/plugin-router/src/collector/amender.ts b/packages/plugin-router/src/collector/amender.ts
index 402c60c..791ad2b 100644
--- a/packages/plugin-router/src/collector/amender.ts
+++ b/packages/plugin-router/src/collector/amender.ts
@@ -126,5 +126,5 @@ export default function amender(
) {
addDefaultLayout(rootDir, routersTempPath, routesCollect);
addDefault404(rootDir, routersTempPath, routesCollect);
- loopAmend('', routesCollect)
+ loopAmend('', routesCollect);
}
\ No newline at end of file
diff --git a/packages/plugin-router/src/collector/splicer.ts b/packages/plugin-router/src/collector/splicer.ts
index 1519c0e..8e0b8ab 100644
--- a/packages/plugin-router/src/collector/splicer.ts
+++ b/packages/plugin-router/src/collector/splicer.ts
@@ -67,7 +67,7 @@ ${indentTabs}{
}
// nest object end
payload.nestSlice.push(`
-${indentTabs}},`)
+${indentTabs}},`);
});
// nest the array end
@@ -83,5 +83,5 @@ export default function splicer(routesCollect: ICollectItem[], routerOptions) {
if (routerOptions.lazy) {
importAhead = 'import { lazy } from \'ice\';\n';
}
- return `${importAhead}${payload.nestImports.join('')}\nexport default ${payload.nestSlice.join('')};`
+ return `${importAhead}${payload.nestImports.join('')}\nexport default ${payload.nestSlice.join('')};`;
}
diff --git a/packages/plugin-router/src/collector/walker.ts b/packages/plugin-router/src/collector/walker.ts
index e4f273a..9ab70ca 100644
--- a/packages/plugin-router/src/collector/walker.ts
+++ b/packages/plugin-router/src/collector/walker.ts
@@ -108,7 +108,7 @@ export default function walker({
...pageConfig,
component: layoutName,
isLayoutLike
- }
+ };
layoutMap[routePath] = pageConfig;
} else {
routesMap[routePath] = pageConfig;
diff --git a/packages/plugin-router/src/index.ts b/packages/plugin-router/src/index.ts
index ff47f79..bd3f458 100644
--- a/packages/plugin-router/src/index.ts
+++ b/packages/plugin-router/src/index.ts
@@ -1,6 +1,6 @@
import * as path from 'path';
import * as fse from 'fs-extra';
-import { IPlugin } from '@alib/build-scripts'
+import { IPlugin } from '@alib/build-scripts';
import { IRouterOptions } from './types';
import walker from './collector/walker';
@@ -24,7 +24,7 @@ const plugin: IPlugin = ({ context, onGetWebpackConfig, getValue, applyMethod, r
if (isMpa) {
// if is mpa use empty router file
fse.writeFileSync(routersTempPath, 'export default [];', 'utf-8');
- routeConfigPath = routersTempPath
+ routeConfigPath = routersTempPath;
}
const hasRouteFile = fse.existsSync(routeConfigPath);
@@ -64,6 +64,6 @@ const plugin: IPlugin = ({ context, onGetWebpackConfig, getValue, applyMethod, r
});
}
}
-}
+};
export default plugin;
diff --git a/packages/plugin-router/src/module.tsx b/packages/plugin-router/src/module.tsx
index bf23382..5e53aa0 100644
--- a/packages/plugin-router/src/module.tsx
+++ b/packages/plugin-router/src/module.tsx
@@ -4,27 +4,35 @@ import { Router } from './runtime/Router';
import formatRoutes, { wrapperPage, wrapperPageWithSSR } from './runtime/formatRoutes';
const module = ({ setRenderRouter, appConfig, modifyRoutes, wrapperRouteComponent, buildConfig, context }) => {
- const { router = {} } = appConfig;
+ const { router: appConfigRouter = {} } = appConfig;
+
// plugin-router 内置确保了 defaultRoutes 最先被添加
modifyRoutes(() => {
- return formatRoutes(router.routes || defaultRoutes, '');
+ return formatRoutes(appConfigRouter.routes || defaultRoutes, '');
});
+
const wrapperPageFn = process.env.__IS_SERVER__ ? wrapperPageWithSSR(context, defaultRoutes) : wrapperPage;
- wrapperRouteComponent(wrapperPageFn)
- if (router.modifyRoutes) {
- modifyRoutes(router.modifyRoutes);
+ wrapperRouteComponent(wrapperPageFn);
+ if (appConfigRouter.modifyRoutes) {
+ modifyRoutes(appConfigRouter.modifyRoutes);
}
- const { router: buildConfigRouter } = buildConfig
+ const lazy = buildConfig.router && buildConfig.router.lazy;
const renderRouter = (routes) => () => {
- const routerProps = {
- ...router,
+ let routerProps = {
+ ...appConfigRouter,
routes,
- lazy: buildConfigRouter && buildConfigRouter.lazy,
+ lazy
};
+
+ if (process.env.__IS_SERVER__) {
+ const { pathname, staticContext = {} } = context;
+ routerProps = Object.assign({}, routerProps, { location: pathname, context: staticContext });
+ }
+
return ;
- }
+ };
setRenderRouter(renderRouter);
-}
+};
export default module;
diff --git a/packages/plugin-router/src/runtime/Router.tsx b/packages/plugin-router/src/runtime/Router.tsx
index 55d7606..6cf1e0f 100644
--- a/packages/plugin-router/src/runtime/Router.tsx
+++ b/packages/plugin-router/src/runtime/Router.tsx
@@ -11,16 +11,16 @@ import {
RouteComponentProps
} from 'react-router-dom';
-import { RoutesProps, RouterProps, IRouteWrapper, IDynamicImportComponent, RouteItemProps, IRenderRouteProps } from '../types'
+import { RoutesProps, RouterProps, IRouteWrapper, IDynamicImportComponent, RouteItemProps, IRenderRouteProps } from '../types';
function wrapperRoute(component, routerWrappers) {
return (routerWrappers || []).reduce((acc, curr) => {
- const compose = curr(acc)
+ const compose = curr(acc);
if (acc.pageConfig) {
- compose.pageConfig = acc.pageConfig
+ compose.pageConfig = acc.pageConfig;
}
if (acc.getInitialProps) {
- compose.getInitialProps = acc.getInitialProps
+ compose.getInitialProps = acc.getInitialProps;
}
return compose;
}, component);
@@ -30,7 +30,7 @@ function getRouteComponent(component, routerWrappers?: IRouteWrapper[]) {
const { __LAZY__, dynamicImport }: IDynamicImportComponent = component || {};
return __LAZY__ ? React.lazy(() => dynamicImport().then((m) => {
if (routerWrappers && routerWrappers.length) {
- return { ...m, default: wrapperRoute(m.default, routerWrappers) }
+ return { ...m, default: wrapperRoute(m.default, routerWrappers) };
}
return m;
})) : wrapperRoute(component, routerWrappers);
@@ -83,9 +83,9 @@ function Routes({ routes, fallback }: RoutesProps) {
} else {
const { component: RouteComponent, ...others } = route;
// React does not currently support Suspense when components are being server-side rendered
- // process.env.__IS_SERVER__ = React.RenderToString()
- // process.env.__SSR_ENABLED__ = React.hydrate()
- const RenderComponent = process.env.__IS_SERVER__ || process.env.__SSR_ENABLED__
+ // process.env.__IS_SERVER__: React.RenderToString()
+ // window.__ICE_SSR_ENABLED__: React.hydrate()
+ const RenderComponent = process.env.__IS_SERVER__ || (window as any).__ICE_SSR_ENABLED__
? (props: RouteComponentProps) =>
: (props: RouteComponentProps) => {
return (
@@ -93,7 +93,7 @@ function Routes({ routes, fallback }: RoutesProps) {
);
- }
+ };
return (
{
const ServerWrapperedPage = (props) => {
- const MatchedPageComponent = getComponentByPath(routes, context.pathname)
+ const MatchedPageComponent = getComponentByPath(routes, context.pathname);
return ;
- }
- return ServerWrapperedPage
- }
+ };
+ return ServerWrapperedPage;
+ };
return WrapperPageFn;
}
@@ -53,17 +53,17 @@ export function wrapperPage(PageComponent) {
// And don't need to re-request to switch routes
// Set the data to null after use, otherwise other pages will use
if ((window as any).__ICE_PAGE_PROPS__) {
- (window as any).__ICE_PAGE_PROPS__ = null
+ (window as any).__ICE_PAGE_PROPS__ = null;
} else if (PageComponent.getInitialProps) {
// When the server does not return data, the client calls getinitialprops
(async () => {
const result = await PageComponent.getInitialProps();
setData(result);
- })()
+ })();
}
}, []);
return ;
- }
+ };
return RouterWrapperedPage;
}
diff --git a/packages/plugin-router/src/utils/index.ts b/packages/plugin-router/src/utils/index.ts
index 7c68d02..be2419a 100644
--- a/packages/plugin-router/src/utils/index.ts
+++ b/packages/plugin-router/src/utils/index.ts
@@ -30,36 +30,36 @@ export function getJsFilePathsIn(filePath: string) {
}
export function isDynamicPath(str: string) {
- return typeof str === 'string' && /^\$\w+/.test(str)
+ return typeof str === 'string' && /^\$\w+/.test(str);
}
export function transformDynamicPath(str: string) {
- return str.replace(/^\$/, ':')
+ return str.replace(/^\$/, ':');
}
export function isOptionalDynamicPath(str: string) {
- return typeof str === 'string' && /^\$\w+\$$/.test(str)
+ return typeof str === 'string' && /^\$\w+\$$/.test(str);
}
export function transformOptionalDynamicPath(str: string) {
- return transformDynamicPath(str).replace(/\$$/, '?')
+ return transformDynamicPath(str).replace(/\$$/, '?');
}
export function isNestFileName(str: string) {
- return typeof str === 'string' && /^_\w+/.test(str)
+ return typeof str === 'string' && /^_\w+/.test(str);
}
export function upperCaseFirst(str: string) {
- if (typeof str !== 'string') return ''
- return str.charAt(0).toUpperCase() + str.slice(1)
+ if (typeof str !== 'string') return '';
+ return str.charAt(0).toUpperCase() + str.slice(1);
}
export function transformComponentName(str: string) {
- return str.replace(/-/g, '$$$')
+ return str.replace(/-/g, '$$$');
}
export function fillTabWith(count: number) {
- return new Array(count).fill(' ').join('')
+ return new Array(count).fill(' ').join('');
}
export function formatPathForWin(strPath: string) {
diff --git a/packages/plugin-ssr/package.json b/packages/plugin-ssr/package.json
index 65aeae9..0c6378c 100644
--- a/packages/plugin-ssr/package.json
+++ b/packages/plugin-ssr/package.json
@@ -1,6 +1,6 @@
{
"name": "build-plugin-ice-ssr",
- "version": "1.1.2",
+ "version": "1.1.3",
"description": "ssr plugin",
"author": "ice-admin@alibaba-inc.com",
"homepage": "",
@@ -26,6 +26,7 @@
},
"dependencies": {
"build-scripts-config": "^0.1.6",
+ "chalk": "^3.0.0",
"cheerio": "^1.0.0-rc.3",
"ejs": "^3.0.1",
"html-minifier": "^4.0.0"
diff --git a/packages/plugin-ssr/src/index.ts b/packages/plugin-ssr/src/index.ts
index 63aae56..7b9857c 100644
--- a/packages/plugin-ssr/src/index.ts
+++ b/packages/plugin-ssr/src/index.ts
@@ -1,48 +1,56 @@
-import * as path from 'path'
-import * as fse from 'fs-extra'
-import * as ejs from 'ejs'
+import * as path from 'path';
+import * as fse from 'fs-extra';
+import * as ejs from 'ejs';
import { minify } from 'html-minifier';
-import { getWebpackConfig } from 'build-scripts-config'
+import { getWebpackConfig } from 'build-scripts-config';
const plugin = async (api): Promise => {
- const { context, registerTask, getValue, onGetWebpackConfig, onHook } = api
- const { rootDir, command, webpack, userConfig } = context
- const ICE_TEMP = getValue('ICE_TEMP')
- const ssrEntry = path.join(ICE_TEMP, 'server.ts')
+ const { context, registerTask, getValue, onGetWebpackConfig, onHook, log } = api;
+ const { rootDir, command, webpack, userConfig, commandArgs } = context;
+ const ICE_TEMP = getValue('ICE_TEMP');
+ const ssrEntry = path.join(ICE_TEMP, 'server.ts');
// Note: Compatible plugins to modify configuration
- const buildDir = path.join(rootDir, userConfig.outputDir)
- const serverDir = path.join(buildDir, 'server')
- const serverFilename = 'index.js'
+ const buildDir = path.join(rootDir, userConfig.outputDir);
+ const serverDir = path.join(buildDir, 'server');
+ const serverFilename = 'index.js';
- const templatePath = path.join(__dirname, '../src/server.ts.ejs')
- const templateContent = fse.readFileSync(templatePath, 'utf-8')
- const content = ejs.render(templateContent)
- fse.ensureDirSync(path.dirname(ssrEntry))
- fse.writeFileSync(ssrEntry, content, 'utf-8')
+ const templatePath = path.join(__dirname, '../src/server.ts.ejs');
+ const templateContent = fse.readFileSync(templatePath, 'utf-8');
+ const content = ejs.render(templateContent);
+ fse.ensureDirSync(path.dirname(ssrEntry));
+ fse.writeFileSync(ssrEntry, content, 'utf-8');
- const mode = command === 'start' ? 'development' : 'production'
- const webpackConfig = getWebpackConfig(mode)
- registerTask('ssr', webpackConfig)
+ const mode = command === 'start' ? 'development' : 'production';
+ const webpackConfig = getWebpackConfig(mode);
+ // config DefinePlugin out of onGetWebpackConfig, so it can be modified by user config
+ webpackConfig
+ .plugin('DefinePlugin')
+ .use(webpack.DefinePlugin, [{
+ 'process.env.APP_MODE': JSON.stringify(commandArgs.mode || command),
+ 'process.env.SERVER_PORT': JSON.stringify(commandArgs.port),
+ }]);
+ registerTask('ssr', webpackConfig);
onGetWebpackConfig('ssr', (config) => {
- config.entryPoints.clear()
+ config.entryPoints.clear();
- config.entry('server').add(ssrEntry)
+ config.entry('server').add(ssrEntry);
- config.target('node')
+ config.target('node');
- config.name('ssr')
+ config.name('ssr');
+
+ config.module
+ .rule('polyfill')
+ .include.add(ssrEntry);
config
.plugin('DefinePlugin')
- .use(webpack.DefinePlugin, [{
- 'process.env.__IS_SERVER__': true
- }])
- .end()
+ .tap(([args]) => [{ ...args, 'process.env.__IS_SERVER__': true }]);
config.plugins.delete('MiniCssExtractPlugin');
['scss', 'scss-module', 'css', 'css-module', 'less', 'less-module'].forEach((rule) => {
if (config.module.rules.get(rule)) {
- config.module.rule(rule).uses.delete('MiniCssExtractPlugin.loader')
+ config.module.rule(rule).uses.delete('MiniCssExtractPlugin.loader');
config.module
.rule(rule)
.use('css-loader')
@@ -51,14 +59,14 @@ const plugin = async (api): Promise => {
onlyLocals: true
}));
}
- })
+ });
config.output
.path(serverDir)
.filename(serverFilename)
.publicPath('/')
- .libraryTarget('commonjs2')
-
+ .libraryTarget('commonjs2');
+
// in case of app with client and server code, webpack-node-externals is helpful to reduce server bundle size
// while by bundle all dependencies, developers do not need to concern about the dependencies of server-side
// TODO: support options to enable nodeExternals
@@ -66,22 +74,26 @@ const plugin = async (api): Promise => {
config.externals([]);
async function serverRender(res, req) {
- const htmlTemplate = fse.readFileSync(path.join(buildDir, 'index.html'), 'utf8')
+ const htmlTemplate = fse.readFileSync(path.join(buildDir, 'index.html'), 'utf8');
console.log('[SSR]', 'start server render');
const requirePath = path.join(serverDir, serverFilename);
delete require.cache[requirePath];
// eslint-disable-next-line
const serverRender = require(requirePath)
- const html = await serverRender.default({ pathname: req.path, htmlTemplate })
+ const { html, error } = await serverRender.default({ pathname: req.path, htmlTemplate });
+ if (error) {
+ log.error('[SSR] Server side rendering error, downgraded to client side rendering');
+ log.error(error);
+ }
console.log('[SSR]', `output html content\n${html}\n`);
- res.send(html)
+ res.send(html);
}
if (command === 'start') {
config.devServer
.hot(true)
.writeToDisk((filePath) => {
- return /(server\/index\.js|index.html)$/.test(filePath)
- })
+ return /(server\/index\.js|index.html)$/.test(filePath);
+ });
let serverReady = false;
let httpResponseQueue = [];
const originalDevServeBefore = config.devServer.get('before');
@@ -103,8 +115,8 @@ const plugin = async (api): Promise => {
httpResponseQueue = [];
}
});
- })
-
+ });
+
const pattern = /^\/?((?!\.(js|css|map|json|png|jpg|jpeg|gif|svg|eot|woff2|ttf|ico)).)*$/;
app.get(pattern, async (req, res) => {
if (serverReady) {
@@ -116,19 +128,16 @@ const plugin = async (api): Promise => {
});
});
}
+ });
- if (command === 'build') {
- config.optimization.minimize(false)
- onHook('after.build.compile', () => {
- const serverFilePath = path.join(serverDir, serverFilename)
- const htmlFilePath = path.join(buildDir, 'index.html')
- const bundle = fse.readFileSync(serverFilePath, 'utf-8')
- const html = fse.readFileSync(htmlFilePath, 'utf-8')
- const minifedHtml = minify(html, { collapseWhitespace: true, })
- const newBundle = bundle.replace(/__ICE_SERVER_HTML_TEMPLATE__/, minifedHtml)
- fse.writeFileSync(serverFilePath, newBundle, 'utf-8')
- });
- }
+ onHook('after.build.compile', () => {
+ const serverFilePath = path.join(serverDir, serverFilename);
+ const htmlFilePath = path.join(buildDir, 'index.html');
+ const bundle = fse.readFileSync(serverFilePath, 'utf-8');
+ const html = fse.readFileSync(htmlFilePath, 'utf-8');
+ const minifedHtml = minify(html, { collapseWhitespace: true, quoteCharacter: "'" });
+ const newBundle = bundle.replace(/__ICE_SERVER_HTML_TEMPLATE__/, minifedHtml);
+ fse.writeFileSync(serverFilePath, newBundle, 'utf-8');
});
};
diff --git a/packages/plugin-ssr/src/server.ts.ejs b/packages/plugin-ssr/src/server.ts.ejs
index 2ba3817..6e2ebbb 100644
--- a/packages/plugin-ssr/src/server.ts.ejs
+++ b/packages/plugin-ssr/src/server.ts.ejs
@@ -1,38 +1,63 @@
-import * as cheerio from 'cheerio'
-import { matchPath } from 'ice'
-import { createAppWithSSR, getAppConfig } from './createApp'
-import routes from '@/routes'
-import '@/app'
+import * as cheerio from 'cheerio';
+import { matchPath } from 'ice';
+import { createAppWithSSR, getAppConfig, loadStaticModules } from './createApp';
+import routes from '@/routes';
+import '@/app';
+
+const chalk = require('chalk');
// appConfig set by: import '@/app'
-const appConfig = getAppConfig()
+const appConfig = getAppConfig();
+
+const serverRender = async ({ context, pathname, initialData, htmlTemplate }) => {
+ // get html template
+ const $ = cheerio.load(htmlTemplate || '__ICE_SERVER_HTML_TEMPLATE__');
+
+ // load module to run before createApp ready
+ loadStaticModules(appConfig);
-const serverRender = async ({ pathname, initialData, htmlTemplate }) => {
+ let pageInitialProps;
+ let error;
- if (!initialData) {
- const getInitialData = appConfig.app && appConfig.app.getInitialData
- if (getInitialData) {
- console.log('[SSR]', 'getting initial data of app');
+ try {
+ // get initial data
+ if (!initialData) {
+ const getInitialData = appConfig.app && appConfig.app.getInitialData;
+ if (getInitialData) {
+ console.log('[SSR]', 'getting initial data of app');
+ initialData = await getInitialData();
+ }
+ }
+
+ // get page initial props
+ const PageComponent = getComponentByPath(routes, pathname);
+ const getInitialProps = PageComponent && PageComponent.getInitialProps;
+ if (getInitialProps) {
+ console.log('[SSR]', 'getting initial props of page component');
+ pageInitialProps = await getInitialProps();
}
- initialData = getInitialData ? await getInitialData() : {}
- }
- const PageComponent = getComponentByPath(routes, pathname)
- const getInitialProps = PageComponent && PageComponent.getInitialProps;
- if (getInitialProps) {
- console.log('[SSR]', 'getting initial props of page component');
+ // generate bundle content and register global variables in html
+ console.log('[SSR]', 'generating html content');
+ const bundleContent = createAppWithSSR(appConfig, {
+ staticContext: context,
+ pathname,
+ initialData,
+ pageInitialProps
+ });
+ $('#ice-container').append(bundleContent);
+ $('head').append(``)
+ } catch (e) {
+ error = e;
+ logError('[SSR] generate html template error');
}
- const pageInitialProps = getInitialProps ? await getInitialProps() : {}
- console.log('[SSR]', 'generating html content');
- const bundleContent = createAppWithSSR(appConfig, { pathname, pageInitialProps, initialData })
- const $ = cheerio.load(htmlTemplate || '__ICE_SERVER_HTML_TEMPLATE__')
- $('#ice-container').append(bundleContent)
- $('head').append(``)
- const html = $.html()
- return html
+
+ const html = $.html();
+ return { html, error };
}
function getComponentByPath(routes, currPath) {
@@ -46,4 +71,11 @@ function getComponentByPath(routes, currPath) {
return matchedRoute && matchedRoute.component;
}
-export default serverRender
+function logError(msg) {
+ console.log(
+ chalk.red('ERR!'),
+ chalk.magenta(msg),
+ );
+}
+
+export default serverRender;
diff --git a/packages/plugin-store/package.json b/packages/plugin-store/package.json
index 5dfed88..f77005d 100644
--- a/packages/plugin-store/package.json
+++ b/packages/plugin-store/package.json
@@ -1,6 +1,6 @@
{
"name": "build-plugin-ice-store",
- "version": "1.1.2",
+ "version": "1.1.3",
"description": "builtin `icestore` in icejs",
"author": "ice-admin@alibaba-inc.com",
"homepage": "",
diff --git a/packages/plugin-store/src/_appModels.ts b/packages/plugin-store/src/_appModels.ts
index 04cd982..50cf174 100644
--- a/packages/plugin-store/src/_appModels.ts
+++ b/packages/plugin-store/src/_appModels.ts
@@ -1,7 +1,7 @@
-import { createStore } from '@ice/store'
+import { createStore } from '@ice/store';
-const models = {}
+const models = {};
-const store = createStore(models)
+const store = createStore(models);
-export default store
+export default store;
diff --git a/packages/plugin-store/src/_pageModels.ts b/packages/plugin-store/src/_pageModels.ts
index eea7169..6f08cd7 100644
--- a/packages/plugin-store/src/_pageModels.ts
+++ b/packages/plugin-store/src/_pageModels.ts
@@ -1,9 +1,9 @@
-import { createStore } from '@ice/store'
+import { createStore } from '@ice/store';
-const Dashboard = createStore({})
+const Dashboard = createStore({});
-const About = createStore({})
+const About = createStore({});
-const PageModles = { Dashboard, About }
+const PageModles = { Dashboard, About };
-export default PageModles
+export default PageModles;
diff --git a/packages/plugin-store/src/generator.ts b/packages/plugin-store/src/generator.ts
index fac4707..4dfef82 100644
--- a/packages/plugin-store/src/generator.ts
+++ b/packages/plugin-store/src/generator.ts
@@ -1,7 +1,7 @@
-import * as path from 'path'
-import * as fse from 'fs-extra'
-import * as ejs from 'ejs'
-import * as recursiveReaddir from 'fs-readdir-recursive'
+import * as path from 'path';
+import * as fse from 'fs-extra';
+import * as ejs from 'ejs';
+import * as recursiveReaddir from 'fs-readdir-recursive';
export interface IExportData {
specifier?: string;
@@ -30,111 +30,111 @@ export default class Generator {
projectType: string;
applyMethod: Function;
}) {
- this.rootDir = rootDir
- this.modelsTemplatePath = modelsTemplatePath
- this.pageModelsTemplatePath = pageModelsTemplatePath
- this.targetPath = targetPath
- this.applyMethod = applyMethod
- this.projectType = projectType
+ this.rootDir = rootDir;
+ this.modelsTemplatePath = modelsTemplatePath;
+ this.pageModelsTemplatePath = pageModelsTemplatePath;
+ this.targetPath = targetPath;
+ this.applyMethod = applyMethod;
+ this.projectType = projectType;
}
private getPageModels (pageName: string, pageModelsDir: string, pageModelFile: string) {
if (fse.pathExistsSync(pageModelsDir)) {
- const pageModels = recursiveReaddir(pageModelsDir).map(item => path.parse(item))
+ const pageModels = recursiveReaddir(pageModelsDir).map(item => path.parse(item));
- pageModelsDir = this.applyMethod('formatPath', pageModelsDir)
+ pageModelsDir = this.applyMethod('formatPath', pageModelsDir);
- let importStr = ''
- let modelsStr = ''
+ let importStr = '';
+ let modelsStr = '';
pageModels.forEach(pageModel => {
if (pageModel.dir) {
// Note: 嵌套忽略
} else {
- importStr += `\nimport ${pageModel.name} from '${pageModelsDir}/${pageModel.name}';`
+ importStr += `\nimport ${pageModel.name} from '${pageModelsDir}/${pageModel.name}';`;
}
- modelsStr += `${pageModel.name},`
- })
+ modelsStr += `${pageModel.name},`;
+ });
return {
isSingleModel: false,
importStr,
modelsStr
- }
+ };
}
return {
isSingleModel: true,
importStr: `import ${pageName} from '${this.applyMethod('formatPath', pageModelFile)}';`,
modelsStr: pageName
- }
+ };
}
private renderAppModels() {
- let appModelsDir = path.join(this.rootDir, 'src', 'models')
- const targetPath = path.join(this.targetPath, 'appModels.ts')
+ let appModelsDir = path.join(this.rootDir, 'src', 'models');
+ const targetPath = path.join(this.targetPath, 'appModels.ts');
- let models = []
+ let models = [];
if (fse.pathExistsSync(appModelsDir)) {
- appModelsDir = this.applyMethod('formatPath', appModelsDir)
- models = fse.readdirSync(appModelsDir).map(item => path.parse(item).name)
+ appModelsDir = this.applyMethod('formatPath', appModelsDir);
+ models = fse.readdirSync(appModelsDir).map(item => path.parse(item).name);
}
- let importStr = ''
- let modelsStr = ''
+ let importStr = '';
+ let modelsStr = '';
models.forEach((model) => {
- importStr += `\nimport ${model} from '${appModelsDir}/${model}';`
- modelsStr += `${model},`
- })
-
- this.renderFile(this.modelsTemplatePath, targetPath, { importStr, modelsStr, isSingleModel: false })
- const exportName = 'store'
- this.applyMethod('removeIceExport', exportName)
- this.applyMethod('addIceExport', { source: './appModels', exportName })
+ importStr += `\nimport ${model} from '${appModelsDir}/${model}';`;
+ modelsStr += `${model},`;
+ });
+
+ this.renderFile(this.modelsTemplatePath, targetPath, { importStr, modelsStr, isSingleModel: false });
+ const exportName = 'store';
+ this.applyMethod('removeIceExport', exportName);
+ this.applyMethod('addIceExport', { source: './appModels', exportName });
}
private renderPageModels() {
const pages = this.applyMethod('getPages', this.rootDir);
- const pageModels = []
+ const pageModels = [];
// generate .ice/pages/*/models.ts
pages.forEach(pageName => {
- const source = `./pages/${pageName}/models.ts`
- const targetPath = path.join(this.targetPath, source)
+ const source = `./pages/${pageName}/models.ts`;
+ const targetPath = path.join(this.targetPath, source);
- const pageNameDir = path.join(this.rootDir, 'src', 'pages', pageName)
+ const pageNameDir = path.join(this.rootDir, 'src', 'pages', pageName);
// example: src/pages/*/models/*
- const pageModelsDir = path.join(pageNameDir, 'models')
+ const pageModelsDir = path.join(pageNameDir, 'models');
// example: src/pages/*/model.ts
- const pageModelFile = path.join(pageNameDir, `model.${this.projectType}`)
+ const pageModelFile = path.join(pageNameDir, `model.${this.projectType}`);
if (fse.pathExistsSync(pageModelsDir) || fse.pathExistsSync(pageModelFile)) {
- pageModels.push(pageName)
- const renderData = this.getPageModels(pageName, pageModelsDir, path.join(pageNameDir, 'model'))
- this.renderFile(this.modelsTemplatePath, targetPath, renderData)
+ pageModels.push(pageName);
+ const renderData = this.getPageModels(pageName, pageModelsDir, path.join(pageNameDir, 'model'));
+ this.renderFile(this.modelsTemplatePath, targetPath, renderData);
- const exportName = 'store'
- this.applyMethod('removePageExport', pageName, exportName)
- this.applyMethod('addPageExport', pageName, { source: './models', exportName })
+ const exportName = 'store';
+ this.applyMethod('removePageExport', pageName, exportName);
+ this.applyMethod('addPageExport', pageName, { source: './models', exportName });
}
- })
+ });
// generate .ice/pageModels.ts
- this.generatePageModelsIndex(pageModels)
+ this.generatePageModelsIndex(pageModels);
}
private generatePageModelsIndex(pageModels: string[]) {
- const targetPath = path.join(this.targetPath, 'pageModels.ts')
+ const targetPath = path.join(this.targetPath, 'pageModels.ts');
- let importPageModelStr = ''
- let pageModelStr = ''
+ let importPageModelStr = '';
+ let pageModelStr = '';
pageModels.forEach(pageModel => {
- importPageModelStr += `\nimport ${pageModel} from './pages/${pageModel}/models';`
- pageModelStr += `${pageModel},`
- })
+ importPageModelStr += `\nimport ${pageModel} from './pages/${pageModel}/models';`;
+ pageModelStr += `${pageModel},`;
+ });
- this.renderFile(this.pageModelsTemplatePath, targetPath, { importPageModelStr, pageModelStr })
+ this.renderFile(this.pageModelsTemplatePath, targetPath, { importPageModelStr, pageModelStr });
}
private renderFile(templatePath: string, targetPath: string, extraData = {}) {
@@ -145,7 +145,7 @@ export default class Generator {
}
public render() {
- this.renderAppModels()
- this.renderPageModels()
+ this.renderAppModels();
+ this.renderPageModels();
}
}
diff --git a/packages/plugin-store/src/index.ts b/packages/plugin-store/src/index.ts
index faa0bff..674df5b 100644
--- a/packages/plugin-store/src/index.ts
+++ b/packages/plugin-store/src/index.ts
@@ -1,19 +1,19 @@
-import * as path from 'path'
-import * as fse from 'fs-extra'
-import Generator from './generator'
+import * as path from 'path';
+import * as fse from 'fs-extra';
+import Generator from './generator';
export default async (api) => {
- const { context, getValue, onHook, applyMethod, onGetWebpackConfig } = api
- const { rootDir, command } = context
+ const { context, getValue, onHook, applyMethod, onGetWebpackConfig } = api;
+ const { rootDir, command } = context;
- const targetPath = getValue('ICE_TEMP')
- const templatePath = path.join(__dirname, 'template')
- const modelsTemplatePath = path.join(templatePath, 'models.ts.ejs')
- const pageModelsTemplatePath = path.join(templatePath, 'pageModels.ts.ejs')
- const projectType = getValue('PROJECT_TYPE')
+ const targetPath = getValue('ICE_TEMP');
+ const templatePath = path.join(__dirname, 'template');
+ const modelsTemplatePath = path.join(templatePath, 'models.ts.ejs');
+ const pageModelsTemplatePath = path.join(templatePath, 'pageModels.ts.ejs');
+ const projectType = getValue('PROJECT_TYPE');
- await fse.copy(path.join(__dirname, '..', 'src/types/index.ts'), path.join(targetPath, './types/store.ts'))
- applyMethod('addIceTypesExport', { source: './types/store', specifier: '{ IStore }', exportName: 'store?: IStore' })
+ await fse.copy(path.join(__dirname, '..', 'src/types/index.ts'), path.join(targetPath, './types/store.ts'));
+ applyMethod('addIceTypesExport', { source: './types/store', specifier: '{ IStore }', exportName: 'store?: IStore' });
onGetWebpackConfig(config => {
if (command === 'build') {
@@ -23,12 +23,12 @@ export default async (api) => {
// eslint-disable-next-line
terserOptions: { ...args.terserOptions, keep_classnames: true, keep_fnames: true }
},
- ])
+ ]);
}
- config.resolve.alias.set('$ice/appModels', path.join(targetPath, 'appModels.ts'))
- config.resolve.alias.set('$ice/pageModels', path.join(targetPath, 'pageModels.ts'))
- })
+ config.resolve.alias.set('$ice/appModels', path.join(targetPath, 'appModels.ts'));
+ config.resolve.alias.set('$ice/pageModels', path.join(targetPath, 'pageModels.ts'));
+ });
const gen = new Generator({
modelsTemplatePath,
@@ -37,13 +37,13 @@ export default async (api) => {
rootDir,
applyMethod,
projectType
- })
+ });
- gen.render()
+ gen.render();
onHook('before.start.run', async () => {
applyMethod('watchFileChange', /models\/.*|model.*/, () => {
- gen.render()
+ gen.render();
});
});
-}
+};
diff --git a/packages/plugin-store/src/module.tsx b/packages/plugin-store/src/module.tsx
index 65f987c..3f556c0 100644
--- a/packages/plugin-store/src/module.tsx
+++ b/packages/plugin-store/src/module.tsx
@@ -1,42 +1,42 @@
-import * as React from 'react'
-import AppStore from '$ice/appModels'
-import PageStores from '$ice/pageModels'
+import * as React from 'react';
+import AppStore from '$ice/appModels';
+import PageStores from '$ice/pageModels';
const wrapperComponent = (PageComponent) => {
- const { pageConfig = {} } = PageComponent
+ const { pageConfig = {} } = PageComponent;
const StoreWrapperedComponent = (props) => {
- const pageComponentName = pageConfig.componentName
- const PageStore = PageStores[pageComponentName]
+ const pageComponentName = pageConfig.componentName;
+ const PageStore = PageStores[pageComponentName];
if (PageStore) {
return (
- )
+ );
}
- return
- }
- return StoreWrapperedComponent
-}
+ return ;
+ };
+ return StoreWrapperedComponent;
+};
export default ({ addProvider, wrapperRouteComponent, appConfig, context }) => {
wrapperRouteComponent(wrapperComponent);
const StoreProvider = ({children}) => {
- const storeConfig = appConfig.store || {}
+ const storeConfig = appConfig.store || {};
const initialStates = storeConfig.getInitialStates
? storeConfig.getInitialStates(context && context.initialData)
- : storeConfig.initialStates || {}
+ : storeConfig.initialStates || {};
return (
{children}
- )
- }
+ );
+ };
if (AppStore) {
- addProvider(StoreProvider)
+ addProvider(StoreProvider);
}
-}
+};
diff --git a/packages/plugin-store/src/template/models.ts.ejs b/packages/plugin-store/src/template/models.ts.ejs
index dc56944..6a0dcbe 100644
--- a/packages/plugin-store/src/template/models.ts.ejs
+++ b/packages/plugin-store/src/template/models.ts.ejs
@@ -1,16 +1,16 @@
<% if (importStr) { %>
-import { createStore } from '@ice/store'
+import { createStore } from '@ice/store';
<%- importStr %>
<% } %>
<% if (importStr && isSingleModel) { %>
const model = { default: <%- modelsStr %> }
-const store = createStore(model)
-export default store
+const store = createStore(model);
+export default store;
<% } %>
<% if (importStr && !isSingleModel) { %>
const models = { <%- modelsStr %> }
-const store = createStore(models)
-export default store
+const store = createStore(models);
+export default store;
<% } %>
diff --git a/packages/plugin-store/src/template/pageModels.ts.ejs b/packages/plugin-store/src/template/pageModels.ts.ejs
index a5bbdce..250dfa8 100644
--- a/packages/plugin-store/src/template/pageModels.ts.ejs
+++ b/packages/plugin-store/src/template/pageModels.ts.ejs
@@ -2,4 +2,4 @@
const pageModels = { <%- pageModelStr %> }
-export default pageModels
+export default pageModels;
diff --git a/scripts/publish.ts b/scripts/publish.ts
index 13854ce..ec38600 100644
--- a/scripts/publish.ts
+++ b/scripts/publish.ts
@@ -50,15 +50,10 @@ async function publish() {
}
});
- log(`5. 🔖 🔖 🔖 Commit${isLatestVersion ? ' & Create tag' : ''}...`)
+ log(`5. 🔖 🔖 🔖 Commit changes...`)
await run(`git commit --all -m v${newVersion}`)
+ await run('git push')
- if (isLatestVersion) {
- await run(`git tag v${newVersion}`)
- await run('git push origin master --tags')
- } else {
- await run('git push')
- }
log(`\n\n 🎉 🎉 🎉 Published successfully...`)
log('6. 💡 💡 💡 Start syncing...')