sptc 0.0.21 → 0.0.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +0 -6
  2. package/dist/httpServer.js +17 -0
  3. package/engine/compiler.js +1 -1
  4. package/engine/interpreter.js +1 -0
  5. package/package.json +2 -3
  6. package/utils/base.js +5 -0
  7. package/utils/compileFile.js +1 -1
  8. package/bin/sptcd-web.js +0 -27
  9. package/dist/router.s +0 -58
  10. package/dist/sptc-web-demo/build/index.js +0 -24
  11. package/dist/sptc-web-demo/build/lib.js +0 -116
  12. package/dist/sptc-web-demo/build/postcss.config.js +0 -31
  13. package/dist/sptc-web-demo/build/sptc.inject.js +0 -73
  14. package/dist/sptc-web-demo/build/webpack.lib.js +0 -242
  15. package/dist/sptc-web-demo/package.json +0 -48
  16. package/dist/sptc-web-demo/server/app/controllers/assets.s +0 -31
  17. package/dist/sptc-web-demo/server/app/controllers/data.s +0 -39
  18. package/dist/sptc-web-demo/server/app/controllers/error.s +0 -10
  19. package/dist/sptc-web-demo/server/app/controllers/ssr.s +0 -6
  20. package/dist/sptc-web-demo/server/app/library/request.s +0 -44
  21. package/dist/sptc-web-demo/server/app/library/response.s +0 -12
  22. package/dist/sptc-web-demo/server/app/library/sqlite.s +0 -91
  23. package/dist/sptc-web-demo/server/app/library/ssr.s +0 -142
  24. package/dist/sptc-web-demo/server/app/library/utils.s +0 -108
  25. package/dist/sptc-web-demo/server/app/models/Message.s +0 -62
  26. package/dist/sptc-web-demo/server/app/setting.s +0 -9
  27. package/dist/sptc-web-demo/server/index.s +0 -24
  28. package/dist/sptc-web-demo/server/public/externals/js/react-dom.production.min.js +0 -244
  29. package/dist/sptc-web-demo/server/public/externals/js/react.production.min.js +0 -33
  30. package/dist/sptc-web-demo/server/public/externals/js/vconsole.js +0 -10
  31. package/dist/sptc-web-demo/src/app/index.jsx +0 -131
  32. package/dist/sptc-web-demo/src/app/index.scss +0 -108
  33. package/dist/sptc-web-demo/src/components/AnimateView/index.jsx +0 -415
  34. package/dist/sptc-web-demo/src/components/AnimateView/index.scss +0 -167
  35. package/dist/sptc-web-demo/src/components/UseComponent/index.jsx +0 -93
  36. package/dist/sptc-web-demo/src/index.jsx +0 -47
  37. package/dist/sptc-web-demo/src/ssrInit.js +0 -20
  38. package/dist/sptc-web-demo/src/utils/base.js +0 -28
  39. package/dist/sptc-web-demo/src/utils/fetch.js +0 -56
package/README.md CHANGED
@@ -73,9 +73,3 @@ module.exports={
73
73
 
74
74
 
75
75
  ```
76
-
77
-
78
- ### sptcd-create-project
79
- ```
80
- Run this command `sptcd-create-project` to create a sample web project that supports react server-side rendering. The sample project already contains commonly used codes, such as reading and writing databases, multi-page data interaction, routing, etc., so it is very suitable for full-stack projects that need to get started quickly.
81
- ```
@@ -4,6 +4,7 @@ const {
4
4
  fileExists,
5
5
  getExtension,
6
6
  listdir,
7
+ assert,
7
8
  }=require('../utils')
8
9
  const {executeSptcFile}=require('../engine')
9
10
 
@@ -137,6 +138,7 @@ function buildRequestContext(req, res, {srvDir, debug, env, isRouterMode}) {
137
138
  state.is_debug=x
138
139
  }
139
140
  reqCtx.isDebug=_=>state.is_debug
141
+ reqCtx.withCache=createWithCacheStore()
140
142
 
141
143
  const handler={
142
144
  write: x=>{
@@ -165,6 +167,21 @@ function getRequestFile(req, srvDir) {
165
167
  pathname,
166
168
  }
167
169
  }
170
+ const cacheStore={}
171
+ function createWithCacheStore() {
172
+ const withCache=(fn, k, v)=>{
173
+ assert(k)
174
+ assert(v)
175
+ assert(typeof fn==='function')
176
+ const o=cacheStore
177
+ if(!o.hasOwnProperty(k) || o[k].v!==v) {
178
+ o[k]={v, x: fn()}
179
+ }
180
+ return o[k].x
181
+ }
182
+ return withCache
183
+ }
184
+
168
185
 
169
186
  function traverseDirectory(ref, dir, exts) {
170
187
  let ret=`
@@ -78,4 +78,4 @@ function compileSptcFile(filename, option) {
78
78
 
79
79
  module.exports={
80
80
  compileSptcFile,
81
- }
81
+ }
@@ -165,6 +165,7 @@ function buildContext(ctx0, option) {
165
165
  ctx.__SPTC_VERSION__=Utils.__SPTC_VERSION__
166
166
  ctx.__SPTC_INSTALL_PATH__=Utils.__SPTC_INSTALL_PATH__
167
167
 
168
+ ctx.assert=Utils.assert
168
169
 
169
170
  // Dynamically set the cache configuration.
170
171
  ctx.configSptcFileCache=(cacheVersion, cacheSeconds)=>{
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sptc",
3
- "version": "0.0.21",
3
+ "version": "0.0.22",
4
4
  "description": "Simple Pretreat Toolkit CLI",
5
5
  "main": "",
6
6
  "engines": {
@@ -8,8 +8,7 @@
8
8
  },
9
9
  "bin": {
10
10
  "sptc": "./bin/sptc.js",
11
- "sptcd": "./bin/sptcd.js",
12
- "sptcd-create-project": "./bin/sptcd-web.js"
11
+ "sptcd": "./bin/sptcd.js"
13
12
  },
14
13
  "dependencies": {
15
14
  "commander": "10.0.1",
package/utils/base.js CHANGED
@@ -71,6 +71,10 @@ function PromiseWithResolvers() {
71
71
  return {promise, resolve: _resolve, reject: _reject}
72
72
  }
73
73
 
74
+ function assert(x) {
75
+ if(!x) throw new Error('Uncaught AssertionError [ERR_ASSERTION]: '+x+' == true')
76
+ }
77
+
74
78
  module.exports={
75
79
  readTextFile,
76
80
  sleep,
@@ -82,4 +86,5 @@ module.exports={
82
86
  getExtension,
83
87
  getLocalIpv4Addresses,
84
88
  PromiseWithResolvers,
89
+ assert,
85
90
  }
@@ -41,4 +41,4 @@ function compileFile(filename, option) {
41
41
 
42
42
  module.exports={
43
43
  compileFile,
44
- }
44
+ }
package/bin/sptcd-web.js DELETED
@@ -1,27 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- const {Command}=require('commander')
4
- const version=require('../package.json').version
5
- const program=new Command()
6
- .name(`create web project`)
7
- .description(`create web project`)
8
- .version(version)
9
- .requiredOption('-d, --dir <string>', 'Specify the project directory.', './sptc-web-demo')
10
- .action(({
11
- dir,
12
- })=>{
13
- const fs=require('fs-extra')
14
- try{
15
- fs.copySync(__dirname+'/../dist/sptc-web-demo', dir)
16
- console.log()
17
- console.log('New project created in `'+dir+'` !')
18
- console.log('The following steps are necessary for developing:')
19
- console.log('1. enter the project directory ', dir)
20
- console.log('2. run `npm i` to install the requirements')
21
- console.log('3. run `npm run dev` to start the demo')
22
- console.log()
23
- }catch(e) {
24
- console.error(e)
25
- }
26
- })
27
- .parse()
package/dist/router.s DELETED
@@ -1,58 +0,0 @@
1
- <?js
2
-
3
- const {$error, $alias, $index_action, $max_redirect=3}=include(__ROUTER_SETTING__)
4
-
5
- function resolve(pathname, maxRedirect=$max_redirect) {
6
- if(maxRedirect<=0) throw new Error('redirect max exceeded')
7
- let _pathname=pathname
8
- for(let a in $alias) {
9
- let p=a.replace(/\*/g, '(.*?)')
10
- const sub=pathname.match(new RegExp('^'+p+'$'))
11
- if(sub) {
12
- _pathname=$alias[a]
13
- if(_pathname.indexOf('$')>-1) {
14
- const r1=_pathname.replace(/\$(\d+)/g, (_, n)=>sub[+n] || _)
15
- if(isDebug()) {
16
- console.log('Redirect:', {
17
- from: pathname,
18
- to: r1,
19
- })
20
- }
21
- return resolve(r1, maxRedirect-1)
22
- }
23
- $_REQUEST_FILE['subRoute']=sub
24
- break
25
- }else if(a===pathname) {
26
- _pathname=$alias[a]
27
- break
28
- }
29
- }
30
- return _pathname
31
- }
32
-
33
- function _call(x, ...e) {
34
- if(!x) return;
35
- const $c=x.substr(1, x.indexOf('/', 1)-1) || x.substr(1)
36
- const c_len=2+$c.length
37
- const $a=x.substr(c_len, (x+'/').indexOf('/', c_len)-c_len) || $index_action
38
- const c=include(__APP__+'/controllers/'+$c+'.s')[$c+'Controller']
39
- if(isDebug()) {
40
- console.log('Request:', {
41
- pathname: $_REQUEST_FILE['pathname'],
42
- Controller: $c,
43
- Action: $a+'Action',
44
- })
45
- }
46
- const _c=new c(...e)
47
- return _c[$a+'Action']()
48
- }
49
-
50
- async function execute(pathname, ...argv) {
51
- const unlock=Sync.Lock()
52
- try{
53
- await _call(pathname, ...argv)
54
- }catch(e) {
55
- await _call($error, e)
56
- }
57
- unlock()
58
- }
@@ -1,24 +0,0 @@
1
- const {getRuntimeArgv, checkEnv, run}=require(__dirname+'/lib')
2
- checkEnv()
3
- const {IS_DEV, IS_BUILD, IS_SERVE, NPM_ARGV_ORIGINAL}=getRuntimeArgv()
4
-
5
- process.env.NODE_ENV=IS_DEV? 'development': 'production'
6
- const {webpackDev, webpackBuild}=require(__dirname+'/webpack.lib')
7
-
8
- const nk='NODE_OPTIONS', nv='--openssl-legacy-provider'
9
- if(+process.version.match(/^v(\d+)/)[1]>16 && process.env[nk]!==nv) {
10
- run('cross-env', [nk+'='+nv, 'npm', ...NPM_ARGV_ORIGINAL])
11
- }else{
12
- const open=require('open')
13
- if(IS_DEV) {
14
- run('cross-env', 'sptcd_environ=dev sptcd -rindex.s -wserver'.split(' '))
15
- webpackDev()
16
- open('http://127.0.0.1:3000')
17
- }else if(IS_BUILD) {
18
- webpackBuild()
19
- }else if(IS_SERVE) {
20
- run('cross-env', 'sptcd_environ=beta sptcd -rindex.s -wserver -n2 -s'.split(' '))
21
- console.log('-- The HTTP service is started with the address 127.0.0.1:9090 --')
22
- open('http://127.0.0.1:9090')
23
- }
24
- }
@@ -1,116 +0,0 @@
1
- const APP_PATH=__dirname+'/..'
2
- const pkg=require(APP_PATH+'/package.json')
3
- const chalk=require('chalk')
4
- const fs=require('fs')
5
-
6
- const RUNTIME_RND_STR=Date.now().toString(36)
7
- function getRuntimeArgv() {
8
- const p=process.argv[2]
9
- const IS_DEV=p==='dev'
10
- const IS_BUILD=p==='build'
11
- const IS_SERVE=p==='serve'
12
- const t=JSON.parse(process.env.npm_config_argv).original
13
- let e={}
14
- for(let s of t) {
15
- s.replace(/^--(.+?)=(.+)/, (_, k, v)=>{
16
- e[k]=v
17
- })
18
- }
19
- return {
20
- NPM_ARGV: e,
21
- NPM_ARGV_ORIGINAL: t,
22
- IS_DEV,
23
- IS_BUILD,
24
- IS_SERVE,
25
- RND: RUNTIME_RND_STR,
26
- }
27
- }
28
-
29
- function satisfiesVersion(target_v, custom_v) {
30
- function _cmp(v1, v2, g=3) {
31
- v1=v1.split('.').slice(0, g)
32
- v2=v2.split('.').slice(0, g)
33
- for(;v1.length<3;) v1.push(0)
34
- for(;v2.length<3;) v2.push(0)
35
- for(let i=0; i<3; i++) {
36
- const _v1=parseInt(v1[i]) || 0, _v2=parseInt(v2[i]) || 0
37
- if(_v1>_v2) return 1
38
- if(_v1<_v2) return -1
39
- }
40
- return 0
41
- }
42
- if(target_v==='*' || target_v===custom_v) return true
43
- let s=false
44
- target_v.replace(/^(>=|>|\^|~)\s*(\S+)/, (_, x, t_ver)=>{
45
- if(x==='>=') {
46
- s=_cmp(custom_v, t_ver)>=0
47
- }else if(x==='>') {
48
- s=_cmp(custom_v, t_ver)>0
49
- }else if(x==='<=') {
50
- s=_cmp(custom_v, t_ver)<=0
51
- }else if(x==='<') {
52
- s=_cmp(custom_v, t_ver)<0
53
- }else if(x==='^' || x==='~') {
54
- s=_cmp(custom_v, t_ver)>=0
55
- if(x==='^') {
56
- s=s && _cmp(custom_v, t_ver.replace(/^\d+/, _=>+_+1), 1)<=0
57
- }else{
58
- s=s && _cmp(custom_v, t_ver.replace(/(^.+?\.)(\d+)/, (_, a, b)=>a+(+b+1)), 2)<=0
59
- }
60
- }
61
- })
62
- return s
63
- }
64
-
65
- function checkEnv() {
66
- if(!satisfiesVersion(pkg.engines.node, process.version.replace(/^v/, ''))) {
67
- console.log([
68
- chalk.red('Node version not met :('),
69
- chalk.yellow(`You are using Node ${process.version}. Node ${pkg.engines.node} is required.`),
70
- ].join('\n'))
71
- process.exit(1)
72
- }
73
-
74
- const unmatched=[]
75
- const t=Object.assign({}, pkg.dependencies, pkg.devDependencies)
76
- for(let n in t) {
77
- let custom_v=''
78
- try{
79
- custom_v=require(APP_PATH+'/node_modules/'+n+'/package.json').version
80
- }catch(e) {}
81
- if(satisfiesVersion(t[n], custom_v)<=0) {
82
- unmatched.push([n, t[n], custom_v])
83
- }
84
- }
85
- if(unmatched.length) {
86
- console.log(chalk.red(`The following packages should be installed:`))
87
- for(let [name, tv, cv] of unmatched) {
88
- console.log(`${name} required: ${tv} | current: ${cv || 'uninstalled'}`)
89
- }
90
- process.exit()
91
- }
92
- }
93
-
94
- function getPostCssPlugins() {
95
- return require("postcss-load-config").sync({}, __dirname+'/postcss.config.js')
96
- }
97
-
98
- function requireNodeModuleFile(fn) {
99
- return require(APP_PATH+'/node_modules/'+fn)
100
- }
101
-
102
- function run(exe, argv) {
103
- const p=require('child_process').spawn(
104
- require('os').platform()==='win32'? exe+'.cmd': exe, argv)
105
- p.stdout.on('data', b=>process.stdout.write(b))
106
- p.stderr.on('data', b=>process.stderr.write(b))
107
- }
108
-
109
- module.exports={
110
- APP_PATH,
111
- getRuntimeArgv,
112
- checkEnv,
113
- getPostCssPlugins,
114
- requireNodeModuleFile,
115
- run,
116
- }
@@ -1,31 +0,0 @@
1
- var autoprefixer = require('autoprefixer')
2
-
3
- module.exports = {
4
- plugins: [
5
- autoprefixer({
6
- overrideBrowserslist: [
7
- 'Android >= 4.0',
8
- 'iOS >= 6',
9
- 'last 5 QQAndroid versions',
10
- 'last 5 UCAndroid versions'
11
- ],
12
- cascade: true
13
- }),
14
- require("postcss-px-to-viewport")({
15
- unitToConvert: 'px',
16
- viewportWidth: 1875,
17
- unitPrecision: 5,
18
- propList: ['*'],
19
- viewportUnit: 'rem',
20
- fontViewportUnit: 'rem',
21
- selectorBlackList: [],
22
- minPixelValue: 1,
23
- mediaQuery: false,
24
- replace: true,
25
- include: 'src/**',
26
- landscape: false,
27
- landscapeUnit: 'rem',
28
- landscapeWidth: 568
29
- })
30
- ]
31
- };
@@ -1,73 +0,0 @@
1
- const argv=require('./lib').getRuntimeArgv()
2
-
3
- function is_server(ctx) {
4
- return (ctx.webpackLoaderThis.target + '').indexOf('node') > -1;
5
- }
6
-
7
- const A={
8
- EXTENDS: (ctx) => ({
9
- ...argv,
10
- IS_NODE_TARGET: is_server(ctx),
11
- }),
12
- TPLS: [
13
- /\.jsx?$/, ctx=>{
14
- let {str, fn}=ctx
15
- let appends={}
16
- if (str.match(/<&[*=]/)) {
17
- str=str.replace(/<(\/)?&([*=&])([^\s>]+)/g, (_, b, a, p) => {
18
- appends[`import UseComponent from '@/components/UseComponent'`]=1
19
- if(a==='*') {
20
- if(b) return `</UseComponent`
21
- return `<UseComponent key={"pathto_component_${p}"} UseComponentGetter={_=>import("${p}")}`
22
- }else if(a==='=') {
23
- appends[`import UseComponent from '@/components/UseComponent'`]=1
24
- if(b) return `</UseComponent`
25
- return `<UseComponent key={"pathto_component_${p}"} UseComponentSync={true} UseComponentGetter={_=>require("${p}")}`
26
- } else if(a==='&') {
27
- const name = `Comp_pathto_component_${p.replace(/[^a-z\d_]+/g, '_')}`
28
- appends[`import ${name} from '${p}'`]=1
29
- if(b) return `</${name}`
30
- return `<${name}`
31
- }
32
- })
33
- str=Object.keys(appends).join('\n')+'\n'+str
34
- }
35
- return str;
36
- },
37
-
38
- /\.jsx?$/, ctx=>{
39
- let adds={}
40
- let str=ctx.str.replace(/\*IMG\((['"])(.+?)\1\)/g, (_, a, pth)=>{
41
- let e='IMG_'+pth.replace(/[^a-z\d_]+/g, '_')
42
- adds[e]=pth
43
- return e
44
- })
45
- for(let e in adds) {
46
- str=`import ${e} from '${adds[e]}'\n`+str
47
- }
48
- return str
49
- },
50
-
51
- /\.jsx?/, ctx=>{
52
- const {str, fn}=ctx
53
- if(fn.match(/ssrInit.js/)) return str
54
- if(!is_server(ctx)) return str
55
- return `
56
- import e from '@/ssrInit'
57
- const {window, document, navigator,location}=e
58
- `+str
59
- },
60
-
61
- /\.(scss|jsx?)/, ctx=>{
62
- const {str, fn}=ctx
63
- const path=require('path')
64
- const src=path.resolve(__dirname+'/src')
65
- const ffn=path.resolve(fn).substr(src.length).replace(/\.[a-z\d]+$/, '')
66
- let t=ffn.replace(/[\/\\]+([^/\\]+)\.[^/\\]+$/, '').replace(/[^a-z\d_-]/ig, '_')
67
- return str.replace(/\b__view_scope\b/g, 'V_'+argv.RND+'_'+t)
68
- },
69
-
70
- ],
71
- };
72
-
73
- module.exports=A
@@ -1,242 +0,0 @@
1
- const {
2
- APP_PATH,
3
- getRuntimeArgv,
4
- getPostCssPlugins,
5
- requireNodeModuleFile,
6
- }=require(__dirname+'/lib')
7
- const craco=require('@craco/craco')
8
- const webpack=require('webpack')
9
- const Webpackbar=require('webpackbar')
10
- const chalk=require('chalk')
11
- const fs=require('fs')
12
- const MiniCssExtractPlugin=require('mini-css-extract-plugin')
13
- const fs_extra=require('fs-extra')
14
- const {NPM_ARGV}=getRuntimeArgv()
15
- const path=require('path')
16
- const createWebpackBase=requireNodeModuleFile('react-scripts/config/webpack.config')
17
- function createWebpackConfig({isServer=false, env='development'}) {
18
- const IS_DEV=env==='development'
19
- const webpackConfig={
20
- target: !isServer? 'web': 'node',
21
- name: !isServer? 'client': 'server',
22
- mode: IS_DEV? 'development': 'production',
23
- optimization: {
24
- runtimeChunk: false,
25
- splitChunks: false,
26
- },
27
- }
28
- const base=createWebpackBase(env)
29
- base.plugins.push(
30
- new Webpackbar({
31
- name: webpackConfig.name,
32
- basic: false,
33
- }),
34
- )
35
-
36
- craco.removePlugins(base, x=>[
37
- 'HtmlWebpackPlugin',
38
- 'ManifestPlugin',
39
- 'ESLintWebpackPlugin',
40
- ].includes(x.constructor.name))
41
-
42
- craco.removeLoaders(base, craco.loaderByName('style-loader'))
43
- craco.getLoaders(base, craco.loaderByName('postcss-loader')).matches.map(e=>{
44
- const _fn=e.loader.options.plugins
45
- e.loader.options.plugins=_=>[..._fn(), ...getPostCssPlugins().plugins]
46
- })
47
- craco.getLoaders(base, craco.loaderByName('babel-loader')).matches.map(e=>{
48
- e.loader.options.plugins=[]
49
- })
50
- base.module.rules.push({
51
- test: /\.([tj]sx?|scss)/,
52
- exclude: /node_modules/,
53
- options: {
54
- file: __dirname+'/sptc.inject.js',
55
- },
56
- loader: 'sptc/dist/webpack.loader.js',
57
- })
58
-
59
- if(isServer) {
60
- craco.removePlugins(base, x=>[
61
- 'MiniCssExtractPlugin',
62
- 'InterpolateHtmlPlugin',
63
- 'InlineChunkHtmlPlugin',
64
- 'WebpackManifestPlugin',
65
- 'ReactRefreshPlugin',
66
- 'ForkTsCheckerWebpackPlugin',
67
- 'WatchMissingNodeModulesPlugin',
68
- 'ModuleNotFoundPlugin',
69
- 'ModuleScopePlugin',
70
- ].includes(x.constructor.name))
71
-
72
- craco.removeLoaders(base, craco.loaderByName('mini-css-extract-plugin'))
73
- base.module.rules[1].oneOf.map(x=>{
74
- if(x.test && ('.css'.match(x.test) || '.scss'.match(x.test))) {
75
- x.use='null-loader'
76
- }
77
- })
78
-
79
- base.resolve.plugins=[]
80
- base.output.filename='server/index.js'
81
- base.entry=APP_PATH+'/src/index.jsx';
82
- base.output.chunkFilename='server/chunk.[contenthash].js';
83
- base.output.libraryTarget='commonjs2';
84
- }else{
85
- if(IS_DEV) {
86
- craco.removePlugins(base, craco.pluginByName('HotModuleReplacementPlugin'))
87
- base.plugins.push(
88
- new webpack.DefinePlugin('process', '{}'),
89
- new webpack.HotModuleReplacementPlugin(),
90
- new MiniCssExtractPlugin({
91
- filename: 'static/css/[name].css',
92
- chunkFilename: 'static/css/[name].chunk.css',
93
- }),
94
- )
95
- base.module.rules[1].oneOf.map(rule=>{
96
- if(!rule.use) return;
97
- if(rule.use.find(x=>x.loader.indexOf('postcss-loader'))) {
98
- rule.use.unshift({
99
- loader: MiniCssExtractPlugin.loader,
100
- options: {},
101
- })
102
- }
103
- })
104
- }
105
- const newEntry=APP_PATH+'/src/index.jsx'
106
- if(typeof base.entry==='string') {
107
- base.entry=newEntry
108
- }else if(Array.isArray(base.entry)) {
109
- base.entry[base.entry.length-1]=newEntry
110
- }
111
- }
112
-
113
- if(!IS_DEV) {
114
- webpackConfig.externals=isServer? {
115
- react: 'react',
116
- 'react-dom': 'react-dom',
117
- }: {
118
- react: 'React',
119
- 'react-dom': 'ReactDom',
120
- }
121
- }
122
-
123
- base.resolve.alias=Object.assign(base.resolve.alias, {
124
- '@': APP_PATH+'/src',
125
- src: APP_PATH+'/src',
126
- })
127
- base.output.chunkCallbackName='webpackChunk_'+Date.now().toString(36)
128
- base.output.jsonpFunction='webpackJsonp_'+Date.now().toString(36)
129
- if(!IS_DEV) {
130
- base.output.path=APP_PATH+'/dist'
131
- base.output.publicPath='/assets/app/'
132
- }
133
- const conf=Object.assign(Object.assign({}, base), webpackConfig)
134
- conf.devtool='none'
135
- return conf
136
- }
137
-
138
- function webpackDev(port=3000) {
139
- fs_extra.emptyDirSync(APP_PATH+'/dist')
140
- const createDevBase=requireNodeModuleFile('react-scripts/config/webpackDevServer.config')
141
- const devConfig=Object.assign({}, createDevBase(), {
142
- writeToDisk: fn=>fn.indexOf('server')>0,
143
- injectClient: true,
144
- disableHostCheck: true,
145
- index: '',
146
- proxy: {
147
- context: ['/'],
148
- target: 'http://127.0.0.1:9090/',
149
- },
150
- })
151
-
152
- const clientConfig=createWebpackConfig({isServer: false})
153
- const serverConfig=createWebpackConfig({isServer: true})
154
- const config=[clientConfig, serverConfig]
155
- const multiCompiler=webpack(config)
156
-
157
- multiCompiler.hooks.done.tap('done', stats=>{
158
- const [clientStats, serverStats] = stats.toJson({
159
- all: false,
160
- warnings: true,
161
- errors: true,
162
- modules: false,
163
- entrypoints: true,
164
- publicPath: false,
165
- }).children
166
- const errors=[...clientStats.errors, ...serverStats.errors]
167
- const warnings=[...clientStats.warnings, ...serverStats.warnings]
168
-
169
- if(errors.length) {
170
- console.log(chalk.red('Failed to compile.\n'))
171
- console.log(errors[0])
172
- }else if(warnings.length) {
173
- console.log(chalk.yellow('Compiled with warnings.\n'))
174
- console.log(warnings.join('\n\n'))
175
- }else{
176
- const hot=clientStats.entrypoints.main.assets.find(x=>x.endsWith('.hot-update.js'))
177
- const ret={
178
- srv: '/server/index.js',
179
- js: '/static/js/bundle.js',
180
- css: '/static/css/main.css',
181
- hot: hot? '/'+hot: '',
182
- }
183
- fs.writeFileSync(APP_PATH+'/dist/assets.json', JSON.stringify(ret))
184
-
185
- console.log(chalk.green('Compiled successfully!'))
186
- }
187
- })
188
-
189
- const WebpackDevServer=require('webpack-dev-server')
190
- const devServer=new WebpackDevServer(multiCompiler, devConfig)
191
- devServer.listen(port, '0.0.0.0', e=>{
192
- if(e) throw e
193
- devServer.middleware.waitUntilValid(_=>{
194
- console.log(`> Ready on http://0.0.0.0:${port}`)
195
- })
196
- })
197
- }
198
-
199
- function webpackBuild() {
200
- fs_extra.emptyDirSync(APP_PATH+'/dist')
201
- const clientConfig=createWebpackConfig({isServer: false, env: 'production'})
202
- const serverConfig=createWebpackConfig({isServer: true, env: 'production'})
203
- const config=[clientConfig, serverConfig]
204
- const multiCompiler=webpack(config)
205
-
206
- multiCompiler.run((err, multiStats)=>{
207
- if(err) {
208
- throw err
209
- }
210
- if(multiStats.hasErrors()) {
211
- const message = multiStats.toJson({ all: false, errors: true }).errors.join('\n')
212
- throw new Error(message)
213
- }
214
-
215
- const [clientStats]=multiStats.toJson({
216
- all: false,
217
- warnings: false,
218
- errors: false,
219
- modules: false,
220
- entrypoints: true,
221
- publicPath: false,
222
- }).children
223
- const _f=re=>clientStats.entrypoints.main.assets.find(x=>x.match(re))
224
- const ret={
225
- srv: 'server/index.js',
226
- js: _f(/main\..+?\.js$/),
227
- css: _f(/main\..+?\.css$/),
228
- }
229
- fs.writeFileSync(APP_PATH+'/dist/assets.json', JSON.stringify(ret))
230
- const srv_dist=path.resolve(APP_PATH+'/server/public/app')
231
- fs_extra.emptyDirSync(srv_dist)
232
- fs_extra.moveSync(APP_PATH+'/dist', srv_dist, {overwrite: true})
233
-
234
- console.info(multiStats.toString({ colors: true }))
235
- })
236
-
237
- }
238
-
239
- module.exports={
240
- webpackDev,
241
- webpackBuild,
242
- }