目录
1. importLocal
1.1. webpack-dev-server 的一个特性
1.2. __filename、__dirname
1.3. path.dirname、path.join、path.resolve、path.relative
1.4. process.cwd()
1.5. find-up
1.6. pkg-dir
1.7. import-local
2. rimraf
3. glob
3.1. glob 模式
3.2. glob 起源
3.3. glob 示例
4. globby
1. importLocal
1.1. webpack-dev-server 的一个特性
webpack-dev-server 官网描述了其 CLI 的一个特性:
webpack-dev-server will always use a local installation over a global one. https://github.com/webpack/webpack-dev-server
看看效果:
看看 webpack-dev-server 实现:
看看 import-local 实现:
分析一波原理:...
1.2. __filename、__dirname
示例:
1.3. path.dirname、path.join、path.resolve、path.relative
示例:
const path = require("path");
console.log(path.dirname(__filename));
const p1 = path.join("/foo", "bar", "baz/asdf", "quuz", "..");
console.log(p1);
const p2 = path.join("./a", "./b");
console.log(p2);
const p3 = path.resolve("/foo/bar", "/tmp/file/");
console.log(p3);
const p4 = path.resolve("wwwroot", "staticfiles/png/", "../gif/image.gif");
console.log(p4);
const p5= path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb');
console.log(p5);
1.4. process.cwd()
示例:
1.5. find-up
示例:
const findUp = require('find-up');
(async () => {
console.log(await findUp('unicorn.png'));
console.log(await findUp(['rainbow.png', 'unicorn.png']));
console.log(await findUp("unicorn.png", {cwd: __dirname}))
})();
1.6. pkg-dir
源码:
示例:
const pkgDir = require('pkg-dir');
(async () => {
const dir = await pkgDir(__dirname);
console.log(dir);
})();
1.7. import-local
示例:
const importLocal = require('import-local');
if (importLocal(__filename)) {
console.log('Using local version of this package');
} else {
// Code for both global and local version here…
}
原理:
2. rimraf
rimraf 是 Linux 命令 rm -rf 的 node 版本。就是用来删除目录、删除文件的。
示例:
3. glob
3.1. glob 模式
In computer programming, glob patterns specify sets of filenames with wildcard characters.
mv *.txt textfiles/ moves
moves (mv) all files with names ending in .txt from the current directory to the directory textfiles.
—— 来源于 Wiki
3.2. glob 起源
The command interpreters of the early versions of Unix relied on a separate program to expand wildcard characters in unquoted arguments to a command: /etc/glob. That program performed the expansion and supplied the expanded list of file paths to the command for execution. Its name is an abbreviation for "global command". Later, this functionality was provided as a library function, glob(), used by programs such as the shell.
—— 来源于 Wiki
3.3. glob 示例
4. globby
globby 是 glob 的增强版本
示例:
参考:
import-local: https://github.com/sindresorhus/import-local process.cwd(): https://nodejs.org/api/process.html#process_process_cwd find-up: https://github.com/sindresorhus/find-up resolve-cwd: https://github.com/sindresorhus/resolve-cwd pkg-dir: https://github.com/sindresorhus/pkg-dir