Skip to content
This repository has been archived by the owner on Aug 30, 2024. It is now read-only.

Commit

Permalink
feat(option): add root option
Browse files Browse the repository at this point in the history
  • Loading branch information
vben-admin committed Mar 6, 2021
1 parent 4bf532d commit 7881b27
Show file tree
Hide file tree
Showing 22 changed files with 4,665 additions and 2,640 deletions.
15 changes: 15 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
root = true

[*]
charset = utf-8
end_of_line = lf
trim_trailing_whitespace = true
insert_final_newline = true

[*.md]
insert_final_newline = false
trim_trailing_whitespace = false

[*.{js,jsx,json,ts,tsx,yml}]
indent_size = 2
indent_style = space
2 changes: 2 additions & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
dist
node_modules
27 changes: 27 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
module.exports = {
root: true,
env: {
browser: true,
es2021: true,
es6: true,
node: true,
},
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:@typescript-eslint/recommended',
'plugin:jest/recommended',
'prettier',
],
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaVersion: 12,
sourceType: 'module',
},
plugins: ['@typescript-eslint', 'jest'],
rules: {
'no-console': 'error',
'@typescript-eslint/no-non-null-assertion': 'off',
'@typescript-eslint/ban-ts-comment': 'off',
},
};
6 changes: 6 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
version: 2
updates:
- package-ecosystem: 'yarn'
directory: '/'
schedule:
interval: 'daily'
28 changes: 26 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,29 @@
node_modules
.DS_Store
dist
es
yarn-error.log
.npmrc
.cache

test/upload-server/static

.local
# local env files
.env.local
.env.*.local

# Log files
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*

# Editor directories and files
.idea
# .vscode
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

coverage
1 change: 1 addition & 0 deletions .husky/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
_
6 changes: 6 additions & 0 deletions .husky/commit-msg
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#!/bin/sh

# shellcheck source=./_/husky.sh
. "$(dirname "$0")/_/husky.sh"

npx --no-install commitlint --edit "$1"
9 changes: 9 additions & 0 deletions .husky/common.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#!/bin/sh
command_exists () {
command -v "$1" >/dev/null 2>&1
}

# Workaround for Windows 10, Git Bash and Yarn
if command_exists winpty && test -t 1; then
exec < /dev/tty
fi
6 changes: 6 additions & 0 deletions .husky/lintstagedrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
module.exports = {
'*.{js,jsx,ts,tsx}': ['eslint --fix', 'prettier --write'],
'{!(package)*.json,*.code-snippets,.!(browserslist)*rc}': ['prettier --write--parser json'],
'package.json': ['prettier --write'],
'*.md': ['prettier --write'],
};
10 changes: 10 additions & 0 deletions .husky/pre-commit
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
. "$(dirname "$0")/common.sh"

[ -n "$CI" ] && exit 0

# Format and submit code according to lintstagedrc.js configuration
npm run lint:lint-staged

npm run lint:pretty
2 changes: 2 additions & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
dist/
node_modules
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ import 'element-plus/lib/theme-chalk/el-button.css`;

// prod
import Button from 'element-plus/lib/el-button';
import 'element-plus/lib/theme-chalk/el-button.css`;
import 'element-plus/lib/theme-chalk/el-button.css';

```

Expand Down
2 changes: 1 addition & 1 deletion README.zh_CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ import 'element-plus/lib/theme-chalk/el-button.css`;

// prod
import Button from 'element-plus/lib/el-button';
import 'element-plus/lib/theme-chalk/el-button.css`;
import 'element-plus/lib/theme-chalk/el-button.css';

```

Expand Down
1 change: 1 addition & 0 deletions commitlint.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = { extends: ['@commitlint/config-conventional'] };
12 changes: 12 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
transform: {
'^.+\\.tsx?$': 'ts-jest',
},
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
testPathIgnorePatterns: ['/node_modules/', '/dist/', '/types/'],
testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.(ts|js)x?$',
coverageDirectory: 'coverage',
collectCoverageFrom: ['src/**/*.{ts,tsx,js,jsx}', '!src/**/*.d.ts'],
};
40 changes: 31 additions & 9 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,22 @@
"scripts": {
"dev": "npm run build -- --watch",
"build": "tsup src/index.ts --dts --format cjs,esm",
"prepublishOnly": "yarn build",
"prepublishOnly": "pinst --disable yarn build",
"log": "conventional-changelog -p angular -i CHANGELOG.md -s ",
"example:dev": "npm -C example run serve",
"example:build": "npm -C example run build"
"lint:lint-staged": "lint-staged -c ./.husky/lintstagedrc.js",
"lint:pretty": "pretty-quick --staged",
"lint:eslint": "eslint \"src/**/*.{ts,tsx}\" --fix",
"test": "jest --coverage",
"test:watch": "jest --watch",
"install:husky": "is-ci || husky install",
"postinstall": "npm run install:husky",
"postpublish": "pinst --enable"
},
"keywords": [
"vite",
"html",
"hmr"
"style",
"import",
"css"
],
"repository": {
"type": "git",
Expand All @@ -35,22 +42,37 @@
"@rollup/pluginutils": "^4.1.0",
"change-case": "^4.1.2",
"debug": "^4.3.2",
"es-module-lexer": "^0.4.0",
"es-module-lexer": "^0.4.1",
"magic-string": "^0.25.7"
},
"peerDependencies": {
"vite": ">=2.0.0"
},
"devDependencies": {
"@commitlint/cli": "^12.0.1",
"@commitlint/config-conventional": "^12.0.1",
"@types/jest": "^26.0.20",
"@typescript-eslint/eslint-plugin": "^4.16.1",
"@typescript-eslint/parser": "^4.16.1",
"commitizen": "^4.2.3",
"eslint": "^7.21.0",
"eslint-config-prettier": "^8.1.0",
"eslint-plugin-jest": "^24.1.5",
"husky": "^5.1.3",
"jest": "^26.6.3",
"lint-staged": "^10.5.4",
"pinst": "^2.1.6",
"pretty-quick": "^3.1.0",
"@types/debug": "^4.1.5",
"@types/es-module-lexer": "^0.3.0",
"@types/node": "^14.14.31",
"conventional-changelog-cli": "^2.1.1",
"ts-jest": "^26.5.3",
"ini": "^2.0.0",
"prettier": "^2.2.1",
"rimraf": "^3.0.2",
"tsup": "^4.6.0",
"typescript": "^4.2.2",
"vite": "^2.0.4"
"tsup": "^4.6.1",
"typescript": "^4.2.3",
"vite": "^2.0.5"
}
}
37 changes: 20 additions & 17 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export default (options: VitePluginComponentImport): Plugin => {
const {
include = ['**/*.vue', '**/*.ts', '**/*.js', '**/*.tsx', '**/*.jsx'],
exclude = 'node_modules/**',
root = process.cwd(),
libs = [],
} = options;

Expand Down Expand Up @@ -55,7 +56,7 @@ export default (options: VitePluginComponentImport): Plugin => {

await init;

let imports: (ImportSpecifier & { n?: string })[] = [];
let imports: readonly ImportSpecifier[] = [];
try {
imports = parse(code)[0];
debug('imports:', imports);
Expand All @@ -80,7 +81,7 @@ export default (options: VitePluginComponentImport): Plugin => {

const importStr = code.slice(ss, se);
const importVariables = transformImportVar(importStr);
const importCssStrList = transformComponentCss(lib, importVariables);
const importCssStrList = transformComponentCss(root, lib, importVariables);

let compStrList: string[] = [];
let compNameList: string[] = [];
Expand Down Expand Up @@ -109,7 +110,7 @@ export default (options: VitePluginComponentImport): Plugin => {
};

// Generate the corresponding component css string array
function transformComponentCss(lib: Lib, importVariables: string[]) {
function transformComponentCss(root: string, lib: Lib, importVariables: readonly string[]) {
const {
libraryName,
resolveStyle,
Expand All @@ -126,13 +127,13 @@ function transformComponentCss(lib: Lib, importVariables: string[]) {

let importStr = resolveStyle(name);
if (esModule) {
importStr = resolveNodeModules(importStr);
importStr = resolveNodeModules(root, importStr);
}

let isAdd = true;

if (ensureStyleFile) {
isAdd = ensureFileExists(importStr, esModule);
isAdd = ensureFileExists(root, importStr, esModule);
}

isAdd && set.add(`import '${importStr}';\n`);
Expand All @@ -142,7 +143,7 @@ function transformComponentCss(lib: Lib, importVariables: string[]) {
}

// Generate the corresponding component string array
function transformComponent(lib: Lib, importVariables: string[]) {
function transformComponent(lib: Lib, importVariables: readonly string[]) {
const { libraryName, resolveComponent, libraryNameChangeCase = 'paramCase' } = lib;
if (!resolveComponent || typeof resolveComponent !== 'function' || !libraryName) {
return {
Expand All @@ -157,7 +158,7 @@ function transformComponent(lib: Lib, importVariables: string[]) {
for (let index = 0; index < importVariables.length; index++) {
const libName = importVariables[index];
const name = getChangeCaseFileName(importVariables[index], libraryNameChangeCase);
let importStr = resolveComponent(name);
const importStr = resolveComponent(name);
componentStrSet.add(`import ${libName} from '${importStr}';\n`);
componentNameSet.add(libName);
}
Expand All @@ -169,29 +170,28 @@ function transformComponent(lib: Lib, importVariables: string[]) {
}

// Extract import variables
function transformImportVar(importStr: string) {
export function transformImportVar(importStr: string) {
if (!importStr) {
return [];
}

const exportStr = importStr.replace('import', 'export').replace(/\s+as\s+\w+,?/g, ',');
let importVariables: string[] = [];
let importVariables: readonly string[] = [];
try {
importVariables = parse(exportStr)[1];
debug('importVariables:', importVariables);
} catch (error) {
console.error(error);
debug('transformImportVar:', error);
}
return importVariables;
}

// Make sure the file exists
// Prevent errors when importing non-existent css files
function ensureFileExists(importStr: string, esModule = false) {
function ensureFileExists(root: string, importStr: string, esModule = false) {
const extName = path.extname(importStr);
if (!extName) {
return tryEnsureFile(importStr, esModule);
return tryEnsureFile(root, importStr, esModule);
}

if (esModule) {
Expand All @@ -201,10 +201,10 @@ function ensureFileExists(importStr: string, esModule = false) {
return true;
}

function tryEnsureFile(filePath: string, esModule = false) {
function tryEnsureFile(root: string, filePath: string, esModule = false) {
const filePathList = ensureFileExts.map((item) => {
const p = `${filePath}${item}`;
return esModule ? p : resolveNodeModules(p);
return esModule ? p : resolveNodeModules(root, p);
});
return filePathList.some((item) => fileExists(item));
}
Expand All @@ -222,7 +222,10 @@ function getLib(libraryName: string, libs: Lib[]) {
}

// File name conversion style
function getChangeCaseFileName(importedName: string, libraryNameChangeCase: LibraryNameChangeCase) {
export function getChangeCaseFileName(
importedName: string,
libraryNameChangeCase: LibraryNameChangeCase
) {
try {
return changeCase[libraryNameChangeCase as ChangeCaseType](importedName);
} catch (error) {
Expand All @@ -237,6 +240,6 @@ function needTransform(code: string, libs: Lib[]) {
});
}

function resolveNodeModules(...dir: string[]) {
return normalizePath(path.join(process.cwd(), 'node_modules', ...dir));
function resolveNodeModules(root: string, ...dir: string[]) {
return normalizePath(path.join(root, 'node_modules', ...dir));
}
4 changes: 4 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ export interface Lib {
export interface VitePluginComponentImport {
include?: RegOptions;
exclude?: RegOptions;
/**
* @default process.cwd()
*/
root?: string;
libs: Lib[];
}

Expand Down
8 changes: 8 additions & 0 deletions tests/transformImportVar.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { transformImportVar } from '../src';
import { init } from 'es-module-lexer';

test('transformImportVar test', async () => {
await init;
const res = transformImportVar(`import { Button, Alert } from 'lib'`);
expect(res).toStrictEqual(['Button', 'Alert']);
});
6 changes: 3 additions & 3 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@
"noUnusedLocals": true,
"esModuleInterop": true,
"outDir": "dist",
"lib": ["dom", "esnext"],
"types": ["vite/client", "jest", "node"],
"sourceMap": false,
"noEmitOnError": true
},
"include": ["./src"],
"exclude": ["**/dist", "**/node_modules", "**/test"]
"include": ["src/**/*", "tests/**/*"],
"exclude": ["**/dist", "**/node_modules"]
}
Loading

0 comments on commit 7881b27

Please sign in to comment.