@cmmn/tools 1.0.3 → 1.2.2

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/bin.js CHANGED
@@ -1,12 +1,13 @@
1
1
  #!/usr/bin/env node
2
-
3
- import {bundle} from "./bundle/bundle.js";
4
- import {compile} from "./compile/compile.js";
5
-
6
- const [action, ...args] = process.argv.slice(2);
7
-
8
- const actions = {
9
- bundle, compile
10
- }
11
-
12
- actions[action](...args);
2
+
3
+ import {bundle} from "./bundle/bundle.js";
4
+ import {compile} from "./compile/compile.js";
5
+ import {gen} from "./gen/gen.js";
6
+
7
+ const [action, ...args] = process.argv.slice(2);
8
+
9
+ const actions = {
10
+ bundle, compile, gen
11
+ }
12
+
13
+ actions[action](...args);
package/bundle/bundle.js CHANGED
@@ -1,53 +1,116 @@
1
- import {getConfig} from "./rollup.config.js";
2
- import {rollup, watch} from "rollup";
3
-
4
- export async function bundle(target, ...options) {
5
- const config = getConfig({
6
- input: target,
7
- minify: options.includes('--prop'),
8
- devServer: options.includes('--run')
9
- });
10
- config.onwarn = function (message){
11
-
12
- }
13
- if (options.includes('--watch')) {
14
- const watcher = watch(config);
15
- watcher.on('event', (event) => {
16
- switch (event.code){
17
- case 'START':
18
- console.clear();
19
- console.log('START BUNDLING');
20
- break;
21
- case 'END':
22
- console.log('FINISH');
23
- break;
24
- case 'BUNDLE_START':
25
- console.log(`1. ${event.input} -> ${event.output}`);
26
- break;
27
- case 'BUNDLE_END':
28
- console.log(`1. ${event.input} -> ${event.output}, (${event.duration/1000}s)`);
29
- break;
30
-
31
- case 'ERROR':
32
- switch (event.error.code){
33
- case 'PARSE_ERROR':
34
- console.warn('Error parsing files:');
35
- console.log(`\t${event.error.parserError.message}`);
36
- console.log(`\tat: ${event.error.id}`);
37
- console.log(`\tline: ${event.error.frame}`);
38
- break;
39
- case 'UNRESOLVED_IMPORT':
40
- console.error(event.error.message);
41
- break;
42
- default:
43
- console.warn('Unknown error:', event.error.code);
44
- console.error(event.error);
45
- break;
46
- }
47
- break;
48
- }
49
- });
50
- } else {
51
- const build = await rollup(config);
52
- }
53
- }
1
+ import {ConfigCreator} from "./rollup.config.js";
2
+ import {rollup, watch} from "rollup";
3
+ import fs from "fs";
4
+ import path from "path";
5
+ import fg from "fast-glob";
6
+
7
+ function getProjectConfig(rootDir, cmmn, options) {
8
+ const configCreator = new ConfigCreator({
9
+ ...options,
10
+ ...cmmn,
11
+ });
12
+ configCreator.setRootDir(rootDir);
13
+ return configCreator.getConfig();
14
+ }
15
+
16
+ function getPackageConfigs(rootDir, options, name = null) {
17
+ const results = [];
18
+ const pkg = JSON.parse(fs.readFileSync(path.join(rootDir, 'package.json')));
19
+ if (name) {
20
+ results.push(...getProjectConfig(rootDir, pkg.cmmn[name], {
21
+ ...options,
22
+ name
23
+ }));
24
+ } else {
25
+ for (let name in pkg.cmmn) {
26
+ results.push(...getProjectConfig(rootDir, pkg.cmmn[name], {
27
+ ...options,
28
+ name
29
+ }));
30
+ }
31
+ }
32
+ return results;
33
+ }
34
+
35
+ function getLernaSubPackages(lernaFile, options) {
36
+ const config = JSON.parse(fs.readFileSync(lernaFile, 'utf8'));
37
+ const packages = config.packages;
38
+ const dirs = packages.flatMap(pkg => fg.sync([pkg], {
39
+ absolute: true,
40
+ globstar: true,
41
+ onlyDirectories: true,
42
+ cwd: path.dirname(lernaFile)
43
+ }));
44
+ return dirs.flatMap(dir => getPackageConfigs(dir, options));
45
+ }
46
+
47
+ function getConfigs(options) {
48
+ if (!options.input || options.project) {
49
+ const rootDir = process.cwd();
50
+ const lernaPath = path.join(rootDir, 'lerna.json');
51
+ if (fs.existsSync(lernaPath)) {
52
+ return getLernaSubPackages(lernaPath, options);
53
+ }
54
+ return getPackageConfigs(process.cwd(), options);
55
+ }
56
+ if (options.input && !fs.existsSync(options.input)) {
57
+ return getPackageConfigs(process.cwd(), options, options.input);
58
+ }
59
+ const creator = new ConfigCreator(options);
60
+ return creator.getConfig();
61
+ }
62
+
63
+ export async function bundle(...options) {
64
+ const configs = getConfigs({
65
+ input: options.filter(x => !x.startsWith('-'))[0],
66
+ project: options.includes('-b'),
67
+ minify: options.includes('--prod'),
68
+ devServer: options.includes('--run'),
69
+ stats: options.includes('--stats'),
70
+ });
71
+ if (!options.includes('--watch')) {
72
+ for (let config of configs) {
73
+ console.log(`1. ${config.input} -> ${config.output.file}`);
74
+ const build = await rollup(config);
75
+ await build.write(config.output);
76
+ console.log('SUCCESS');
77
+ }
78
+ return;
79
+ }
80
+ const watcher = watch(configs);
81
+ watcher.on('event', (event) => {
82
+ switch (event.code) {
83
+ case 'START':
84
+ console.clear();
85
+ console.log('START BUNDLING');
86
+ break;
87
+ case 'END':
88
+ console.log('FINISH');
89
+ break;
90
+ case 'BUNDLE_START':
91
+ console.log(`1. ${event.input} -> ${event.output}`);
92
+ break;
93
+ case 'BUNDLE_END':
94
+ console.log(`1. ${event.input} -> ${event.output}, (${event.duration / 1000}s)`);
95
+ break;
96
+
97
+ case 'ERROR':
98
+ switch (event.error.code) {
99
+ case 'PARSE_ERROR':
100
+ console.warn('Error parsing files:');
101
+ console.log(`\t${event.error.parserError.message}`);
102
+ console.log(`\tat: ${event.error.id}`);
103
+ console.log(`\tline: ${event.error.frame}`);
104
+ break;
105
+ case 'UNRESOLVED_IMPORT':
106
+ console.error(event.error.message);
107
+ break;
108
+ default:
109
+ console.warn('Unknown error:', event.error.code);
110
+ console.error(event.error);
111
+ break;
112
+ }
113
+ break;
114
+ }
115
+ });
116
+ }
@@ -1,78 +1,183 @@
1
- import commonjs from '@rollup/plugin-commonjs';
2
- import nodeResolve from '@rollup/plugin-node-resolve';
3
- import {terser} from "rollup-plugin-terser"
4
- import { visualizer } from 'rollup-plugin-visualizer';
5
- import less from 'rollup-plugin-less';
6
- import { string } from "rollup-plugin-string";
7
- import serve from 'rollup-plugin-serve'
8
-
9
- export const getConfig = ({minify, input, devServer}) => {
10
- if (minify){
11
- return {
12
- input,
13
- output: {
14
- file: 'dist/index.min.js',
15
- format: 'cjs'
16
- },
17
- plugins: [
18
- commonjs(),
19
- nodeResolve({
20
- browser: true,
21
- }),
22
- terser({
23
- }),
24
- visualizer({
25
- open: true,
26
- template: 'sunburst',
27
- brotliSize: true,
28
- filename: 'dist/stats.html'
29
- }),
30
-
31
- ]
32
- }
33
- }
34
- return ({
35
- input,
36
- output: [
37
- {
38
- file: 'dist/index-cjs.js',
39
- sourcemap: true,
40
- format: 'cjs',
41
- exports: 'auto',
42
- },
43
- {
44
- file: 'dist/index-umd.js',
45
- sourcemap: true,
46
- format: 'umd',
47
- name: 'global'
48
- },
49
- {
50
- file: 'dist/index-es.js',
51
- sourcemap: true,
52
- exports: 'auto',
53
- format: 'es'
54
- }
55
- ],
56
- // prettier-ignore
57
- plugins: [
58
- nodeResolve({
59
- browser: true,
60
- }),
61
- commonjs({
62
-
63
- }),
64
- less({
65
- insert: true
66
- }),
67
- string({
68
- include: /\.(html|svg)$/,
69
- }),
70
- ...[devServer ? serve({
71
- open: false,
72
- contentBase: ['dist', 'assets'],
73
- port: 3001,
74
- historyApiFallback: true
75
- }) : '']
76
- ]
77
- });
78
- };
1
+ import commonjs from '@rollup/plugin-commonjs';
2
+ import nodeResolve from '@rollup/plugin-node-resolve';
3
+ import {terser} from "rollup-plugin-terser"
4
+ import {visualizer} from 'rollup-plugin-visualizer';
5
+ import styles from "rollup-plugin-styles";
6
+ import builtins from "rollup-plugin-node-builtins";
7
+ import {string} from "rollup-plugin-string";
8
+ import serve from 'rollup-plugin-serve'
9
+ import livereload from 'rollup-plugin-livereload'
10
+ import fs from "fs";
11
+ import path from "path";
12
+ import html from '@open-wc/rollup-plugin-html';
13
+ /**
14
+ * @typedef {import(rollup).RollupOptions} RollupOptions
15
+ * @typedef {import(rollup).OutputOptions} OutputOptions
16
+ */
17
+
18
+ export class ConfigCreator {
19
+
20
+ /**
21
+ * @type {{
22
+ * minify: boolean,
23
+ * input: string,
24
+ * devServer: boolean,
25
+ * module: string,
26
+ * external: string[],
27
+ * stats: boolean,
28
+ * name: string,
29
+ * outDir: string,
30
+ * html: string,
31
+ * dedupe: string[]
32
+ * }}
33
+ */
34
+ options;
35
+
36
+ /**
37
+ * @type {string}
38
+ */
39
+ root = process.cwd();
40
+
41
+
42
+ constructor(options) {
43
+ this.options = {
44
+ ...options
45
+ };
46
+ }
47
+
48
+ setRootDir(rootDir){
49
+ this.root = rootDir;
50
+ }
51
+
52
+ get outDir(){
53
+ return path.join(this.root, this.options.outDir);
54
+ }
55
+
56
+ /**
57
+ *
58
+ * @returns {OutputOptions}
59
+ */
60
+ get output() {
61
+ // const output = `${this.options.name ?? 'index'}-${this.options.module}${this.options.minify ? '.min' : ''}.js`;
62
+ return {
63
+ entryFileNames: `[name]-${this.options.module}${this.options.minify ? '.min' : ''}.js`,
64
+ // file: output,
65
+ dir: this.outDir,
66
+ sourcemap: !this.options.minify,
67
+ format: this.options.module,
68
+ name: 'global',
69
+ };
70
+ }
71
+
72
+ get html(){
73
+ return html({
74
+ publicPath: '/',
75
+ dir: this.outDir,
76
+ template: () => fs.readFileSync(path.join(this.root, this.options.html), 'utf8')
77
+ });
78
+ }
79
+ get devServer(){
80
+ return serve({
81
+ open: false,
82
+ contentBase: [this.outDir, path.join(this.root, 'assets')],
83
+ port: 3001,
84
+ historyApiFallback: true
85
+ });
86
+ }
87
+
88
+ get livereload(){
89
+ return livereload({
90
+ watch: [this.outDir, path.join(this.root, 'assets')],
91
+ verbose: false, // Disable console output
92
+ // other livereload options
93
+ port: 12345,
94
+ delay: 300,
95
+ })
96
+ }
97
+
98
+ get visualizer(){
99
+ return visualizer({
100
+ open: true,
101
+ sourcemap: true,
102
+ template: 'treemap',
103
+ brotliSize: true,
104
+ filename: path.join(this.outDir, '/stats.html')
105
+ })
106
+ }
107
+
108
+ get plugins() {
109
+ const result = [
110
+ builtins(),
111
+ nodeResolve({
112
+ browser: true,
113
+ dedupe: this.options.dedupe || []
114
+ }),
115
+ commonjs({
116
+ requireReturnsDefault: "namespace",
117
+ }),
118
+ styles({
119
+ mode: "emit",
120
+ }),
121
+ string({
122
+ include: /\.(html|svg|less|css)$/,
123
+ }),
124
+ ];
125
+ if (this.options.html || this.options.input.endsWith('.html')){
126
+ result.push(this.html);
127
+ }
128
+ if (this.options.minify) {
129
+ result.push(terser({
130
+ module: true,
131
+ ecma: 2020,
132
+ compress: true,
133
+ keep_classnames: false,
134
+ keep_fnames: false,
135
+ mangle: true,
136
+ output: {
137
+ comments: false
138
+ }
139
+ }));
140
+ }
141
+ if (this.options.devServer) {
142
+ result.push(this.devServer, this.livereload);
143
+ }
144
+ if (this.options.stats){
145
+ result.push(this.visualizer);
146
+ }
147
+ return result;
148
+ }
149
+
150
+ /**
151
+ * @returns {RollupOptions[]}
152
+ */
153
+ getConfig() {
154
+ Object.assign(this.options,{
155
+ module: this.options.module || 'es',
156
+ external: this.options.external || [],
157
+ name: this.options.name || 'index',
158
+ outDir: this.options.outDir || 'dist'
159
+ });
160
+ if (this.options.external && typeof this.options.external === "string")
161
+ this.options.external = [this.options.external]
162
+ console.log(this.options);
163
+ return [{
164
+ input: {
165
+ [this.options.name]: path.join(this.root,this.options.input)
166
+ },
167
+ output: this.output,
168
+ external: (this.options.external || []).map(s => new RegExp(s)),
169
+ onwarn(warning) {
170
+ // Silence circular dependency warning for moment package
171
+ if (
172
+ warning.code === 'CIRCULAR_DEPENDENCY'
173
+ ) {
174
+ return
175
+ }
176
+
177
+ console.warn(`(!) ${warning.message}`)
178
+ },
179
+ plugins: this.plugins,
180
+ treeshake: this.options.minify ? "smallest" : "recommended"
181
+ }]
182
+ }
183
+ }
@@ -1,47 +1,38 @@
1
- import ts from "typescript";
2
-
3
- export function compile(target, options) {
4
- const config = {
5
- declaration: true,
6
- declarationDir: "dist/typings",
7
- experimentalDecorators: true,
8
- emitDecoratorMetadata: true,
9
- module: ts.ModuleKind.ES2020,
10
- moduleResolution: ts.ModuleResolutionKind.NodeJs,
11
- lib: ["lib.es2020.d.ts", "lib.dom.d.ts"],
12
- noEmitHelpers: false,
13
- noImplicitAny: true,
14
- downlevelIteration: true,
15
- noImplicitOverride: true,
16
- noImplicitReturns: true,
17
- outDir: "dist/esm",
18
- target: ts.ScriptTarget.ES2018
19
- }
20
- // Note that there is another overload for `createWatchCompilerHost` that takes
21
- // a set of root files.
22
- const host = ts.createWatchCompilerHost(
23
- [ target ],
24
- config,
25
- ts.sys
26
- );
27
-
28
- // You can technically override any given hook on the host, though you probably
29
- // don't need to.
30
- // Note that we're assuming `origCreateProgram` and `origPostProgramCreate`
31
- // doesn't use `this` at all.
32
- const origCreateProgram = host.createProgram;
33
- host.createProgram = (rootNames, options, host, oldProgram) => {
34
- console.log("** We're about to create the program! **");
35
- return origCreateProgram(rootNames, options, host, oldProgram);
36
- };
37
- const origPostProgramCreate = host.afterProgramCreate;
38
-
39
- host.afterProgramCreate = program => {
40
- console.log("** We finished making the program! **");
41
- origPostProgramCreate(program);
42
- };
43
-
44
- // `createWatchProgram` creates an initial program, watches files, and updates
45
- // the program over time.
46
- ts.createWatchProgram(host);
47
- }
1
+ import ts from "ttypescript";
2
+ import {resolve} from 'path';
3
+
4
+ const rootDir = process.cwd();
5
+
6
+ export function compile(...flags) {
7
+
8
+ const host = ts.createSolutionBuilderWithWatchHost(ts.sys, createProgram);
9
+ host.useCaseSensitiveFileNames();
10
+
11
+ const builderFactory = flags.includes('--watch') ?
12
+ ts.createSolutionBuilderWithWatch :
13
+ ts.createSolutionBuilder;
14
+
15
+ const builder = builderFactory(host, [rootDir], {
16
+ incremental: true,
17
+ dry: false
18
+ }, {
19
+ excludeDirectories: ["node_modules", "dist"]
20
+ });
21
+ if (flags.includes('-b')) {
22
+ builder.cleanReferences(rootDir);
23
+ builder.buildReferences(rootDir);
24
+ } else {
25
+ builder.clean(rootDir);
26
+ builder.build(rootDir);
27
+ }
28
+ }
29
+
30
+ function createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences) {
31
+ options.outDir = resolve(options.configFilePath, '../dist/esm');
32
+ options.declarationDir = resolve(options.configFilePath, '../dist/typings');
33
+ options.baseUrl = resolve(options.configFilePath, '../');
34
+ console.log('build', options.configFilePath);
35
+ return ts.createEmitAndSemanticDiagnosticsBuilderProgram(
36
+ rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences
37
+ )
38
+ }
@@ -0,0 +1,47 @@
1
+ {
2
+ "compilerOptions": {
3
+ "module": "ES6",
4
+ "moduleResolution": "Node",
5
+ "target": "ES2019",
6
+ "composite": true,
7
+ "sourceMap": true,
8
+ "baseUrl": "./",
9
+ "experimentalDecorators": true,
10
+ "checkJs": false,
11
+ "outDir": "./dist/esm",
12
+ "skipLibCheck": true,
13
+ "skipDefaultLibCheck": true,
14
+ "allowJs": true,
15
+ "allowSyntheticDefaultImports": true,
16
+ "emitDecoratorMetadata": true ,
17
+ "noEmitHelpers": true,
18
+ "declarationDir": "./dist/typings",
19
+ "declaration": true,
20
+ "types": [
21
+ ],
22
+ "lib": [
23
+ "ES2020.BigInt",
24
+ "ESNext",
25
+ "DOM"
26
+ ],
27
+ "plugins": [
28
+ {
29
+ "transform": "@cmmn/tools/plugins/absolute-plugin.cjs",
30
+ "after": true
31
+ },
32
+ // Transform paths in output .js files
33
+ {
34
+ "transform": "typescript-transform-paths"
35
+ },
36
+ // Transform paths in output .d.ts files (Include this line if you output declarations files)
37
+ {
38
+ "transform": "typescript-transform-paths",
39
+ "afterDeclarations": true
40
+ }
41
+ ]
42
+ },
43
+ "exclude": [
44
+ "node_modules",
45
+ "dist"
46
+ ]
47
+ }
@@ -0,0 +1,16 @@
1
+ import {component, HtmlComponent, property} from "@cmmn/ui";
2
+ import {template, IState, IEvents} from "./$name$.template";
3
+ import style from "./$name$.style.less";
4
+ import {Injectable} from "@cmmn/core";
5
+
6
+ @Injectable(true)
7
+ @component({name: '$name$', template, style})
8
+ export class $Name$Component extends HtmlComponent<IState, IEvents> {
9
+
10
+ @property()
11
+ private property!: any;
12
+
13
+ get State() {
14
+ return this.property;
15
+ }
16
+ }
package/gen/gen.js ADDED
@@ -0,0 +1,27 @@
1
+ import fs from "fs";
2
+ import path from "path";
3
+ import {fileURLToPath} from 'url';
4
+ import {execSync} from "child_process";
5
+
6
+ const currentDir = '__dirname' in global ? __dirname : path.dirname(fileURLToPath(import.meta.url));
7
+
8
+ const templateTpl = fs.readFileSync(path.join(currentDir, './template.ts.tpl'), 'utf8');
9
+ const componentTpl = fs.readFileSync(path.join(currentDir, './component.ts.tpl'), 'utf8');
10
+ const styleTpl = fs.readFileSync(path.join(currentDir, './style.less.tpl'), 'utf8');
11
+
12
+
13
+ export function gen(name, directory, nested = false) {
14
+ const Name = name.replace(/^./, c => c.toUpperCase());
15
+ name = Name.replace(/[A-Z]/g, (c, i) => (i ? '-' : '') + c.toLowerCase());
16
+ process.chdir(directory);
17
+ if (nested) {
18
+ fs.mkdirSync(name);
19
+ process.chdir(name);
20
+ }
21
+ fs.writeFileSync(name + '.component.ts', componentTpl.replace(/\$Name\$/g, Name).replace(/\$name\$/g, name), 'utf8');
22
+ fs.writeFileSync(name + '.template.ts', templateTpl.replace(/\$Name\$/g, Name).replace(/\$name\$/g, name), 'utf8');
23
+ fs.writeFileSync(name + '.style.less', styleTpl.replace(/\$Name\$/g, Name).replace(/\$name\$/g, name), 'utf8');
24
+ execSync(`git add ${name}.component.ts`);
25
+ execSync(`git add ${name}.template.ts`);
26
+ execSync(`git add ${name}.style.less`);
27
+ }
@@ -0,0 +1,3 @@
1
+ $name$ {
2
+ display: block;
3
+ }
@@ -0,0 +1,8 @@
1
+ import {ITemplate} from "@cmmn/ui";
2
+
3
+ export const template: ITemplate<IState, IEvents> = (html, state, events) => html`
4
+ `;
5
+
6
+ export type IState = {}
7
+
8
+ export type IEvents = {}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cmmn/tools",
3
- "version": "1.0.3",
3
+ "version": "1.2.2",
4
4
  "description": "di, base extensions, useful functions",
5
5
  "main": "dist/rollup.config.js",
6
6
  "type": "module",
@@ -13,26 +13,33 @@
13
13
  },
14
14
  "files": [
15
15
  "bin.js",
16
- "absolute-plugin.cjs",
16
+ "gen/*",
17
+ "compile/*",
17
18
  "bundle/*",
18
- "compile/*"
19
+ "plugins/*"
19
20
  ],
20
- "peerDependencies": {
21
- "typescript": "4.4.3"
22
- },
23
21
  "dependencies": {
22
+ "@open-wc/rollup-plugin-html": "^1.2.5",
24
23
  "@rollup/plugin-commonjs": "^21",
25
24
  "@rollup/plugin-node-resolve": "^13",
26
25
  "@rollup/plugin-typescript": "^8",
26
+ "@web/rollup-plugin-html": "^1.10.1",
27
+ "fast-glob": "^3.2.11",
28
+ "less": "^4",
27
29
  "rollup": "^2",
28
- "rollup-plugin-less": "^1.1.3",
30
+ "rollup-plugin-livereload": "^2.0.5",
31
+ "rollup-plugin-node-builtins": "^2.1.2",
32
+ "rollup-plugin-node-globals": "^1.4.0",
29
33
  "rollup-plugin-serve": "^1.1.0",
30
34
  "rollup-plugin-string": "^3.0.0",
35
+ "rollup-plugin-styles": "^4",
31
36
  "rollup-plugin-terser": "^7",
32
37
  "rollup-plugin-visualizer": "^5.5.4",
33
- "typescript": "4.4.3"
38
+ "ttypescript": "1.5.13",
39
+ "typescript": "4.4.3",
40
+ "typescript-transform-paths": "^3.3.1"
34
41
  },
35
42
  "author": "",
36
43
  "license": "ISC",
37
- "gitHead": "a96e009d45a7e453cb419989710f16f30e5d8290"
44
+ "gitHead": "66f94deba77ee833d4fca4350e7c98869afb8c6f"
38
45
  }
@@ -0,0 +1,50 @@
1
+ const ts = require("typescript");
2
+ const path = require("path");
3
+
4
+ function visitImportNode(importNode, sourceFile) {
5
+ const file = importNode.moduleSpecifier?.text;
6
+ if (!/\.(less|css|scss|sass|svg|png|html)/.test(file))
7
+ return;
8
+ const sourceFileDir = path.dirname(sourceFile.path);
9
+ const real = path.join(sourceFileDir, file);
10
+ return ts.updateImportDeclaration(importNode, importNode.decorators, importNode.modifiers, importNode.importClause, ts.createStringLiteral(real));
11
+ }
12
+
13
+ function visitRequireNode(importNode, sourceFile) {
14
+ if (!(importNode.expression.kind == ts.SyntaxKind.Identifier &&
15
+ importNode.expression.escapedText == "require")) {
16
+ return;
17
+ }
18
+ const file = importNode.arguments[0].text;
19
+ if (/\.(less|css|scss|sass|svg|png|html)/.test(file)) {
20
+ const sourceFileDir = path.dirname(sourceFile.path);
21
+ const real = path.join(sourceFileDir, file);
22
+ return ts.updateCall(importNode, importNode.expression, undefined, [ts.createStringLiteral(real)]);
23
+ }
24
+ }
25
+
26
+ const lessToStringTransformer = function (context) {
27
+ return (sourceFile) => {
28
+ function visitor(node) {
29
+ // if (node && node.kind == ts.SyntaxKind.ImportDeclaration) {
30
+ // return visitImportNode(node as ts.ImportDeclaration);
31
+ // }
32
+ if (node && ts.isCallExpression(node)) {
33
+ const result = visitRequireNode(node, sourceFile);
34
+ if (result)
35
+ return result;
36
+ }
37
+ if (node && ts.isImportDeclaration(node)) {
38
+ const result = visitImportNode(node, sourceFile);
39
+ if (result)
40
+ return result;
41
+ }
42
+ return ts.visitEachChild(node, visitor, context);
43
+ }
44
+
45
+ return ts.visitEachChild(sourceFile, visitor, context);
46
+ };
47
+ };
48
+ exports.default = function (program, pluginOptions) {
49
+ return lessToStringTransformer;
50
+ }
package/readme.md ADDED
@@ -0,0 +1,11 @@
1
+ ## Builder and bundler for your projects
2
+
3
+ ### Use cases:
4
+ `cmmn compile [target] [-b] [--watch]`
5
+ > Runs typescript compiler
6
+
7
+ `cmmn bundle [target] [-b] [--watch] [--run] [--prod]`
8
+ > Runs rollup bundler
9
+
10
+ `cmmn gen name directory [-n]`
11
+ > Generates component with template at directory
@@ -1,36 +0,0 @@
1
- const ts = require("typescript");
2
- const path_1 = require("path");
3
-
4
- function visitRequireNode(importNode) {
5
- if (importNode.expression.kind == ts.SyntaxKind.Identifier &&
6
- importNode.expression.escapedText == "require") {
7
- const file = importNode.arguments[0].text;
8
- if (/\.(less|css|scss|sass|svg|png|html)/.test(file)) {
9
- const currentFileName = importNode.getSourceFile().fileName;
10
- const absolute = path_1.join(path_1.dirname(currentFileName), file);
11
- return ts.updateCall(importNode, importNode.expression, undefined, [ts.createStringLiteral(absolute)]);
12
- }
13
- }
14
- return null;
15
- }
16
-
17
- const lessToStringTransformer = function (context) {
18
- return (sourceFile) => {
19
- function visitor(node) {
20
- // if (node && node.kind == ts.SyntaxKind.ImportDeclaration) {
21
- // return visitImportNode(node as ts.ImportDeclaration);
22
- // }
23
- if (node && ts.isCallExpression(node)) {
24
- const result = visitRequireNode(node);
25
- if (result)
26
- return result;
27
- }
28
- return ts.visitEachChild(node, visitor, context);
29
- }
30
-
31
- return ts.visitEachChild(sourceFile, visitor, context);
32
- };
33
- };
34
- exports.default = function (program, pluginOptions) {
35
- return lessToStringTransformer;
36
- }