Skip to content

Commit

Permalink
修复 & 新增 (#25)
Browse files Browse the repository at this point in the history
  • Loading branch information
SunLxy authored Mar 23, 2022
1 parent 92c3109 commit 2c8bf2f
Show file tree
Hide file tree
Showing 21 changed files with 114 additions and 74 deletions.
15 changes: 8 additions & 7 deletions core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,7 @@ Support multiple webpack configurations to execute together.
npx create-kkt-ssr my-app
cd my-app
npm install
npm run watch
npm run server
npm run start
```

You can also initialize a project from one of the examples. Example from [kktjs/ssr](./example) example-path.
Expand Down Expand Up @@ -75,8 +74,7 @@ npm run server # Start service
Runs the project in development mode.

```bash
npm run watch
npm run server
npm run start
```

**production**
Expand Down Expand Up @@ -131,7 +129,7 @@ Add `.kktssrrc.js` to the root directory of your project

```js
export default {
overridesClientWebpack:(conf,env)=>{
overridesClientWebpack:(conf,env,options)=>{
return conf
}
}
Expand All @@ -143,7 +141,7 @@ export default {
```js
export default {
overridesServerWebpack:(conf,env)=>{
overridesServerWebpack:(conf,env,options)=>{
return conf
}
}
Expand All @@ -153,7 +151,7 @@ export default {

```js
export default {
overridesWebpack:(conf,env)=>{
overridesWebpack:(conf,env,options)=>{
return conf
}
}
Expand Down Expand Up @@ -208,6 +206,9 @@ export default {
path: "./mocker/index.js",
options:{
changeHost: true,
proxy:{

}
}
}),
}
Expand Down
9 changes: 6 additions & 3 deletions core/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@kkt/ssr",
"version": "3.1.5",
"version": "3.1.6",
"description": "",
"license": "MIT",
"main": "lib/index.js",
Expand Down Expand Up @@ -28,15 +28,18 @@
"dependencies": {
"@babel/core": "^7.17.8",
"@babel/runtime": "^7.17.8",
"@babel/register": "^7.17.7",
"babel-preset-react-app": "^10.0.1",
"css-loader": "^6.7.1",
"kkt": "^7.1.5",
"mini-css-extract-plugin": "2.6.0",
"mocker-api": "^2.9.5",
"nodemon-webpack-plugin": "^4.7.1",
"razzle-start-server-webpack-plugin": "^4.2.16",
"react-scripts": "^5.0.0",
"ts-node": "^10.7.0",
"typescript": "^4.6.2",
"webpack-manifest-plugin": "^5.0.0",
"webpack-node-externals": "^3.0.0",
"webpackbar": "^5.0.2"
}
}
}
42 changes: 23 additions & 19 deletions core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ function help() {
console.log(' --c-ne, --c-nodeExternals ', 'client use webpack-node-external .');
console.log(' --s-st, --s-split ', 'server Split code .');
console.log(' --c-st, --c-split ', 'client Split code .');

console.log(' -o, --original ', 'Use original react-scripts .');

console.log('\n Example:\n');
console.log(' $ \x1b[35mkkt-ssr\x1b[0m build');
Expand All @@ -27,6 +27,7 @@ function help() {
console.log(' $ \x1b[35mkkt-ssr\x1b[0m watch --s-ne');
console.log(' $ \x1b[35mkkt-ssr\x1b[0m build --s-st');
console.log(' $ \x1b[35mkkt-ssr\x1b[0m watch --s-st');
console.log(' $ \x1b[35mkkt-ssr\x1b[0m start -o');
console.log(`\n \x1b[34;1m@kkt/ssr\x1b[0m \x1b[32;1mv${version || ''}\x1b[0m\n`);
}

Expand All @@ -39,6 +40,8 @@ interface SSRNCCArgs extends BuildArgs {
"c-nodeExternals"?: boolean,
"c-st"?: boolean,
"c-split"?: boolean,
"o"?: boolean,
"original"?: boolean,
}

(async () => {
Expand Down Expand Up @@ -78,41 +81,42 @@ interface SSRNCCArgs extends BuildArgs {
const clientIsChunk = argvs["c-st"] || argvs['c-split']
const serverIsChunk = argvs["s-st"] || argvs['s-split']

// 使用原始 react-scripts
const original = argvs["o"] || argvs["original"]

const options = {
clientNodeExternals,
serverNodeExternals,
clientIsChunk,
serverIsChunk,
original
}
// 解决 原始情况下 PUBLIC_URL 报错
if (argvs["PUBLIC_URL"]) {
process.env.PUBLIC_URL = argvs["PUBLIC_URL"];
} else {
process.env.PUBLIC_URL = '';
}

if (scriptName === 'build') {
process.env.BABEL_ENV = 'production';
process.env.NODE_ENV = 'production';

const build = await import("./script/build")
await build.default({
clientNodeExternals,
serverNodeExternals,
clientIsChunk,
serverIsChunk
})
await build.default(options)
} else if (scriptName === 'watch') {

process.env.BABEL_ENV = 'development';
process.env.NODE_ENV = 'development';

const watch = await import("./script/watch")
await watch.default({
clientNodeExternals,
serverNodeExternals,
clientIsChunk,
serverIsChunk
})
await watch.default(options)
} else if (scriptName === 'start') {
process.env.BABEL_ENV = 'development';
process.env.NODE_ENV = 'development';

const start = await import("./script/start")
await start.default({
clientNodeExternals,
serverNodeExternals,
clientIsChunk,
serverIsChunk
})
await start.default(options)
}
} catch (error) {
console.log('\x1b[31m KKT:SSR:ERROR:\x1b[0m', error);
Expand Down
1 change: 1 addition & 0 deletions core/src/interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ export interface OptionsProps {
serverNodeExternals: boolean;
serverIsChunk: boolean;
clientIsChunk: boolean;
original: boolean
}
4 changes: 1 addition & 3 deletions core/src/overrides/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,12 +112,10 @@ export async function loaderConf(): Promise<OverridesProps> {
if (!fs.existsSync(path.appIndexJs)) {
path.appIndexJs = overrides.client_path
}

overrides.paths = path
// 覆盖配置 里面的地址
overridePaths(undefined, {
...(path as unknown as Record<string, string>),
appBuild: overrides.output_path
...(path as unknown as Record<string, string>)
});
return overrides;
} catch (error) {
Expand Down
18 changes: 17 additions & 1 deletion core/src/overrides/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,10 @@ export const restWebpackManifestPlugin = (

const getPahts = (name: string) => {
if (!isCreateAsset || /^http/.test(name)) {
return name
if (/^\//.test(name) || /^http/.test(name)) {
return name
}
return "/" + name
}
if (/^\//.test(name)) {
return httpPath + name
Expand Down Expand Up @@ -149,6 +152,19 @@ export const addMiniCssExtractPlugin = (conf: WebpackConfiguration): WebpackConf
}
}

// loader source-map-loader

export const removeSourceMapLoader = (conf: WebpackConfiguration): WebpackConfiguration => {
return {
...conf,
module: {
...conf.module,
rules: conf.module.rules.filter((rule) => !(rule !== "..." && /source-map-loader/.test(rule.loader) && /\.(js|mjs|jsx|ts|tsx|css)$/.toString() === rule.test.toString()))
}
}
}


// node 环境 把 css 进行处理
export const restDevModuleRuleCss = (conf: WebpackConfiguration,): WebpackConfiguration => {
return {
Expand Down
6 changes: 3 additions & 3 deletions core/src/script/start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,19 @@

import createCompiler from "./utils"
import { OptionsProps } from "../interface"
import { webpackConfigPath, reactScripts, } from "./../overrides/pathUtils"
import { webpackConfigPath, reactScripts, reactDevUtils } from "./../overrides/pathUtils"
import overridesDevServer from "./utils/overridesDevServer"

export default async (options: OptionsProps) => {
// 修复 运行 start 停止之后,再次运行 watch 报错
delete require.cache[require.resolve(webpackConfigPath)];
delete require.cache[require.resolve(`${reactDevUtils}/openBrowser`)];

try {
const { overrides, config } = await createCompiler("development", options, true)

require.cache[require.resolve(webpackConfigPath)].exports = (env: string) => config;

await overridesDevServer(overrides)
await overridesDevServer(overrides, options.original)

require(`${reactScripts}/scripts/start`);

Expand Down
30 changes: 20 additions & 10 deletions core/src/script/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ import {
restOutPut,
restWebpackManifestPlugin,
clearHtmlTemp,
restDevModuleRuleCss
restDevModuleRuleCss,
removeSourceMapLoader
} from "../../overrides/utils"
const { choosePort } = require('react-dev-utils/WebpackDevServerUtils');
// 引入环境变量
Expand Down Expand Up @@ -47,12 +48,15 @@ const getWebpackConfig = (newConfig: webpack.Configuration, type: "server" | "cl

if (isWebpackDevServer && env === "development") {
newConfig.output.publicPath = `${httpPath}/`
} else {
newConfig.output.publicPath = `/`
}

let isCreateAsset = false;
if (isWebpackDevServer && type === "client" && env === "development") {
isCreateAsset = true
}

if (isWebpackDevServer && type === "server" && env === "development") {
newConfig.plugins.push(
new DevServerPlugins({
Expand All @@ -68,9 +72,7 @@ const getWebpackConfig = (newConfig: webpack.Configuration, type: "server" | "cl

newConfig = restWebpackManifestPlugin(newConfig, overrides.paths, type, isCreateAsset, httpPath)

if (!isWebpackDevServer) {
newConfig = clearHtmlTemp(newConfig)
}
newConfig = clearHtmlTemp(newConfig)

newConfig.module.exprContextCritical = false;
newConfig.plugins.push(
Expand All @@ -80,14 +82,11 @@ const getWebpackConfig = (newConfig: webpack.Configuration, type: "server" | "cl
PORT: JSON.stringify(PORT),
Dev_Server: JSON.stringify(isWebpackDevServer),
"process.env.PORT": JSON.stringify(PORT || 3000),
"process.env.HOST": JSON.stringify(HOST || "localhost")
"process.env.HOST": JSON.stringify(HOST || "localhost"),
"process.env.PUBLIC_URL": JSON.stringify(process.env.PUBLIC_URL || overrides.output_path || "")
}),
)

if (isWebpackDevServer) {
// newConfig.output.publicPath = `http://${HOST}:${PORT}/`
}

if (!split) {
newConfig.plugins.push(new webpack.optimize.LimitChunkCountPlugin({ maxChunks: 1 }))
}
Expand Down Expand Up @@ -121,7 +120,16 @@ export default async (env: "development" | "production", options: OptionsProps,
/**------------------------ client --------------------- */
if (fs.existsSync(overrides.client_path)) {
const configClient = configFactory(env);
let newConfigClient = getWebpackConfig(configClient, "client", overrides, options.clientNodeExternals, options.clientIsChunk, env, isWebpackDevServer)

let newConfigClient = configClient
// 控制 client 是否使用 ssr,默认情况下使用
if (!options.original) {
newConfigClient = getWebpackConfig(configClient, "client", overrides, options.clientNodeExternals, options.clientIsChunk, env, isWebpackDevServer)
}
if (isWebpackDevServer && !options.original) {
// 去除 source-map-loader
newConfigClient = removeSourceMapLoader(newConfigClient)
}
if (overridesClientWebpack) {
newConfigClient = overridesClientWebpack(newConfigClient, env, { ...rest, env })
}
Expand All @@ -135,6 +143,8 @@ export default async (env: "development" | "production", options: OptionsProps,
newConfigServer.devtool = false
newConfigServer.target = "node14"
newConfigServer = restDevModuleRuleCss(newConfigServer)
// 去除 source-map-loader
newConfigServer = removeSourceMapLoader(newConfigServer)
if (overridesServerWebpack) {
newConfigServer = overridesServerWebpack(newConfigServer, env, { ...rest, env })
}
Expand Down
13 changes: 8 additions & 5 deletions core/src/script/utils/overridesDevServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,17 @@ const evalSourceMapMiddleware = require('react-dev-utils/evalSourceMapMiddleware
const noopServiceWorkerMiddleware = require('react-dev-utils/noopServiceWorkerMiddleware');
const redirectServedPath = require('react-dev-utils/redirectServedPathMiddleware');

export default async (overrides: OverridesProps) => {
export default async (overrides: OverridesProps, original: boolean) => {

const openBrowserPath = `${reactDevUtils}/openBrowser`;
if (!original) {

require(openBrowserPath);
const openBrowserPath = `${reactDevUtils}/openBrowser`;

// override config in memory
require.cache[require.resolve(openBrowserPath)].exports = () => { };
require(openBrowserPath);

// override config in memory
require.cache[require.resolve(openBrowserPath)].exports = () => { };
}


const webpackdDevServerConfigPath = require(`${devServerConfigPath}`)
Expand Down
4 changes: 2 additions & 2 deletions example/basic-plugins/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@examples/basic-plugins",
"version": "3.1.5",
"version": "3.1.6",
"description": "",
"private": true,
"scripts": {
Expand All @@ -16,7 +16,7 @@
"react-dom": "17.0.2"
},
"devDependencies": {
"@kkt/ssr": "3.1.5",
"@kkt/ssr": "3.1.6",
"kkt": "~7.1.5"
},
"browserslist": {
Expand Down
7 changes: 4 additions & 3 deletions example/basic-routes-rematch-new/package.json
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
{
"name": "@examples/basic-routes-rematch-new",
"version": "3.1.5",
"version": "3.1.6",
"description": "",
"private": true,
"scripts": {
"server": "node dist/server.js",
"build": "kkt-ssr build",
"watch": "kkt-ssr watch"
"watch": "kkt-ssr watch",
"start": "kkt-ssr start"
},
"keywords": [],
"dependencies": {
Expand All @@ -21,7 +22,7 @@
"serialize-javascript": "6.0.0"
},
"devDependencies": {
"@kkt/ssr": "3.1.5",
"@kkt/ssr": "3.1.6",
"kkt": "~7.1.5"
},
"browserslist": {
Expand Down
Loading

0 comments on commit 2c8bf2f

Please sign in to comment.