@tmbr/bundler 0.1.4 → 1.2.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.
Files changed (3) hide show
  1. package/cli.js +163 -115
  2. package/error.js +107 -0
  3. package/package.json +8 -12
package/cli.js CHANGED
@@ -1,135 +1,183 @@
1
1
  #!/usr/bin/env node
2
- const webpack = require('webpack');
2
+ const esbuild = require('esbuild');
3
3
  const path = require('path');
4
- const SourceMapDevToolPlugin = require('webpack').SourceMapDevToolPlugin;
5
- const MiniCssExtractPlugin = require('mini-css-extract-plugin');
6
- const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
4
+ const exec = require('child_process').execSync;
5
+ const styles = require('esbuild-sass-plugin').sassPlugin;
6
+ const chalk = require('chalk');
7
+ const qr = require('qrcode-terminal');
8
+ const bs = require('browser-sync').create();
9
+ const renderError = require('./error');
7
10
 
8
11
  const cwd = process.cwd();
9
- const command = process.argv[2] || 'build';
10
12
  const package = require(`${cwd}/package.json`);
13
+ const command = process.argv[2];
14
+ let error;
11
15
 
12
- const config = {
13
- entry: {
14
- admin: path.resolve(cwd, 'src/admin'),
15
- main: path.resolve(cwd, 'src'),
16
- },
17
- output: {
18
- path: path.resolve(cwd, 'build'),
19
- filename: '[name].js',
20
- },
21
- resolve: {
22
- alias: {'@': path.resolve(cwd, 'src')}
23
- },
24
- devtool: false,
25
- module: {
26
- rules: [{
27
- test: /\.js$/,
28
- exclude: /node_modules/,
29
- use: {
30
- loader: 'babel-loader',
31
- options: {presets: [['@babel/preset-env', {targets: '> 0.5%, not IE 11, not dead'}]]}
16
+ if (!['build', 'watch'].includes(command)) {
17
+ console.log(`Invalid command: ${chalk.red(command)}\n`);
18
+ process.exit();
19
+ }
20
+
21
+ exec(`rm -rf ${cwd}/build/*`);
22
+
23
+ /* const logger = (options = {}) => ({
24
+ name: 'logger',
25
+ setup(build) {
26
+
27
+ let info;
28
+ // const cache = new Map;
29
+
30
+ function reset() {
31
+ console.clear();
32
+ info.external && console.log(info.qrcode);
33
+ console.log(`Proxying: ${chalk.green(info.proxying)}`);
34
+ console.log(`External: ${chalk.cyan(info.external || 'offline')}`);
35
+ }
36
+
37
+ build.onEnd(() => {
38
+
39
+ if (typeof info === 'undefined') {
40
+
41
+ const host = bs.getOption('proxy').get('target');
42
+ const port = bs.getOption('port');
43
+
44
+ info = {};
45
+ info.proxying = `${host}:${port}`;
46
+ info.external = bs.getOption('urls').get('external');
47
+
48
+ info.external && qr.generate(info.external, {small: true}, qrcode => {
49
+ info.qrcode = qrcode;
50
+ reset();
51
+ });
52
+
53
+ return;
54
+ }
55
+
56
+ error = result.errors[0];
57
+
58
+ if (error) {
59
+ bs.reload();
60
+ } else {
61
+ reset();
32
62
  }
33
- }, {
34
- test: /\.(css|scss)$/,
35
- use: [
36
- {loader: MiniCssExtractPlugin.loader, options: {publicPath: ''}},
37
- {loader: 'css-loader'},
38
- {loader: 'sass-loader'},
39
- ]
40
- }, {
41
- test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|json|mp3|mp4|ico)$/,
42
- type: 'asset/resource',
43
- generator: {emit: false, filename: '../[path][name][ext]?[hash]'}
44
- }]
63
+ });
45
64
  }
46
- };
65
+ }); */
47
66
 
48
- const watchConfig = Object.assign({}, config, {
49
- name: 'watch',
50
- mode: 'development',
51
- stats: {
52
- all: false,
53
- colors: true,
54
- builtAt: true,
55
- timings: true,
56
- warnings: true,
57
- errors: true,
67
+ const assets = (options = {}) => ({
68
+ name: 'assets',
69
+ setup(build) {
70
+ build.onResolve({filter: /..\/(fonts|images)\//}, args => ({
71
+ path: args.path,
72
+ external: true
73
+ }))
58
74
  },
59
- plugins: [
60
- new SourceMapDevToolPlugin(),
61
- new MiniCssExtractPlugin({
62
- filename: '[name].css'
63
- }),
64
- new BrowserSyncPlugin({
65
- proxy: `${package.name}.test`,
66
- host: 'localhost',
67
- port: 5000,
68
- open: false,
69
- notify: false,
70
- files: ['build/main.js', 'images/*', '**/*.php']
71
- })
72
- ]
73
75
  });
74
76
 
75
- const buildConfig = Object.assign({}, config, {
76
- name: 'build',
77
- mode: 'production',
78
- output: {
79
- path: path.resolve(cwd, 'build'),
80
- filename: '[name].min.js',
77
+ const errors = (options = {}) => ({
78
+ name: 'errors',
79
+ setup(build) {
80
+
81
+ build.onEnd(result => {
82
+ error = result.errors[0];
83
+ error && bs.reload();
84
+ });
81
85
  },
82
- stats: 'none',
83
- plugins: [
84
- new MiniCssExtractPlugin({
85
- filename: '[name].min.css'
86
- })
87
- ]
88
86
  });
89
87
 
90
- function callback(err, stats) {
91
- if (err) {
92
- console.error(err.stack || err);
93
- if (err.details) {
94
- console.error(err.details);
95
- }
96
- return;
97
- }
98
- const info = stats.toJson();
99
- if (stats.hasErrors()) {
100
- console.error(info.errors);
101
- }
102
- if (stats.hasWarnings()) {
103
- console.warn(info.warnings);
88
+ function entryPoints(suffix = '') {
89
+
90
+ if (suffix.length && !suffix.startsWith('.')) {
91
+ suffix = `.${suffix}`;
104
92
  }
105
- // Log result...
93
+
94
+ const entries = Object.entries({
95
+ admin: path.resolve(cwd, './src/admin'),
96
+ main: path.resolve(cwd, './src'),
97
+ });
98
+
99
+ return entries.reduce((result, [name, path]) => {
100
+ result[`${name}${suffix}`] = path;
101
+ return result;
102
+ }, {});
106
103
  }
107
104
 
108
- const compiler = webpack([
109
- watchConfig,
110
- buildConfig
111
- ]);
112
-
113
- switch (command) {
114
-
115
- case 'watch':
116
- compiler.watch({
117
- // https://webpack.js.org/configuration/watch/#watchoptions
118
- aggregateTimeout: 300,
119
- poll: undefined
120
- }, callback);
121
- break;
122
-
123
- case 'build':
124
- compiler.run((err, stats) => {
125
- // https://webpack.js.org/api/node/#stats-object
126
- // https://webpack.js.org/configuration/stats/
127
- console.log(stats.toJson());
128
- // callback(err, stats);
129
- compiler.close();
130
- });
131
- break;
105
+ const defaults = {
106
+ watch: command === 'watch',
107
+ outdir: path.resolve(cwd, 'build'),
108
+ bundle: true,
109
+ minify: true,
110
+ sourcemap: false,
111
+ logLevel: 'warning',
112
+ legalComments: 'none',
113
+ treeShaking: true,
114
+ target: 'es2019',
115
+ plugins: [
116
+ styles({sourceMap: true}),
117
+ assets(),
118
+ ],
119
+ };
120
+
121
+ const watchConfig = Object.assign({}, defaults, {
122
+ entryPoints: entryPoints('dev'),
123
+ minify: false,
124
+ sourcemap: 'inline',
125
+ logLevel: 'silent',
126
+ plugins: [
127
+ ...defaults.plugins,
128
+ errors()
129
+ ],
130
+ });
132
131
 
133
- default:
134
- console.log(`Command "${command}" not found`);
132
+ const buildConfig = Object.assign({}, defaults, {
133
+ entryPoints: entryPoints('min'),
134
+ });
135
+
136
+ esbuild.build(watchConfig);
137
+ esbuild.build(buildConfig);
138
+
139
+ if (command === 'watch') {
140
+
141
+ const watchedBuilds = Object.keys(watchConfig.entryPoints).map(name => (
142
+ `${watchConfig.outdir}/${name}.*`
143
+ ));
144
+
145
+ const files = [
146
+ ...watchedBuilds,
147
+ 'images/*',
148
+ '**/*.php'
149
+ ];
150
+
151
+ const middleware = (proxyRes, req, res) => {
152
+ error && res.end(renderError(error));
153
+ };
154
+
155
+ const options = {
156
+ proxy: {
157
+ target: `${package.name}.test`,
158
+ proxyRes: [middleware]
159
+ },
160
+ host: 'localhost',
161
+ open: false,
162
+ notify: false,
163
+ logLevel: 'silent',
164
+ ui: false,
165
+ files
166
+ };
167
+
168
+ bs.init(options, () => {
169
+
170
+ const host = bs.getOption('proxy').get('target');
171
+ const port = bs.getOption('port');
172
+ const proxying = `${host}:${port}`;
173
+ const external = bs.getOption('urls').get('external');
174
+ external && qr.generate(external, {small: true}, console.log);
175
+
176
+ console.log(`Proxying: ${chalk.green(proxying)}`);
177
+ console.log(`External: ${chalk.cyan(external || 'offline')}`);
178
+ });
135
179
  }
180
+
181
+ process.on('SIGINT', () => {
182
+ process.exit();
183
+ })
package/error.js ADDED
@@ -0,0 +1,107 @@
1
+ const fs = require('fs');
2
+ const encode = require('html-entities').encode;
3
+
4
+ module.exports = error => {
5
+
6
+ const { file, line, column } = error.location;
7
+
8
+ const lines = fs.readFileSync(file, 'UTF-8').split(/\r?\n/);
9
+ const index = line - 1;
10
+ const inset = String((lines[index + 2] && line + 2) || (lines[index + 1] && line + 1) || line).split('').length;
11
+
12
+ const print = offset => (
13
+ `<span class="c-gray">${String(line + offset).padStart(2 + inset, ' ')} | </span>` + encode(lines[index + offset])
14
+ );
15
+
16
+ const space = length => {
17
+ return ' '.repeat(length);
18
+ };
19
+
20
+ const output = [
21
+ (index - 2) >= 0 && print(-2),
22
+ (index - 1) >= 0 && print(-1),
23
+ `<span class="c-red fw-700">&gt;</span><span class="c-gray"> ${line} | </span>${encode(lines[index])}`,
24
+ ` <span class="c-gray">${space(2 + inset)}| </span>${space(column ? column - 1 : 0)}<span class="c-red fw-700">^</span>`,
25
+ (index + 1) <= lines.length - 1 && print(1),
26
+ (index + 2) <= lines.length - 1 && print(2),
27
+ ].filter(Boolean).join('\n');
28
+
29
+ return /* html */`
30
+ <!DOCTYPE html>
31
+ <html>
32
+ <head>
33
+
34
+ <meta charset="UTF-8">
35
+ <meta content="width=device-width, initial-scale=1.0" name="viewport">
36
+
37
+ <title>Build Error: ${file}</title>
38
+
39
+ <style>
40
+
41
+ * {
42
+ margin: 0;
43
+ padding: 0;
44
+ box-sizing: border-box;
45
+ }
46
+
47
+ .c-red { color: #ff5555; }
48
+ .c-cyan { color: #88ddff; }
49
+ .c-gray { color: #666666; }
50
+ .fw-700 { font-weight: 700; }
51
+
52
+ ::selection {
53
+ background-color: rgba(95, 126, 151, 0.48);
54
+ }
55
+
56
+ html {
57
+ font: 1rem / 1.5 sans-serif;
58
+ color: #FFF;
59
+ background-color: #151515;
60
+ }
61
+ main {
62
+ max-width: 1280px;
63
+ margin: 3em auto;
64
+ padding: 1rem;
65
+ }
66
+ h1 {
67
+ font-size: 1.5rem;
68
+ line-height: 1.5;
69
+ margin-bottom: 0.25em;
70
+ }
71
+
72
+ .terminal {
73
+ color: #CCC;
74
+ border-radius: 0.25rem;
75
+ }
76
+ .terminal pre {
77
+ font-family: Menlo, Monaco, monospace;
78
+ overflow: scroll;
79
+ }
80
+ .terminal > * {
81
+ padding: 1rem 0;
82
+ }
83
+
84
+ </style>
85
+
86
+ </head>
87
+ <body>
88
+
89
+ <main>
90
+
91
+ <h1>Build Error</h1>
92
+
93
+ <div class="terminal">
94
+
95
+ <pre>
96
+ <span class="c-cyan">${file}</span><span class="c-gray">:</span>${line}<span class="c-gray">:</span>${column}
97
+ <span class="c-red fw-700">${error.text}</span>
98
+
99
+ ${output}
100
+ </pre>
101
+
102
+ </div>
103
+
104
+ </main>
105
+
106
+ </body>
107
+ </html>`};
package/package.json CHANGED
@@ -1,23 +1,19 @@
1
1
  {
2
2
  "name": "@tmbr/bundler",
3
3
  "author": "TMBR (https://wearetmbr.com/)",
4
- "version": "0.1.4",
4
+ "version": "1.2.0",
5
5
  "license": "MIT",
6
6
  "repository": "https://github.com/TMBR/tmbr-bundler",
7
- "description": "WordPress development toolkit built on webpack and browser-sync",
7
+ "description": "WordPress development toolkit built on esbuild and browser-sync",
8
8
  "bin": {
9
9
  "tmbr-bundler": "cli.js"
10
10
  },
11
11
  "dependencies": {
12
- "@babel/core": "^7.12.17",
13
- "@babel/preset-env": "^7.12.17",
14
- "babel-loader": "^8.2.2",
15
- "browser-sync": "^2.26.14",
16
- "browser-sync-webpack-plugin": "^2.3.0",
17
- "css-loader": "^5.0.2",
18
- "mini-css-extract-plugin": "^1.3.8",
19
- "sass": "^1.32.8",
20
- "sass-loader": "^11.0.1",
21
- "webpack": "^5.23.0"
12
+ "browser-sync": "^2.27.5",
13
+ "chalk": "^4.1.2",
14
+ "esbuild": "^0.14.14",
15
+ "esbuild-sass-plugin": "^2.2.1",
16
+ "html-entities": "^2.3.2",
17
+ "qrcode-terminal": "^0.12.0"
22
18
  }
23
19
  }