hw-weapp-compiler 1.0.0

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.
package/build/prod.js ADDED
@@ -0,0 +1,34 @@
1
+ const chalk = require('chalk');
2
+ const webpack = require('webpack');
3
+ const ENV = require('./config/env');
4
+ const webpackConfig = require('./webpack.config');
5
+
6
+ module.exports = (opts) => {
7
+ const compiler = webpack(
8
+ webpackConfig(
9
+ {
10
+ mode: ENV.PROD,
11
+ devtool: 'cheap-module-source-map',
12
+ },
13
+ opts || {},
14
+ ),
15
+ );
16
+
17
+ compiler.run((err, stats) => {
18
+ if (err) {
19
+ console.error(err);
20
+ return;
21
+ }
22
+
23
+ if (stats.hasErrors()) {
24
+ console.log(
25
+ stats.toString({
26
+ chunks: false, // Makes the build much quieter
27
+ colors: true, // Shows colors in the console
28
+ }),
29
+ );
30
+ }
31
+
32
+ console.log(chalk.green(`completed in ${(stats.endTime - stats.startTime) / 1000} seconds`));
33
+ });
34
+ };
@@ -0,0 +1,31 @@
1
+ const ENV = require('../config/env');
2
+ const recordEnv = require('./recordEnv');
3
+
4
+ let env = '';
5
+
6
+ function setBuildEnv({ mode, development, simulation, production }) {
7
+ env = mode;
8
+
9
+ if (development) {
10
+ env = ENV.DEV;
11
+ }
12
+ if (simulation) {
13
+ env = ENV.SIMULATION;
14
+ }
15
+ if (production) {
16
+ env = ENV.PROD;
17
+ }
18
+
19
+ recordEnv({
20
+ env,
21
+ });
22
+ }
23
+
24
+ function getBuildEnv() {
25
+ return env;
26
+ }
27
+
28
+ module.exports = {
29
+ setBuildEnv,
30
+ getBuildEnv,
31
+ };
@@ -0,0 +1,13 @@
1
+ const os = require('os');
2
+
3
+ const platform = os.platform();
4
+
5
+ function compatiblePath(str) {
6
+ if (platform === 'win32') {
7
+ // path.win32.normalize()
8
+ return str.replace(/\\/g, '/');
9
+ }
10
+ return str;
11
+ }
12
+
13
+ module.exports = compatiblePath;
@@ -0,0 +1,107 @@
1
+ const htmlparser2 = require('htmlparser2');
2
+ const path = require('path');
3
+ const fse = require('fs-extra');
4
+ const getResourceAccept = require('../config/getResourceAccept');
5
+ const getContext = require('../config/getContext');
6
+
7
+ const context = getContext();
8
+
9
+ function getWxmlAssets(filePath, content) {
10
+ const resolvePath = (attr, dir) => {
11
+ // console.log('-------------');
12
+ // console.log(attr, dir);
13
+ // console.log('-------------');
14
+ return new Promise((resolve) => {
15
+ this.resolve(context, attr, async (err, result) => {
16
+ let res = result;
17
+ if (err) {
18
+ if (await fse.pathExists(path.resolve(dir, attr))) {
19
+ res = path.resolve(dir, attr);
20
+ resolve(res);
21
+ } else {
22
+ // console.log('-------------');
23
+ // console.log(attr);
24
+ this.emitError(err);
25
+ // this.emitWarning(err);
26
+ // reject(err);
27
+ resolve(res);
28
+ }
29
+ } else {
30
+ resolve(res);
31
+ }
32
+ });
33
+ });
34
+ };
35
+ return new Promise((resolve, reject) => {
36
+ let allAttrs = [];
37
+ const parser = new htmlparser2.Parser({
38
+ onopentag: async (name, attributes) => {
39
+ const reg = /url\(.*\)/g;
40
+ const { style } = attributes;
41
+
42
+ allAttrs = allAttrs.concat(
43
+ Object.values({
44
+ ...attributes,
45
+ style: '',
46
+ }),
47
+ );
48
+
49
+ if (style) {
50
+ const styles = attributes.style.split(';');
51
+ styles.forEach((styleItem) => {
52
+ (styleItem.match(reg) || []).forEach((item) => {
53
+ allAttrs.push(
54
+ item
55
+ .replace(/^(url\(”)/g, '')
56
+ .replace(/^(url\(')/g, '')
57
+ .replace(/^(url\()/g, '')
58
+ .replace(/(“\)|'\)|\))$/g, ''),
59
+ );
60
+ });
61
+ });
62
+ }
63
+ },
64
+ onerror: (err) => {
65
+ reject(err);
66
+ },
67
+ onend: async () => {
68
+ const filteredAttrs = allAttrs
69
+ .filter((item) => !!item)
70
+ .map((item) => item.split('?')[0])
71
+ .filter((item) => !/^(http:|https:)/.test(item))
72
+ .filter((item) => !/{{.*}}/g.test(item))
73
+ .filter((item) => !/\+.*\+/g.test(item));
74
+
75
+ const assets = filteredAttrs.filter((item) => getResourceAccept().test(item));
76
+ const wxmls = allAttrs.filter((item) => /\.(wxs|wxml)$/g.test(item));
77
+
78
+ const assetsImports = [];
79
+ const wxmlsImports = [];
80
+
81
+ for (let index = 0; index < wxmls.length; index += 1) {
82
+ const attr = wxmls[index];
83
+ const result = await resolvePath(attr, path.parse(filePath).dir);
84
+
85
+ if (result) {
86
+ wxmlsImports.push([attr, result]);
87
+ }
88
+ }
89
+
90
+ for (let index = 0; index < assets.length; index += 1) {
91
+ const attr = assets[index];
92
+ const result = await resolvePath(attr, path.parse(filePath).dir);
93
+
94
+ if (result) {
95
+ assetsImports.push([attr, result]);
96
+ }
97
+ }
98
+
99
+ resolve([assetsImports, wxmlsImports]);
100
+ },
101
+ });
102
+ parser.write(content);
103
+ parser.end();
104
+ });
105
+ }
106
+
107
+ module.exports = getWxmlAssets;
@@ -0,0 +1,17 @@
1
+ const nodeModulesUsingComponent = [];
2
+
3
+ function isNodeModulesUsingComponent(name) {
4
+ const key = name.replace(/\.(js|wxml|wxss|json|wxs)$/g, '');
5
+ const nmIndex = key.indexOf('node_modules/');
6
+ const searchKey = nmIndex !== -1 ? key.substring(nmIndex + 'node_modules/'.length) : key;
7
+ return nodeModulesUsingComponent.indexOf(searchKey) !== -1;
8
+ }
9
+
10
+ function addNodeModulesUsingComponent(item) {
11
+ nodeModulesUsingComponent.push(item);
12
+ }
13
+
14
+ module.exports = {
15
+ isNodeModulesUsingComponent,
16
+ addNodeModulesUsingComponent,
17
+ };
@@ -0,0 +1,22 @@
1
+ const compatiblePath = require('./compatiblePath');
2
+ const getAppConfig = require('../config/getAppConfig');
3
+
4
+ const appConfig = getAppConfig();
5
+
6
+ function isSubpackage(file) {
7
+ let isSub = false;
8
+
9
+ (appConfig.subpackages || []).forEach((pkg) => {
10
+ let { root } = pkg;
11
+
12
+ if (!/\/$/g.test(root)) {
13
+ root = `${root}/`;
14
+ }
15
+
16
+ if (compatiblePath(file).indexOf(root) === 0) {
17
+ isSub = true;
18
+ }
19
+ });
20
+ return isSub;
21
+ }
22
+ module.exports = isSubpackage;
@@ -0,0 +1,19 @@
1
+ function loadModule(file) {
2
+ return new Promise((resolve) => {
3
+ this.addDependency(file);
4
+ this.loadModule(file, (err, src) => {
5
+ if (err) {
6
+ // console.log();
7
+ // console.log(file, this.resourcePath);
8
+ // console.log();
9
+ this.emitError(err);
10
+ // this.emitWarning(err);
11
+ // reject(err);
12
+ resolve(src);
13
+ } else {
14
+ resolve(src);
15
+ }
16
+ });
17
+ });
18
+ }
19
+ module.exports = loadModule;
@@ -0,0 +1,11 @@
1
+ const fs = require('fs-extra');
2
+ const path = require('path');
3
+ const getOutput = require('../config/getOutput');
4
+ const ENV = require('../config/env');
5
+
6
+ module.exports = (config) => {
7
+ fs.writeJSONSync(path.join(getOutput(), 'weapp.env.json'), {
8
+ env: ENV.DEV,
9
+ ...config,
10
+ });
11
+ };
@@ -0,0 +1,29 @@
1
+ const path = require('path');
2
+ const fs = require('fs-extra');
3
+ const { debounce } = require('throttle-debounce');
4
+
5
+ const tempDir = path.resolve(process.cwd(), '.temp');
6
+ const uploadJsonDir = path.join(tempDir, 'upload.json');
7
+ let uploadJson = {};
8
+ const writeUploadJsonDebounce = debounce(300, () => {
9
+ fs.writeJSONSync(uploadJsonDir, uploadJson);
10
+ });
11
+
12
+ if (!fs.existsSync(tempDir)) {
13
+ fs.mkdirSync(tempDir);
14
+ }
15
+ if (!fs.existsSync(uploadJsonDir)) {
16
+ fs.writeJSONSync(uploadJsonDir, uploadJson);
17
+ } else {
18
+ uploadJson = fs.readJSONSync(uploadJsonDir);
19
+ }
20
+
21
+ module.exports = {
22
+ getStorage(key) {
23
+ return uploadJson[key];
24
+ },
25
+ setStorage(key, value) {
26
+ uploadJson[key] = value;
27
+ writeUploadJsonDebounce();
28
+ },
29
+ };
@@ -0,0 +1,21 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+
4
+ function traverseDir(dir) {
5
+ let result = [];
6
+ const files = fs.readdirSync(dir);
7
+
8
+ files.forEach((file) => {
9
+ const fullPath = path.resolve(dir, file);
10
+
11
+ if (fs.statSync(fullPath).isDirectory()) {
12
+ result = result.concat(traverseDir(fullPath));
13
+ } else {
14
+ result.push(fullPath);
15
+ }
16
+ });
17
+
18
+ return result;
19
+ }
20
+
21
+ module.exports = traverseDir;
@@ -0,0 +1,194 @@
1
+ const path = require('path');
2
+ const OBSClient = require('esdk-obs-nodejs');
3
+ const OSSClient = require('ali-oss');
4
+ // const chalk = require('chalk');
5
+ const Progress = require('progress');
6
+ const getConfig = require('../config/getConfig');
7
+
8
+ const { getStorage, setStorage } = require('./storage');
9
+ const compatiblePath = require('./compatiblePath');
10
+ const getOutput = require('../config/getOutput');
11
+
12
+ const output = getOutput();
13
+ const { obsConfig, ossConfig } = getConfig();
14
+
15
+ let obsClient;
16
+ let ossClient;
17
+ let progress;
18
+ let uploadQueue = {};
19
+
20
+ function getObsClient() {
21
+ if (!obsClient) {
22
+ obsClient = new OBSClient({
23
+ ...obsConfig,
24
+ });
25
+ }
26
+ return obsClient;
27
+ }
28
+
29
+ function getOssClient() {
30
+ if (!ossClient) {
31
+ ossClient = new OSSClient({
32
+ ...ossConfig,
33
+ });
34
+ }
35
+ return ossClient;
36
+ }
37
+
38
+ function doOssUpload(file) {
39
+ return getOssClient().put(
40
+ compatiblePath(path.join(ossConfig.dir, path.relative(output, file))),
41
+ file,
42
+ );
43
+ }
44
+
45
+ function getOssStat(file) {
46
+ return getOssClient().head(compatiblePath(path.join(ossConfig.dir, path.relative(output, file))));
47
+ }
48
+
49
+ function doObsUpload(file) {
50
+ return new Promise((resolve, reject) => {
51
+ getObsClient().putObject(
52
+ {
53
+ Bucket: obsConfig.bucket,
54
+ Key: compatiblePath(path.join(obsConfig.dir, path.relative(output, file))),
55
+ SourceFile: file,
56
+ },
57
+ (err, result) => {
58
+ if (err) {
59
+ reject(err);
60
+ // console.log(chalk.red("上传失败"), file);
61
+ } else if (result.CommonMsg.Status >= 300) {
62
+ reject(new Error(`OBS upload failed with status ${result.CommonMsg.Status}`));
63
+ // console.log(chalk.red("上传失败"), file);
64
+ } else {
65
+ resolve(result);
66
+ // console.log(chalk.green("上传成功"), file);
67
+ }
68
+ },
69
+ );
70
+ });
71
+ }
72
+ async function getObsStat(file) {
73
+ return new Promise((resolve, reject) => {
74
+ getObsClient().getObjectMetadata(
75
+ {
76
+ Bucket: obsConfig.bucket,
77
+ Key: compatiblePath(path.join(obsConfig.dir, path.relative(output, file))),
78
+ },
79
+ (err, result) => {
80
+ if (err) {
81
+ reject(err);
82
+ } else if (result.CommonMsg.Status < 300) {
83
+ resolve(result);
84
+ } else {
85
+ reject(result);
86
+ }
87
+ },
88
+ );
89
+ });
90
+ }
91
+
92
+ function getStat(file) {
93
+ const isUploaded = !!getStorage(file);
94
+
95
+ if (isUploaded) {
96
+ return Promise.resolve();
97
+ }
98
+
99
+ if (ossConfig) {
100
+ return getOssStat(file);
101
+ }
102
+ return getObsStat(file);
103
+ }
104
+
105
+ function doUpload(file) {
106
+ if (ossConfig) {
107
+ return doOssUpload(file);
108
+ }
109
+ return doObsUpload(file);
110
+ }
111
+
112
+ function updateProgress() {
113
+ const completed =
114
+ Object.entries(uploadQueue).filter((item) => item[1] === 'completed').length + 1;
115
+ const total = Object.keys(uploadQueue).length;
116
+
117
+ if (!progress) {
118
+ progress = new Progress('uploading assets [:bar] :current/:total', {
119
+ total,
120
+ width: 40,
121
+ clear: true,
122
+ });
123
+ }
124
+
125
+ progress.tick();
126
+
127
+ if (completed === total) {
128
+ progress.tick({
129
+ current: total,
130
+ });
131
+ progress = null;
132
+ uploadQueue = {};
133
+ // setTimeout(() => {
134
+ // console.log(chalk.green('assets upload completed'));
135
+ // }, 0);
136
+ }
137
+
138
+ return `[${completed}/${total}]`;
139
+ }
140
+
141
+ async function checkUpload() {
142
+ const files = Object.entries(uploadQueue)
143
+ .filter((item) => item[1] === false)
144
+ .splice(0, 10);
145
+
146
+ if (files && files.length) {
147
+ await Promise.all(
148
+ files.map(async (file) => {
149
+ uploadQueue[file[0]] = 'uploading';
150
+ try {
151
+ await getStat(file[0]);
152
+ setStorage(file[0], true);
153
+ updateProgress();
154
+ // console.log(
155
+ // chalk.blue(`${publicPath}${path.relative(output, file[0])} ${updateProgress()}`),
156
+ // );
157
+ } catch (error) {
158
+ try {
159
+ await doUpload(file[0]);
160
+ setStorage(file[0], true);
161
+ } catch (uploadError) {
162
+ console.error(`Failed to upload ${file[0]}:`, uploadError);
163
+ }
164
+ updateProgress();
165
+ // console.log(
166
+ // chalk.green(`${publicPath}${path.relative(output, file[0])} ${updateProgress()}`),
167
+ // );
168
+ }
169
+ uploadQueue[file[0]] = 'completed';
170
+ }),
171
+ );
172
+
173
+ checkUpload();
174
+ }
175
+ }
176
+
177
+ function addToUploadQueue(assets) {
178
+ if (!obsConfig && !ossConfig) {
179
+ console.warn('请配置obsConfig 或 ossConfig,否则无法上传文件到obs 或 oss');
180
+ return;
181
+ }
182
+
183
+ assets.forEach((asset) => {
184
+ const file = path.resolve(output, asset);
185
+ if (uploadQueue[file] === undefined) {
186
+ uploadQueue[file] = false;
187
+ }
188
+ });
189
+ checkUpload();
190
+ }
191
+
192
+ module.exports = {
193
+ addToUploadQueue,
194
+ };