@shuvi/toolpack 0.0.1-pre.1

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 (65) hide show
  1. package/lib/babel/plugins/auto-css-modules.d.ts +7 -0
  2. package/lib/babel/plugins/auto-css-modules.js +24 -0
  3. package/lib/babel/plugins/jsx-pragma.d.ts +4 -0
  4. package/lib/babel/plugins/jsx-pragma.js +77 -0
  5. package/lib/babel/plugins/loadable-plugin.d.ts +24 -0
  6. package/lib/babel/plugins/loadable-plugin.js +105 -0
  7. package/lib/babel/plugins/optimize-hook-destructuring.d.ts +4 -0
  8. package/lib/babel/plugins/optimize-hook-destructuring.js +59 -0
  9. package/lib/babel/preset.d.ts +14 -0
  10. package/lib/babel/preset.js +106 -0
  11. package/lib/constants.d.ts +1 -0
  12. package/lib/constants.js +3 -0
  13. package/lib/utils/emptyComponent.d.ts +1 -0
  14. package/lib/utils/emptyComponent.js +7 -0
  15. package/lib/utils/forkTsCheckerWebpackPlugin.d.ts +4 -0
  16. package/lib/utils/forkTsCheckerWebpackPlugin.js +9 -0
  17. package/lib/utils/formatWebpackMessages.d.ts +5 -0
  18. package/lib/utils/formatWebpackMessages.js +91 -0
  19. package/lib/utils/hotDevClient/eventsource.d.ts +1 -0
  20. package/lib/utils/hotDevClient/eventsource.js +63 -0
  21. package/lib/utils/hotDevClient/index.d.ts +4 -0
  22. package/lib/utils/hotDevClient/index.js +304 -0
  23. package/lib/utils/verifyTypeScriptSetup.d.ts +5 -0
  24. package/lib/utils/verifyTypeScriptSetup.js +229 -0
  25. package/lib/webpack/config/base.d.ts +16 -0
  26. package/lib/webpack/config/base.js +236 -0
  27. package/lib/webpack/config/browser.d.ts +8 -0
  28. package/lib/webpack/config/browser.js +147 -0
  29. package/lib/webpack/config/index.d.ts +4 -0
  30. package/lib/webpack/config/index.js +9 -0
  31. package/lib/webpack/config/node.d.ts +7 -0
  32. package/lib/webpack/config/node.js +55 -0
  33. package/lib/webpack/config/parts/external.d.ts +4 -0
  34. package/lib/webpack/config/parts/external.js +91 -0
  35. package/lib/webpack/config/parts/helpers.d.ts +3 -0
  36. package/lib/webpack/config/parts/helpers.js +48 -0
  37. package/lib/webpack/config/parts/resolve.d.ts +1 -0
  38. package/lib/webpack/config/parts/resolve.js +10 -0
  39. package/lib/webpack/config/parts/style.d.ts +9 -0
  40. package/lib/webpack/config/parts/style.js +217 -0
  41. package/lib/webpack/loaders/export-global-loader.d.ts +7 -0
  42. package/lib/webpack/loaders/export-global-loader.js +26 -0
  43. package/lib/webpack/loaders/route-component-loader.d.ts +7 -0
  44. package/lib/webpack/loaders/route-component-loader.js +14 -0
  45. package/lib/webpack/loaders/shuvi-babel-loader.d.ts +1 -0
  46. package/lib/webpack/loaders/shuvi-babel-loader.js +60 -0
  47. package/lib/webpack/plugins/build-manifest-plugin.d.ts +27 -0
  48. package/lib/webpack/plugins/build-manifest-plugin.js +215 -0
  49. package/lib/webpack/plugins/chunk-names-plugin.d.ts +4 -0
  50. package/lib/webpack/plugins/chunk-names-plugin.js +43 -0
  51. package/lib/webpack/plugins/fix-watching-plugin.d.ts +4 -0
  52. package/lib/webpack/plugins/fix-watching-plugin.js +23 -0
  53. package/lib/webpack/plugins/module-replace-plugin/index.d.ts +1 -0
  54. package/lib/webpack/plugins/module-replace-plugin/index.js +4 -0
  55. package/lib/webpack/plugins/module-replace-plugin/plugin.d.ts +31 -0
  56. package/lib/webpack/plugins/module-replace-plugin/plugin.js +177 -0
  57. package/lib/webpack/plugins/module-replace-plugin/stub-loader.d.ts +1 -0
  58. package/lib/webpack/plugins/module-replace-plugin/stub-loader.js +34 -0
  59. package/lib/webpack/plugins/prefer-resolver-plugin.d.ts +10 -0
  60. package/lib/webpack/plugins/prefer-resolver-plugin.js +47 -0
  61. package/lib/webpack/plugins/require-cache-hot-reloader-plugin.d.ts +6 -0
  62. package/lib/webpack/plugins/require-cache-hot-reloader-plugin.js +48 -0
  63. package/lib/webpack/types.d.ts +40 -0
  64. package/lib/webpack/types.js +2 -0
  65. package/package.json +80 -0
@@ -0,0 +1,236 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const webpack_chain_1 = __importDefault(require("webpack-chain"));
7
+ exports.WebpackChain = webpack_chain_1.default;
8
+ const terser_webpack_plugin_1 = __importDefault(require("terser-webpack-plugin"));
9
+ const webpack_1 = __importDefault(require("webpack"));
10
+ const path_1 = __importDefault(require("path"));
11
+ const constants_1 = require("@shuvi/shared/lib/constants");
12
+ const detectTypescript_1 = require("@shuvi/utils/lib/detectTypescript");
13
+ const escapeRegExp_1 = require("@shuvi/utils/lib/escapeRegExp");
14
+ const build_manifest_plugin_1 = __importDefault(require("../plugins/build-manifest-plugin"));
15
+ const module_replace_plugin_1 = __importDefault(require("../plugins/module-replace-plugin"));
16
+ const chunk_names_plugin_1 = __importDefault(require("../plugins/chunk-names-plugin"));
17
+ const fix_watching_plugin_1 = __importDefault(require("../plugins/fix-watching-plugin"));
18
+ const require_cache_hot_reloader_plugin_1 = __importDefault(require("../plugins/require-cache-hot-reloader-plugin"));
19
+ const constants_2 = require("../../constants");
20
+ const crypto_1 = __importDefault(require("crypto"));
21
+ const dumbRouteComponent = require.resolve('../../utils/emptyComponent');
22
+ const resolveLocalLoader = (name) => path_1.default.join(__dirname, `../loaders/${name}`);
23
+ const terserOptions = {
24
+ parse: {
25
+ ecma: 2017 // es8 === 2017
26
+ },
27
+ compress: {
28
+ ecma: 5,
29
+ // The following two options are known to break valid JavaScript code
30
+ comparisons: false,
31
+ inline: 2 // https://github.com/zeit/next.js/issues/7178#issuecomment-493048965
32
+ },
33
+ mangle: { safari10: true },
34
+ output: {
35
+ ecma: 5,
36
+ safari10: true,
37
+ comments: false,
38
+ // Fixes usage of Emoji and certain Regex
39
+ ascii_only: true
40
+ }
41
+ };
42
+ function baseWebpackChain({ dev, projectRoot, srcDirs, mediaFilename, name, buildManifestFilename, publicPath = '/', env = {} }) {
43
+ const { typeScriptPath, tsConfigPath, useTypeScript } = detectTypescript_1.getTypeScriptInfo(projectRoot);
44
+ const config = new webpack_chain_1.default();
45
+ config.mode(dev ? 'development' : 'production');
46
+ config.bail(!dev);
47
+ config.performance.hints(false);
48
+ config.context(projectRoot);
49
+ config.optimization.merge({
50
+ emitOnErrors: !dev,
51
+ checkWasmTypes: false,
52
+ nodeEnv: false,
53
+ splitChunks: false,
54
+ runtimeChunk: undefined,
55
+ minimize: !dev,
56
+ realContentHash: false
57
+ });
58
+ if (!dev) {
59
+ config.optimization.minimizer('terser').use(terser_webpack_plugin_1.default, [
60
+ {
61
+ extractComments: false,
62
+ parallel: true,
63
+ terserOptions
64
+ }
65
+ ]);
66
+ }
67
+ config.output.merge({
68
+ publicPath,
69
+ hotUpdateChunkFilename: 'static/webpack/[id].[fullhash].hot-update.js',
70
+ hotUpdateMainFilename: 'static/webpack/[fullhash].hot-update.json',
71
+ // This saves chunks with the name given via `import()`
72
+ chunkFilename: `static/chunks/${dev ? '[name]' : '[name].[contenthash:8]'}.js`,
73
+ strictModuleExceptionHandling: true,
74
+ // crossOriginLoading: crossOrigin,
75
+ webassemblyModuleFilename: 'static/wasm/[modulehash:8].wasm'
76
+ });
77
+ // Support for NODE_PATH
78
+ const nodePathList = (process.env.NODE_PATH || '')
79
+ .split(process.platform === 'win32' ? ';' : ':')
80
+ .filter(p => !!p);
81
+ config.resolve.merge({
82
+ modules: [
83
+ 'node_modules',
84
+ ...nodePathList // Support for NODE_PATH environment variable
85
+ ],
86
+ alias: {}
87
+ });
88
+ config.resolveLoader.merge({
89
+ alias: ['shuvi-babel-loader', 'route-component-loader'].reduce((alias, loader) => {
90
+ alias[`@shuvi/${loader}`] = resolveLocalLoader(loader);
91
+ return alias;
92
+ }, {})
93
+ });
94
+ config.module.set('strictExportPresence', true);
95
+ const mainRule = config.module.rule('main');
96
+ // TODO: FIXME: await babel/babel-loader to update to fix this.
97
+ // x-ref: https://github.com/webpack/webpack/issues/11467
98
+ config.module
99
+ .rule('webpackPatch')
100
+ .test(/\.m?js/)
101
+ .resolve.set('fullySpecified', false);
102
+ mainRule
103
+ .oneOf('js')
104
+ .test(/\.(tsx|ts|js|mjs|jsx)$/)
105
+ .include.merge([...srcDirs, ...constants_2.AppSourceRegexs])
106
+ .end()
107
+ .exclude.add((path) => {
108
+ if (constants_2.AppSourceRegexs.some(r => r.test(path))) {
109
+ return false;
110
+ }
111
+ if (srcDirs.some(src => path.includes(src))) {
112
+ return false;
113
+ }
114
+ return /node_modules/.test(path);
115
+ })
116
+ .end()
117
+ .use('shuvi-babel-loader')
118
+ .loader('@shuvi/shuvi-babel-loader')
119
+ .options({
120
+ isNode: false,
121
+ // webpack 5 have in-built cache.
122
+ cacheDirectory: false
123
+ });
124
+ mainRule
125
+ .oneOf('media')
126
+ .exclude.merge([/\.(js|mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/])
127
+ .end()
128
+ .use('file-loader')
129
+ .loader(require.resolve('file-loader'))
130
+ .options({
131
+ name: mediaFilename
132
+ });
133
+ config.plugin('chunk-names').use(chunk_names_plugin_1.default);
134
+ config.plugin('private/ignore-plugin').use(webpack_1.default.IgnorePlugin, [
135
+ {
136
+ resourceRegExp: /^\.\/locale$/,
137
+ contextRegExp: /moment$/
138
+ }
139
+ ]);
140
+ const shuviPublicEnv = Object.keys(process.env).reduce((prev, key) => {
141
+ if (key.startsWith(constants_1.PUBLIC_ENV_PREFIX)) {
142
+ prev[`process.env.${key}`] = JSON.stringify(process.env[key]);
143
+ }
144
+ return prev;
145
+ }, {});
146
+ const shuviConfigEnv = Object.keys(env).reduce((acc, key) => {
147
+ if (/^(?:NODE_.+)|^(?:__.+)$/i.test(key)) {
148
+ throw new Error(`The key "${key}" under "env" is not allowed.`);
149
+ }
150
+ return Object.assign(Object.assign({}, acc), { [`process.env.${key}`]: JSON.stringify(env[key]) });
151
+ }, {});
152
+ config.plugin('define').use(webpack_1.default.DefinePlugin, [
153
+ Object.assign(Object.assign(Object.assign({}, shuviPublicEnv), shuviConfigEnv), { 'process.env.NODE_ENV': JSON.stringify(dev ? 'development' : 'production') })
154
+ ]);
155
+ config
156
+ .plugin('private/build-manifest')
157
+ .use(build_manifest_plugin_1.default, [
158
+ { filename: buildManifestFilename, chunkRequest: dev }
159
+ ]);
160
+ if (useTypeScript) {
161
+ config
162
+ .plugin('private/fork-ts-checker-webpack-plugin')
163
+ .use(require.resolve('fork-ts-checker-webpack-plugin'), [
164
+ {
165
+ typescript: {
166
+ configFile: tsConfigPath,
167
+ typeScriptPath,
168
+ diagnosticOptions: {
169
+ syntactic: true
170
+ }
171
+ },
172
+ async: dev,
173
+ logger: {
174
+ infrastructure: 'silent',
175
+ issues: 'silent',
176
+ devServer: false
177
+ },
178
+ formatter: 'codeframe'
179
+ }
180
+ ]);
181
+ }
182
+ const getCacheConfig = () => {
183
+ const projectHash = crypto_1.default
184
+ .createHash('md5')
185
+ .update(projectRoot)
186
+ .digest('hex');
187
+ const stringifiedEnvs = Object.entries(Object.assign(Object.assign({}, shuviConfigEnv), shuviPublicEnv)).reduce((prev, [key, value]) => {
188
+ return `${prev}|${key}=${value}`;
189
+ }, '');
190
+ const SHUVI_VERSION = require('shuvi/package.json').version;
191
+ return {
192
+ cacheDirectory: path_1.default.resolve(`node_modules/.cache/webpack/${projectHash}`),
193
+ type: 'filesystem',
194
+ name: `${name.replace(/\//, '-')}-${config.get('mode')}`,
195
+ version: `${SHUVI_VERSION}|${stringifiedEnvs}`
196
+ };
197
+ };
198
+ config.cache(typeof process.env.SHUVI_DEV_DISABLE_CACHE !== 'undefined'
199
+ ? false
200
+ : getCacheConfig());
201
+ if (dev) {
202
+ // For webpack-dev-middleware usage
203
+ config.watchOptions({
204
+ // timeout 300 will make hmr.test to failed, set to 350
205
+ aggregateTimeout: 350,
206
+ ignored: ['**/.git/**', '**/node_modules/**']
207
+ });
208
+ config.set('infrastructureLogging', {
209
+ level: 'none'
210
+ });
211
+ config.plugin('private/fix-watching-plugin').use(fix_watching_plugin_1.default);
212
+ config.plugin('private/module-replace-plugin').use(module_replace_plugin_1.default, [
213
+ {
214
+ modules: [
215
+ {
216
+ resourceQuery: RegExp(escapeRegExp_1.escapeRegExp(`?${constants_1.ROUTE_RESOURCE_QUERYSTRING}`)),
217
+ module: dumbRouteComponent
218
+ }
219
+ ]
220
+ }
221
+ ]);
222
+ // Even though require.cache is server only we have to clear assets from both compilations
223
+ // This is because the client compilation generates the build manifest that's used on the server side
224
+ config
225
+ .plugin('private/require-cache-hot-reloader')
226
+ .use(require_cache_hot_reloader_plugin_1.default);
227
+ config.optimization.usedExports(false);
228
+ }
229
+ else {
230
+ config
231
+ .plugin('private/hashed-moduleids-plugin')
232
+ .use(webpack_1.default.ids.HashedModuleIdsPlugin);
233
+ }
234
+ return config;
235
+ }
236
+ exports.baseWebpackChain = baseWebpackChain;
@@ -0,0 +1,8 @@
1
+ import WebpackChain from 'webpack-chain';
2
+ import { BaseOptions } from './base';
3
+ import { IWebpackHelpers } from '../types';
4
+ export interface BrowserOptions extends BaseOptions {
5
+ webpackHelpers: IWebpackHelpers;
6
+ analyze?: boolean;
7
+ }
8
+ export declare function createBrowserWebpackChain({ webpackHelpers, ...baseOptions }: BrowserOptions): WebpackChain;
@@ -0,0 +1,147 @@
1
+ "use strict";
2
+ var __rest = (this && this.__rest) || function (s, e) {
3
+ var t = {};
4
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
5
+ t[p] = s[p];
6
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
7
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
8
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
9
+ t[p[i]] = s[p[i]];
10
+ }
11
+ return t;
12
+ };
13
+ var __importDefault = (this && this.__importDefault) || function (mod) {
14
+ return (mod && mod.__esModule) ? mod : { "default": mod };
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ const crypto_1 = __importDefault(require("crypto"));
18
+ const webpack_1 = __importDefault(require("webpack"));
19
+ const webpack_bundle_analyzer_1 = require("webpack-bundle-analyzer");
20
+ const detectTypescript_1 = require("@shuvi/utils/lib/detectTypescript");
21
+ // import PreferResolverPlugin from '../plugins/prefer-resolver-plugin';
22
+ const base_1 = require("./base");
23
+ const style_1 = require("./parts/style");
24
+ const BIG_LIBRARY_THRESHOLD = 160000; // byte
25
+ function createBrowserWebpackChain(_a) {
26
+ var { webpackHelpers } = _a, baseOptions = __rest(_a, ["webpackHelpers"]);
27
+ const { dev, publicPath, analyze } = baseOptions;
28
+ const chain = base_1.baseWebpackChain(baseOptions);
29
+ const { useTypeScript } = detectTypescript_1.getTypeScriptInfo(baseOptions.projectRoot);
30
+ chain.target('web');
31
+ chain.devtool(dev ? 'cheap-module-source-map' : false);
32
+ chain.resolve.extensions.merge([
33
+ ...(useTypeScript ? ['.tsx', '.ts'] : []),
34
+ '.mjs',
35
+ '.js',
36
+ '.jsx',
37
+ '.json',
38
+ '.wasm'
39
+ ]);
40
+ // if (baseOptions.target) {
41
+ // chain.resolve
42
+ // .plugin('private/prefer-resolver-plugin')
43
+ // .use(PreferResolverPlugin, [{ suffix: baseOptions.target }]);
44
+ // }
45
+ if (dev) {
46
+ chain.plugin('private/hmr-plugin').use(webpack_1.default.HotModuleReplacementPlugin);
47
+ }
48
+ else {
49
+ chain.optimization.splitChunks({
50
+ chunks: 'all',
51
+ cacheGroups: {
52
+ default: false,
53
+ defaultVendors: false,
54
+ framework: {
55
+ chunks: 'all',
56
+ name: 'framework',
57
+ // This regex ignores nested copies of framework libraries so they're
58
+ // bundled with their issuer.
59
+ // https://github.com/zeit/next.js/pull/9012
60
+ test: /(?<!node_modules.*)[\\/]node_modules[\\/](react|react-dom|@shuvi\/router|@shuvi\/router-react|scheduler|prop-types|use-subscription|history)[\\/]/,
61
+ priority: 40,
62
+ // Don't let webpack eliminate this chunk (prevents this chunk from
63
+ // becoming a part of the commons chunk)
64
+ enforce: true
65
+ },
66
+ lib: {
67
+ test(module) {
68
+ return (module.size() > BIG_LIBRARY_THRESHOLD &&
69
+ /node_modules[/\\]/.test(module.identifier()));
70
+ },
71
+ name(module) {
72
+ const hash = crypto_1.default.createHash('sha1');
73
+ if (module.type === `css/mini-extract`) {
74
+ module.updateHash(hash);
75
+ }
76
+ else {
77
+ if (!module.libIdent) {
78
+ throw new Error(`Encountered unknown module type: ${module.type}. Please open an issue.`);
79
+ }
80
+ hash.update(module.libIdent({ context: baseOptions.projectRoot }));
81
+ }
82
+ return hash.digest('hex').substring(0, 8);
83
+ },
84
+ priority: 30,
85
+ minChunks: 1,
86
+ reuseExistingChunk: true
87
+ },
88
+ commons: {
89
+ name: 'commons',
90
+ minChunks: 2,
91
+ priority: 20
92
+ },
93
+ shared: {
94
+ name(module, chunks) {
95
+ return crypto_1.default
96
+ .createHash('sha1')
97
+ .update(chunks.reduce((acc, chunk) => {
98
+ return acc + chunk.name;
99
+ }, ''))
100
+ .digest('hex');
101
+ },
102
+ priority: 10,
103
+ minChunks: 2,
104
+ reuseExistingChunk: true
105
+ }
106
+ },
107
+ maxInitialRequests: 25,
108
+ minSize: 20000
109
+ });
110
+ if (analyze) {
111
+ chain.plugin('private/bundle-analyzer-plugin').use(webpack_bundle_analyzer_1.BundleAnalyzerPlugin, [
112
+ {
113
+ logLevel: 'warn',
114
+ openAnalyzer: false,
115
+ analyzerMode: 'static',
116
+ reportFilename: '../analyze/client.html'
117
+ }
118
+ ]);
119
+ }
120
+ }
121
+ chain.resolve.alias
122
+ .set('stream', require.resolve('stream-browserify'))
123
+ .set('path', require.resolve('path-browserify'))
124
+ .set('crypto', require.resolve('crypto-browserify'))
125
+ .set('buffer', require.resolve('buffer'))
126
+ .set('vm', require.resolve('vm-browserify'));
127
+ chain.plugin('node-buffer-polyfill').use(webpack_1.default.ProvidePlugin, [
128
+ {
129
+ Buffer: ['buffer', 'Buffer']
130
+ }
131
+ ]);
132
+ chain.plugin('node-process-polyfill').use(webpack_1.default.ProvidePlugin, [
133
+ {
134
+ process: ['process']
135
+ }
136
+ ]);
137
+ chain.plugin('define').tap(([options]) => [
138
+ Object.assign(Object.assign({}, options), { __BROWSER__: true,
139
+ // prevent errof of destructing process.env
140
+ 'process.env': JSON.stringify('{}') })
141
+ ]);
142
+ chain.plugin('private/build-manifest').tap(([options]) => [
143
+ Object.assign(Object.assign({}, options), { modules: true })
144
+ ]);
145
+ return style_1.withStyle(chain, { extractCss: !dev, publicPath });
146
+ }
147
+ exports.createBrowserWebpackChain = createBrowserWebpackChain;
@@ -0,0 +1,4 @@
1
+ export * from './base';
2
+ export * from './browser';
3
+ export * from './node';
4
+ export * from './parts/helpers';
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ function __export(m) {
3
+ for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
4
+ }
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ __export(require("./base"));
7
+ __export(require("./browser"));
8
+ __export(require("./node"));
9
+ __export(require("./parts/helpers"));
@@ -0,0 +1,7 @@
1
+ import WebpackChain from 'webpack-chain';
2
+ import { BaseOptions } from './base';
3
+ import { IWebpackHelpers } from '../types';
4
+ export interface NodeOptions extends BaseOptions {
5
+ webpackHelpers: IWebpackHelpers;
6
+ }
7
+ export declare function createNodeWebpackChain({ webpackHelpers, ...baseOptions }: NodeOptions): WebpackChain;
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ var __rest = (this && this.__rest) || function (s, e) {
3
+ var t = {};
4
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
5
+ t[p] = s[p];
6
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
7
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
8
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
9
+ t[p[i]] = s[p[i]];
10
+ }
11
+ return t;
12
+ };
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ const detectTypescript_1 = require("@shuvi/utils/lib/detectTypescript");
15
+ const base_1 = require("./base");
16
+ const external_1 = require("./parts/external");
17
+ const style_1 = require("./parts/style");
18
+ const resolve_1 = require("./parts/resolve");
19
+ function createNodeWebpackChain(_a) {
20
+ var { webpackHelpers } = _a, baseOptions = __rest(_a, ["webpackHelpers"]);
21
+ const chain = base_1.baseWebpackChain(baseOptions);
22
+ const { useTypeScript } = detectTypescript_1.getTypeScriptInfo(baseOptions.projectRoot);
23
+ chain.target('node');
24
+ chain.devtool(false);
25
+ const extensions = [
26
+ ...(useTypeScript ? ['.tsx', '.ts'] : []),
27
+ '.js',
28
+ '.mjs',
29
+ '.jsx',
30
+ '.json',
31
+ '.wasm'
32
+ ];
33
+ chain.resolve.extensions.merge(baseOptions.target
34
+ ? resolve_1.resolvePreferTarget(baseOptions.target, extensions)
35
+ : extensions);
36
+ // fix: Can't reexport the named export 'BREAK' from non EcmaScript module
37
+ // related issue: https://github.com/graphql/graphql-js/issues/1272
38
+ chain.resolve.mainFields.clear().add('main').add('module');
39
+ chain.output.libraryTarget('commonjs2');
40
+ chain.optimization.minimize(false);
41
+ webpackHelpers.addExternals(chain, external_1.nodeExternals({ projectRoot: baseOptions.projectRoot }));
42
+ chain.module
43
+ .rule('main')
44
+ .oneOf('js')
45
+ .use('shuvi-babel-loader')
46
+ .tap(options => (Object.assign(Object.assign({}, options), { isNode: true })));
47
+ chain.plugin('private/build-manifest').tap(([options]) => [
48
+ Object.assign(Object.assign({}, options), { modules: false })
49
+ ]);
50
+ chain.plugin('define').tap(([options]) => [
51
+ Object.assign(Object.assign({}, options), { __BROWSER__: false })
52
+ ]);
53
+ return style_1.withStyle(chain, { ssr: true });
54
+ }
55
+ exports.createNodeWebpackChain = createNodeWebpackChain;
@@ -0,0 +1,4 @@
1
+ import { ExternalsFunction } from '../../types';
2
+ export declare function nodeExternals({ projectRoot }: {
3
+ projectRoot: string;
4
+ }): ExternalsFunction;
@@ -0,0 +1,91 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ // import resolve from "resolve";
4
+ const constants_1 = require("../../../constants");
5
+ function match(value, tests) {
6
+ let matched = false;
7
+ for (let index = 0; index < tests.length; index++) {
8
+ const test = tests[index];
9
+ if (typeof test === 'string') {
10
+ matched = test === value;
11
+ }
12
+ else {
13
+ matched = value.match(test) !== null;
14
+ }
15
+ if (matched) {
16
+ return true;
17
+ }
18
+ else {
19
+ continue;
20
+ }
21
+ }
22
+ return matched;
23
+ }
24
+ function nodeExternals({ projectRoot }) {
25
+ const nodeExternal = ({ context, request }, next) => {
26
+ function transpiled() {
27
+ return next(null, undefined);
28
+ }
29
+ function external() {
30
+ return next(null, `commonjs ${request}`);
31
+ }
32
+ const notExternalModules = [];
33
+ const externalModules = [
34
+ /@shuvi[/\\]service[/\\]lib[/\\]lib[/\\]runtimeConfig/
35
+ ];
36
+ // make sure we don't externalize anything that is
37
+ // supposed to be transpiled
38
+ if (match(request, constants_1.AppSourceRegexs)) {
39
+ return transpiled();
40
+ }
41
+ if (match(request, notExternalModules)) {
42
+ return transpiled();
43
+ }
44
+ if (match(request, externalModules)) {
45
+ return external();
46
+ }
47
+ next(null, 'next');
48
+ // // Relative requires don't need custom resolution, because they
49
+ // // are relative to requests we've already resolved here.
50
+ // // Absolute requires (require('/foo')) are extremely uncommon, but
51
+ // // also have no need for customization as they're already resolved.
52
+ // const start = request.charAt(0);
53
+ // if (start === "." || request.startsWith("/")) {
54
+ // return transpiled();
55
+ // }
56
+ // let res;
57
+ // try {
58
+ // res = resolve.sync(request, { basedir: context });
59
+ // } catch (err) {
60
+ // // If the request cannot be resolved, we need to tell webpack to
61
+ // // "bundle" it so that webpack shows an error (that it cannot be
62
+ // // resolved).
63
+ // return transpiled();
64
+ // }
65
+ // if (!res) {
66
+ // return transpiled();
67
+ // }
68
+ // let baseRes;
69
+ // try {
70
+ // baseRes = resolve.sync(request, { basedir: projectRoot });
71
+ // } catch (err) {}
72
+ // if (baseRes !== res) {
73
+ // return transpiled();
74
+ // }
75
+ // // Webpack itself has to be compiled because it doesn't always use module relative paths
76
+ // if (
77
+ // res.match(/node_modules[/\\]webpack/) ||
78
+ // res.match(/node_modules[/\\]css-loader/)
79
+ // ) {
80
+ // return transpiled();
81
+ // }
82
+ // // Anything else that is standard JavaScript within `node_modules`
83
+ // // can be externalized.
84
+ // if (res.match(/node_modules[/\\].*\.js$/)) {
85
+ // return external();
86
+ // }
87
+ // transpiled();
88
+ };
89
+ return nodeExternal;
90
+ }
91
+ exports.nodeExternals = nodeExternals;
@@ -0,0 +1,3 @@
1
+ import { IWebpackHelpers } from '../../types';
2
+ export declare const webpackHelpers: () => IWebpackHelpers;
3
+ export declare function shouldUseRelativeAssetPaths(publicPath: string): boolean;
@@ -0,0 +1,48 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.webpackHelpers = () => {
4
+ const externalFns = [];
5
+ const defaultExternalsFn = ({ context, request }, callback) => {
6
+ let callbackCalled = false;
7
+ const nextHandler = (err, result) => {
8
+ if (err) {
9
+ callback(err, undefined);
10
+ callbackCalled = true;
11
+ }
12
+ else {
13
+ if (result !== 'next') {
14
+ callback(err, result);
15
+ callbackCalled = true;
16
+ }
17
+ }
18
+ };
19
+ for (let i = 0; i < externalFns.length; i++) {
20
+ externalFns[i]({ context, request }, nextHandler);
21
+ if (callbackCalled) {
22
+ break;
23
+ }
24
+ }
25
+ if (!callbackCalled) {
26
+ callback(null, undefined);
27
+ }
28
+ };
29
+ return {
30
+ addExternals: (webpackChain, externalFn) => {
31
+ let externals = webpackChain.get('externals');
32
+ if (!externals) {
33
+ externals = defaultExternalsFn;
34
+ webpackChain.externals(externals);
35
+ }
36
+ if (typeof externals === 'function' &&
37
+ externals.name === 'defaultExternalsFn') {
38
+ externalFns.push(externalFn);
39
+ return;
40
+ }
41
+ throw new Error('Externals was modified directly, addExternals will have no effect.');
42
+ }
43
+ };
44
+ };
45
+ function shouldUseRelativeAssetPaths(publicPath) {
46
+ return publicPath === './';
47
+ }
48
+ exports.shouldUseRelativeAssetPaths = shouldUseRelativeAssetPaths;
@@ -0,0 +1 @@
1
+ export declare function resolvePreferTarget(target: string, extensions: string[]): string[];
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ function resolvePreferTarget(target, extensions) {
4
+ return extensions.reduce((res, ext) => {
5
+ res.push(`.${target}${ext}`);
6
+ res.push(ext);
7
+ return res;
8
+ }, []);
9
+ }
10
+ exports.resolvePreferTarget = resolvePreferTarget;
@@ -0,0 +1,9 @@
1
+ import Config from 'webpack-chain';
2
+ interface StyleOptions {
3
+ publicPath?: string;
4
+ extractCss?: boolean;
5
+ sourceMap?: boolean;
6
+ ssr?: boolean;
7
+ }
8
+ export declare function withStyle(chain: Config, { extractCss, sourceMap, ssr, publicPath }: StyleOptions): Config;
9
+ export {};