1 |
|
2 | 'use strict';
|
3 |
|
4 | const path = require('path');
|
5 | const fs = require('fs');
|
6 | const npm = require('./npm-dependency');
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 | function importNpmModule(moduleName) {
|
14 |
|
15 | const modulePath = path.join(process.cwd(), 'node_modules', moduleName);
|
16 |
|
17 |
|
18 | const pkg = npm.loadPackage(modulePath);
|
19 | const key = [
|
20 | 'sass',
|
21 | 'scss',
|
22 |
|
23 | 'style'
|
24 | ].find(function (key) {
|
25 | return typeof pkg[key] === "string";
|
26 | });
|
27 | if (key || (pkg.main && !pkg.main.endsWith('.js'))) {
|
28 |
|
29 | return path.join(modulePath, pkg[key || 'main']);
|
30 | }
|
31 |
|
32 |
|
33 | const name = [
|
34 | 'index.scss', 'index.sass', 'index.wxss', 'index.css',
|
35 | 'style.scss', 'style.sass', 'style.wxss', 'style.css',
|
36 | ].find(name => fs.existsSync(path.join(modulePath, name)));
|
37 | if (name) {
|
38 | return path.join(modulePath, name);
|
39 | }
|
40 |
|
41 |
|
42 | const bower = fs.existsSync(path.join(modulePath, 'bower.json')) && npm.loadPackage(modulePath, 'bower.json');
|
43 | if (bower) {
|
44 | const key = ['sass', 'scss', 'wxss', 'css', 'style'].find(key => typeof bower[key] === "string");
|
45 | if (key || (bower.main && !bower.main.endsWith('.js'))) {
|
46 | return path.join(modulePath, bower[key || 'main'])
|
47 | }
|
48 | }
|
49 | }
|
50 |
|
51 |
|
52 |
|
53 |
|
54 |
|
55 | function syncFile(file) {
|
56 |
|
57 | if (
|
58 | !['.css', '.scss', '.sass'].includes(path.extname(file)) &&
|
59 | !fs.existsSync(file + '.scss') &&
|
60 | !fs.existsSync(file + '.css') &&
|
61 | !fs.existsSync(file + '.sass')
|
62 | ) {
|
63 | fs.copyFileSync(file, file + '.scss');
|
64 | }
|
65 | return file;
|
66 |
|
67 | }
|
68 |
|
69 |
|
70 |
|
71 |
|
72 |
|
73 |
|
74 | module.exports = function importer(url, prev, done) {
|
75 |
|
76 | if (url[0] === '~' && url[1] !== '/') {
|
77 |
|
78 | const npmModule = url.substr(1);
|
79 | const n = npmModule.split('/').length;
|
80 | if (n === 1 || (n === 2 && npmModule[0] === '@')) {
|
81 |
|
82 | const file = importNpmModule(npmModule);
|
83 | if (file) {
|
84 | return {
|
85 | file: syncFile(file),
|
86 | }
|
87 | }
|
88 | } else {
|
89 | const file = path.join(process.cwd(), 'node_modules', npmModule);
|
90 | return { file: syncFile(file) }
|
91 | }
|
92 | } else if (prev && prev.indexOf('node_modules') >= 0) {
|
93 |
|
94 |
|
95 | const file = path.resolve(path.dirname(prev), url);
|
96 | return { file: syncFile(file) }
|
97 | } else if (url.endsWith(".wxss") && !fs.existsSync(url + '.scss') && !fs.existsSync(url + '.css') && !fs.existsSync(url + '.sass')) {
|
98 |
|
99 |
|
100 |
|
101 |
|
102 | if (url.startsWith("file://")) {
|
103 |
|
104 | url = url.substr(7)
|
105 | }
|
106 | return { contents: '@import url("' + url.trim() + '");' };
|
107 |
|
108 | } else {
|
109 | return null;
|
110 | }
|
111 | }; |
\ | No newline at end of file |