lvyjs 0.2.2 → 0.2.3

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/lib/postcss.js CHANGED
@@ -1,100 +1,104 @@
1
- import fs from 'fs'
2
- import postcss from 'postcss'
3
- import { createRequire } from 'module'
4
- import { join, resolve, dirname } from 'path'
1
+ import fs from 'fs';
2
+ import postcss from 'postcss';
3
+ import { createRequire } from 'module';
4
+ import { join, resolve, dirname } from 'path';
5
5
 
6
- const require = createRequire(import.meta.url)
6
+ const require = createRequire(import.meta.url);
7
7
  const loadPostcssConfig = configPath => {
8
- const plugins = []
9
- let aliasEntries = []
10
- if (typeof global.lvyConfig?.alias != 'boolean') {
11
- aliasEntries = global.lvyConfig.alias?.entries || []
12
- }
13
- if (aliasEntries.length > 0) {
14
- // 创建 postcss-import 插件并配置别名解析
8
+ const plugins = [];
9
+ let aliasEntries = [];
10
+ if (typeof global.lvyConfig?.alias != 'boolean') {
11
+ aliasEntries = global.lvyConfig.alias?.entries || [];
12
+ }
13
+ if (aliasEntries.length > 0) {
14
+ // 创建 postcss-import 插件并配置别名解析
15
+ try {
16
+ plugins.push(require('postcss-import')({
17
+ resolve: (id, basedir) => {
18
+ // 检查别名
19
+ for (const entry of aliasEntries) {
20
+ if (id.startsWith(entry.find)) {
21
+ const aliasedPath = id.replace(entry.find, entry.replacement);
22
+ return resolve(basedir, aliasedPath); // 返回绝对路径
23
+ }
24
+ }
25
+ return id; // 默认返回原始路径
26
+ }
27
+ }));
28
+ }
29
+ catch (err) {
30
+ console.error(err);
31
+ }
32
+ }
15
33
  try {
16
- plugins.push(
17
- require('postcss-import')({
18
- resolve: (id, basedir) => {
19
- // 检查别名
20
- for (const entry of aliasEntries) {
21
- if (id.startsWith(entry.find)) {
22
- const aliasedPath = id.replace(entry.find, entry.replacement)
23
- return resolve(basedir, aliasedPath) // 返回绝对路径
24
- }
34
+ if (fs.existsSync(configPath)) {
35
+ const cfg = require(configPath);
36
+ // 添加其他插件
37
+ if (!Array.isArray(cfg.plugins)) {
38
+ const keys = Object.keys(cfg.plugins);
39
+ keys.forEach(key => {
40
+ try {
41
+ const pluginConfig = cfg.plugins[key];
42
+ const plugin = require(key);
43
+ if (typeof plugin === 'function') {
44
+ plugins.push(plugin(pluginConfig));
45
+ }
46
+ else {
47
+ throw new Error(`插件 ${key} 不是有效的 PostCSS 插件函数`);
48
+ }
49
+ }
50
+ catch (err) {
51
+ console.error(`加载 PostCSS 插件 ${key} 失败:`, err);
52
+ }
53
+ });
25
54
  }
26
- return id // 默认返回原始路径
27
- }
28
- })
29
- )
30
- } catch (err) {
31
- console.error(err)
32
- }
33
- }
34
- try {
35
- if (fs.existsSync(configPath)) {
36
- const cfg = require(configPath)
37
- // 添加其他插件
38
- if (!Array.isArray(cfg.plugins)) {
39
- const keys = Object.keys(cfg.plugins)
40
- keys.forEach(key => {
41
- try {
42
- const pluginConfig = cfg.plugins[key]
43
- const plugin = require(key)
44
- if (typeof plugin === 'function') {
45
- plugins.push(plugin(pluginConfig))
46
- } else {
47
- throw new Error(`插件 ${key} 不是有效的 PostCSS 插件函数`)
55
+ else {
56
+ plugins.push(...cfg.plugins);
48
57
  }
49
- } catch (err) {
50
- console.error(`加载 PostCSS 插件 ${key} 失败:`, err)
51
- }
52
- })
53
- } else {
54
- plugins.push(...cfg.plugins)
55
- }
56
- return { plugins }
57
- } else {
58
- throw new Error(`未找到 PostCSS 配置文件: ${configPath}`)
58
+ return { plugins };
59
+ }
60
+ else {
61
+ throw new Error(`未找到 PostCSS 配置文件: ${configPath}`);
62
+ }
59
63
  }
60
- } catch (err) {
61
- console.error('加载 PostCSS 配置失败:', err)
62
- return { plugins }
63
- }
64
- }
65
- const postCSS = (inputPath, outputPath) => {
66
- const configPath = join(process.cwd(), 'postcss.config.cjs')
67
- const postcssConfig = loadPostcssConfig(configPath)
68
- const readAndProcessCSS = async () => {
69
- const css = fs.readFileSync(inputPath, 'utf-8')
70
- fs.mkdirSync(dirname(outputPath), { recursive: true })
71
- const result = await postcss(postcssConfig.plugins).process(css, {
72
- from: inputPath,
73
- to: outputPath
74
- })
75
- fs.writeFileSync(outputPath, result.css)
76
- if (result.warnings().length) {
77
- result.warnings().forEach(warn => {
78
- console.warn(warn.toString())
79
- })
64
+ catch (err) {
65
+ console.error('加载 PostCSS 配置失败:', err);
66
+ return { plugins };
80
67
  }
81
- const dependencies = result.messages
82
- .filter(msg => msg.type === 'dependency')
83
- .map(msg => msg.file)
84
- for (const dep of dependencies) {
85
- fs.watch(dep, eventType => {
68
+ };
69
+ const postCSS = (inputPath, outputPath) => {
70
+ const configPath = join(process.cwd(), 'postcss.config.cjs');
71
+ const postcssConfig = loadPostcssConfig(configPath);
72
+ const readAndProcessCSS = async () => {
73
+ const css = fs.readFileSync(inputPath, 'utf-8');
74
+ fs.mkdirSync(dirname(outputPath), { recursive: true });
75
+ const result = await postcss(postcssConfig.plugins).process(css, {
76
+ from: inputPath,
77
+ to: outputPath
78
+ });
79
+ fs.writeFileSync(outputPath, result.css);
80
+ if (result.warnings().length) {
81
+ result.warnings().forEach(warn => {
82
+ console.warn(warn.toString());
83
+ });
84
+ }
85
+ const dependencies = result.messages
86
+ .filter(msg => msg.type === 'dependency')
87
+ .map(msg => msg.file);
88
+ for (const dep of dependencies) {
89
+ fs.watch(dep, eventType => {
90
+ if (eventType === 'change') {
91
+ readAndProcessCSS();
92
+ }
93
+ });
94
+ }
95
+ };
96
+ readAndProcessCSS();
97
+ fs.watch(inputPath, eventType => {
86
98
  if (eventType === 'change') {
87
- readAndProcessCSS()
99
+ readAndProcessCSS();
88
100
  }
89
- })
90
- }
91
- }
92
- readAndProcessCSS()
93
- fs.watch(inputPath, eventType => {
94
- if (eventType === 'change') {
95
- readAndProcessCSS()
96
- }
97
- })
98
- }
101
+ });
102
+ };
99
103
 
100
- export { postCSS }
104
+ export { postCSS };
@@ -7,11 +7,11 @@
7
7
  * @param inputs
8
8
  * @param output
9
9
  */
10
- declare const buildJS: (inputs: string[]) => Promise<void>
10
+ declare const buildJS: (inputs: string[]) => Promise<void>;
11
11
  /**
12
12
  *
13
13
  * @param script
14
14
  */
15
- declare function buildAndRun(): Promise<void>
15
+ declare function buildAndRun(): Promise<void>;
16
16
 
17
- export { buildAndRun, buildJS }
17
+ export { buildAndRun, buildJS };
@@ -1,13 +1,13 @@
1
- import { rollup } from 'rollup'
2
- import { join } from 'path'
3
- import typescript from '@rollup/plugin-typescript'
4
- import commonjs from '@rollup/plugin-commonjs'
5
- import json from '@rollup/plugin-json'
6
- import styles from 'rollup-plugin-styles'
7
- import { getScriptFiles } from './utils/files.js'
8
- import alias from '@rollup/plugin-alias'
9
- import { rollupStylesCSSImport } from './plugins/loader-css.js'
10
- import { rollupAssets } from './plugins/loader-files.js'
1
+ import { rollup } from 'rollup';
2
+ import { join } from 'path';
3
+ import typescript from '@rollup/plugin-typescript';
4
+ import commonjs from '@rollup/plugin-commonjs';
5
+ import json from '@rollup/plugin-json';
6
+ import styles from 'rollup-plugin-styles';
7
+ import { getScriptFiles } from './utils/files.js';
8
+ import alias from '@rollup/plugin-alias';
9
+ import { rollupStylesCSSImport } from './plugins/loader-css.js';
10
+ import { rollupAssets } from './plugins/loader-files.js';
11
11
 
12
12
  /**
13
13
  * 用于忽略警告
@@ -15,9 +15,10 @@ import { rollupAssets } from './plugins/loader-files.js'
15
15
  * @param warn
16
16
  */
17
17
  const onwarn = (warning, warn) => {
18
- if (warning.code === 'UNRESOLVED_IMPORT') return
19
- warn(warning)
20
- }
18
+ if (warning.code === 'UNRESOLVED_IMPORT')
19
+ return;
20
+ warn(warning);
21
+ };
21
22
  /**
22
23
  * 打包 JS
23
24
  * *** 注意 **
@@ -27,101 +28,108 @@ const onwarn = (warning, warn) => {
27
28
  * @param inputs
28
29
  * @param output
29
30
  */
30
- const buildJS = async inputs => {
31
- if (!global.lvyConfig) global.lvyConfig = {}
32
- if (!global.lvyConfig.build) global.lvyConfig.build = {}
33
- // 插件
34
- const plugins = []
35
- if (typeof global.lvyConfig?.alias !== 'boolean') {
36
- plugins.push(alias(global.lvyConfig?.alias ?? {}))
37
- }
38
- if (typeof global.lvyConfig?.assets !== 'boolean') {
39
- plugins.push(rollupAssets(global.lvyConfig?.assets ?? {}))
40
- }
41
- if (typeof global.lvyConfig?.styles !== 'boolean') {
42
- if (!global.lvyConfig.alias) global.lvyConfig.alias = {}
43
- const newAlias = val => {
44
- const alias = {}
45
- // 遍历 entries 数组
46
- val.entries.forEach(entry => {
47
- alias[entry.find] = entry.replacement
48
- })
49
- return alias
31
+ const buildJS = async (inputs) => {
32
+ if (!global.lvyConfig)
33
+ global.lvyConfig = {};
34
+ if (!global.lvyConfig.build)
35
+ global.lvyConfig.build = {};
36
+ // 插件
37
+ const plugins = [];
38
+ if (typeof global.lvyConfig?.alias !== 'boolean') {
39
+ plugins.push(alias(global.lvyConfig?.alias ?? {}));
50
40
  }
51
- plugins.push(
52
- styles({
53
- alias: newAlias(global.lvyConfig?.alias),
54
- mode: ['inject', () => '']
55
- })
56
- )
57
- plugins.push(rollupStylesCSSImport(global.lvyConfig.styles))
58
- }
59
- plugins.push(json())
60
- if (typeof global.lvyConfig.build != 'boolean') {
61
- //
62
- for (const key in global.lvyConfig.build) {
63
- if (typeof global.lvyConfig.build[key] == 'boolean') {
64
- continue
65
- }
66
- if (key == 'commonjs' && !global.lvyConfig.build['@rollup/plugin-commonjs']) {
67
- plugins.push(commonjs(global.lvyConfig.build[key]))
68
- } else if (key == 'typescript' && !global.lvyConfig.build['@rollup/plugin-typescript']) {
69
- plugins.push(typescript(global.lvyConfig.build[key]))
70
- } else if (key == 'OutputOptions') {
71
- continue
72
- } else if (key == 'RollupOptions') {
73
- continue
74
- }
41
+ if (typeof global.lvyConfig?.assets !== 'boolean') {
42
+ plugins.push(rollupAssets(global.lvyConfig?.assets ?? {}));
75
43
  }
76
- // 如果不存在这些配置
77
- const keys = ['commonjs', 'typescript']
78
- for (const key of keys) {
79
- // 如果是布尔值
80
- if (typeof global.lvyConfig.build[key] == 'boolean') {
81
- continue
82
- }
83
- // 存在这些配置
84
- if (global.lvyConfig.build[key]) {
85
- continue
86
- }
87
- //
88
- if (key === 'commonjs') {
89
- plugins.push(commonjs())
90
- } else if (key === 'typescript') {
91
- plugins.push(typescript())
92
- }
44
+ if (typeof global.lvyConfig?.styles !== 'boolean') {
45
+ if (!global.lvyConfig.alias)
46
+ global.lvyConfig.alias = {};
47
+ const newAlias = val => {
48
+ const alias = {};
49
+ // 遍历 entries 数组
50
+ val.entries.forEach(entry => {
51
+ alias[entry.find] = entry.replacement;
52
+ });
53
+ return alias;
54
+ };
55
+ plugins.push(styles({
56
+ alias: newAlias(global.lvyConfig?.alias),
57
+ mode: ['inject', () => '']
58
+ }));
59
+ plugins.push(rollupStylesCSSImport(global.lvyConfig.styles));
93
60
  }
94
- }
95
- const RollupOptions = global.lvyConfig?.build?.RollupOptions ?? {}
96
- const OutputOptions = global.lvyConfig?.build?.OutputOptions ?? []
97
- // build
98
- const bundle = await rollup({
99
- input: inputs,
100
- plugins: [...plugins],
101
- onwarn: onwarn,
102
- ...RollupOptions
103
- })
104
- // 写入输出文件
105
- await bundle.write({
106
- dir: 'lib',
107
- format: 'es',
108
- sourcemap: false,
109
- preserveModules: true,
110
- assetFileNames: 'assets/[name]-[hash][extname]',
111
- ...OutputOptions
112
- })
113
- }
61
+ plugins.push(json());
62
+ if (typeof global.lvyConfig.build != 'boolean') {
63
+ //
64
+ for (const key in global.lvyConfig.build) {
65
+ if (typeof global.lvyConfig.build[key] == 'boolean') {
66
+ continue;
67
+ }
68
+ if (key == 'commonjs' && !global.lvyConfig.build['@rollup/plugin-commonjs']) {
69
+ plugins.push(commonjs(global.lvyConfig.build[key]));
70
+ }
71
+ else if (key == 'typescript' && !global.lvyConfig.build['@rollup/plugin-typescript']) {
72
+ plugins.push(typescript(global.lvyConfig.build[key]));
73
+ }
74
+ else if (key == 'OutputOptions') {
75
+ continue;
76
+ }
77
+ else if (key == 'RollupOptions') {
78
+ continue;
79
+ }
80
+ }
81
+ // 如果不存在这些配置
82
+ const keys = ['commonjs', 'typescript'];
83
+ for (const key of keys) {
84
+ // 如果是布尔值
85
+ if (typeof global.lvyConfig.build[key] == 'boolean') {
86
+ continue;
87
+ }
88
+ // 存在这些配置
89
+ if (global.lvyConfig.build[key]) {
90
+ continue;
91
+ }
92
+ //
93
+ if (key === 'commonjs') {
94
+ plugins.push(commonjs());
95
+ }
96
+ else if (key === 'typescript') {
97
+ plugins.push(typescript());
98
+ }
99
+ }
100
+ }
101
+ const RollupOptions = global.lvyConfig?.build?.RollupOptions ?? {};
102
+ const OutputOptions = global.lvyConfig?.build?.OutputOptions ?? [];
103
+ // build
104
+ const bundle = await rollup({
105
+ input: inputs,
106
+ plugins: [...plugins],
107
+ onwarn: onwarn,
108
+ ...RollupOptions
109
+ });
110
+ // 写入输出文件
111
+ await bundle.write({
112
+ dir: 'lib',
113
+ format: 'es',
114
+ sourcemap: false,
115
+ preserveModules: true,
116
+ assetFileNames: 'assets/[name]-[hash][extname]',
117
+ ...OutputOptions
118
+ });
119
+ };
114
120
  /**
115
121
  *
116
122
  * @param script
117
123
  */
118
124
  async function buildAndRun() {
119
- if (!global.lvyConfig) global.lvyConfig = {}
120
- if (!global.lvyConfig.build) global.lvyConfig.build = {}
121
- // rollup 配置
122
- let inputDir = global.lvyConfig?.build?.OutputOptions?.input ?? 'src'
123
- const inputFiles = getScriptFiles(join(process.cwd(), inputDir))
124
- await buildJS(inputFiles)
125
+ if (!global.lvyConfig)
126
+ global.lvyConfig = {};
127
+ if (!global.lvyConfig.build)
128
+ global.lvyConfig.build = {};
129
+ // rollup 配置
130
+ let inputDir = global.lvyConfig?.build?.OutputOptions?.input ?? 'src';
131
+ const inputFiles = getScriptFiles(join(process.cwd(), inputDir));
132
+ await buildJS(inputFiles);
125
133
  }
126
134
 
127
- export { buildAndRun, buildJS }
135
+ export { buildAndRun, buildJS };
@@ -1,4 +1,4 @@
1
- const assetsReg = /\.(png|jpg|jpeg|gif|svg|webp|ico)$/
2
- const cssReg = /\.(css|scss|less|sass|less)$/
1
+ const assetsReg = /\.(png|jpg|jpeg|gif|svg|webp|ico)$/;
2
+ const cssReg = /\.(css|scss|less|sass|less)$/;
3
3
 
4
- export { assetsReg, cssReg }
4
+ export { assetsReg, cssReg };
@@ -1,47 +1,49 @@
1
- import { createFilter } from '@rollup/pluginutils'
2
- import { resolve, dirname, basename } from 'node:path'
3
- import { cssReg } from './config.js'
1
+ import { createFilter } from '@rollup/pluginutils';
2
+ import { resolve, dirname, basename } from 'node:path';
3
+ import { cssReg } from './config.js';
4
4
 
5
5
  /**
6
6
  *
7
7
  * @returns
8
8
  */
9
- const rollupStylesCSSImport = options => {
10
- const include = options?.filter ?? cssReg
11
- const filter = createFilter(include, null)
12
- return {
13
- name: 'c-css',
14
- resolveId(source, importer) {
15
- if (filter(source) && importer) {
16
- return resolve(dirname(importer), source)
17
- }
18
- },
19
- load(id) {
20
- if (filter(id)) this.addWatchFile(resolve(id))
21
- return null
22
- },
23
- async transform(code, id) {
24
- if (!filter(id)) return null
25
- // 删除 export default css
26
- const codex = code.replace(/(export|default css)/g, '')
27
- // 使用 eval 执行代码并获取默认导出的值
28
- const evalCode = `
9
+ const rollupStylesCSSImport = (options) => {
10
+ const include = options?.filter ?? cssReg;
11
+ const filter = createFilter(include, null);
12
+ return {
13
+ name: 'c-css',
14
+ resolveId(source, importer) {
15
+ if (filter(source) && importer) {
16
+ return resolve(dirname(importer), source);
17
+ }
18
+ },
19
+ load(id) {
20
+ if (filter(id))
21
+ this.addWatchFile(resolve(id));
22
+ return null;
23
+ },
24
+ async transform(code, id) {
25
+ if (!filter(id))
26
+ return null;
27
+ // 删除 export default css
28
+ const codex = code.replace(/(export|default css)/g, '');
29
+ // 使用 eval 执行代码并获取默认导出的值
30
+ const evalCode = `
29
31
  (() => {
30
32
  ${codex}
31
33
  return css;
32
34
  })()
33
- `
34
- // 得到css变量的值
35
- const csscode = eval(evalCode)
36
- // 确保最后生产的css文件
37
- const refeId = this.emitFile({
38
- // 属于静态资源
39
- type: 'asset',
40
- name: basename(`${id}.css`),
41
- // 内容
42
- source: csscode
43
- })
44
- const contents = `
35
+ `;
36
+ // 得到css变量的值
37
+ const csscode = eval(evalCode);
38
+ // 确保最后生产的css文件
39
+ const refeId = this.emitFile({
40
+ // 属于静态资源
41
+ type: 'asset',
42
+ name: basename(`${id}.css`),
43
+ // 内容
44
+ source: csscode
45
+ });
46
+ const contents = `
45
47
  const createUrl = () => {
46
48
  const platform = ['linux', 'android', 'darwin'];
47
49
  const T = platform.includes(process.platform);
@@ -49,10 +51,10 @@ const rollupStylesCSSImport = options => {
49
51
  return import.meta.ROLLUP_FILE_URL_${refeId}.replace(reg, '')
50
52
  };
51
53
  export default createUrl();
52
- `
53
- return contents
54
- }
55
- }
56
- }
54
+ `;
55
+ return contents;
56
+ }
57
+ };
58
+ };
57
59
 
58
- export { rollupStylesCSSImport }
60
+ export { rollupStylesCSSImport };
@@ -1,40 +1,40 @@
1
- import { resolve, dirname, basename } from 'path'
2
- import { readFileSync } from 'fs'
3
- import { assetsReg } from './config.js'
1
+ import { resolve, dirname, basename } from 'path';
2
+ import { readFileSync } from 'fs';
3
+ import { assetsReg } from './config.js';
4
4
 
5
5
  /**
6
6
  * @param {Object} options
7
7
  * @returns {Object}
8
8
  */
9
- const rollupAssets = options => {
10
- const { filter = assetsReg } = options ?? {}
11
- return {
12
- name: 'rollup-node-files',
13
- resolveId(source, importer) {
14
- if (filter.test(source) && importer) {
15
- return resolve(dirname(importer), source)
16
- }
17
- },
18
- load(id) {
19
- if (filter.test(id)) {
20
- const referenceId = this.emitFile({
21
- type: 'asset',
22
- name: basename(id),
23
- source: readFileSync(id)
24
- })
25
- const content = [
26
- 'const createUrl = () => {',
27
- "const platform = ['linux', 'android', 'darwin'];",
28
- 'const T = platform.includes(process.platform);',
29
- 'const reg = T ? /^file:\\/\\// : /^file:\\/\\/\\//',
30
- 'return import.meta.ROLLUP_FILE_URL_' + referenceId + ".replace(reg, '')",
31
- '};',
32
- 'export default createUrl();'
33
- ].join('\n')
34
- return content
35
- }
36
- }
37
- }
38
- }
9
+ const rollupAssets = (options) => {
10
+ const { filter = assetsReg } = options ?? {};
11
+ return {
12
+ name: 'rollup-node-files',
13
+ resolveId(source, importer) {
14
+ if (filter.test(source) && importer) {
15
+ return resolve(dirname(importer), source);
16
+ }
17
+ },
18
+ load(id) {
19
+ if (filter.test(id)) {
20
+ const referenceId = this.emitFile({
21
+ type: 'asset',
22
+ name: basename(id),
23
+ source: readFileSync(id)
24
+ });
25
+ const content = [
26
+ 'const createUrl = () => {',
27
+ "const platform = ['linux', 'android', 'darwin'];",
28
+ 'const T = platform.includes(process.platform);',
29
+ 'const reg = T ? /^file:\\/\\// : /^file:\\/\\/\\//',
30
+ 'return import.meta.ROLLUP_FILE_URL_' + referenceId + ".replace(reg, '')",
31
+ '};',
32
+ 'export default createUrl();'
33
+ ].join('\n');
34
+ return content;
35
+ }
36
+ }
37
+ };
38
+ };
39
39
 
40
- export { rollupAssets }
40
+ export { rollupAssets };