当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript path.resolve函数代码示例

本文整理汇总了TypeScript中path.resolve函数的典型用法代码示例。如果您正苦于以下问题:TypeScript resolve函数的具体用法?TypeScript resolve怎么用?TypeScript resolve使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了resolve函数的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1: runTest

export function runTest(testDirectory: string, rulesDirectory?: string | string[]): TestResult {
    const filesToLint = glob.sync(path.join(testDirectory, `**/*${MARKUP_FILE_EXTENSION}`));
    const tslintConfig = Linter.findConfiguration(path.join(testDirectory, "tslint.json"), "").results;
    const tsConfig = path.join(testDirectory, "tsconfig.json");
    let compilerOptions: ts.CompilerOptions = { allowJs: true };
    const hasConfig = fs.existsSync(tsConfig);
    if (hasConfig) {
        const {config, error} = ts.readConfigFile(tsConfig, ts.sys.readFile);
        if (error !== undefined) {
            throw new Error(JSON.stringify(error));
        }

        const parseConfigHost = {
            fileExists: fs.existsSync,
            readDirectory: ts.sys.readDirectory,
            readFile: (file: string) => fs.readFileSync(file, "utf8"),
            useCaseSensitiveFileNames: true,
        };
        compilerOptions = ts.parseJsonConfigFileContent(config, parseConfigHost, testDirectory).options;
    }
    const results: TestResult = { directory: testDirectory, results: {} };

    for (const fileToLint of filesToLint) {
        const isEncodingRule = path.basename(testDirectory) === "encoding";

        const fileCompileName = denormalizeWinPath(path.resolve(fileToLint.replace(/\.lint$/, "")));
        let fileText = isEncodingRule ? readBufferWithDetectedEncoding(fs.readFileSync(fileToLint)) : fs.readFileSync(fileToLint, "utf-8");
        const tsVersionRequirement = parse.getTypescriptVersionRequirement(fileText);
        if (tsVersionRequirement !== undefined) {
            const tsVersion = new semver.SemVer(ts.version);
            // remove prerelease suffix when matching to allow testing with nightly builds
            if (!semver.satisfies(`${tsVersion.major}.${tsVersion.minor}.${tsVersion.patch}`, tsVersionRequirement)) {
                results.results[fileToLint] = {
                    requirement: tsVersionRequirement,
                    skipped: true,
                };
                continue;
            }
            // remove the first line from the file before continuing
            const lineBreak = fileText.search(/\n/);
            fileText = lineBreak === -1 ? "" : fileText.substr(lineBreak + 1);
        }
        const fileTextWithoutMarkup = parse.removeErrorMarkup(fileText);
        const errorsFromMarkup = parse.parseErrorsFromMarkup(fileText);

        let program: ts.Program | undefined;
        if (hasConfig) {
            const compilerHost: ts.CompilerHost = {
                fileExists: (file) => file === fileCompileName || fs.existsSync(file),
                getCanonicalFileName: (filename) => filename,
                getCurrentDirectory: () => process.cwd(),
                getDefaultLibFileName: () => ts.getDefaultLibFileName(compilerOptions),
                getDirectories: (dir) => fs.readdirSync(dir),
                getNewLine: () => "\n",
                getSourceFile(filenameToGet) {
                    const target = compilerOptions.target === undefined ? ts.ScriptTarget.ES5 : compilerOptions.target;
                    if (filenameToGet === ts.getDefaultLibFileName(compilerOptions)) {
                        const fileContent = fs.readFileSync(ts.getDefaultLibFilePath(compilerOptions), "utf8");
                        return ts.createSourceFile(filenameToGet, fileContent, target);
                    } else if (denormalizeWinPath(filenameToGet) === fileCompileName) {
                        return ts.createSourceFile(filenameToGet, fileTextWithoutMarkup, target, true);
                    }
                    const text = fs.readFileSync(filenameToGet, "utf8");
                    return ts.createSourceFile(filenameToGet, text, target, true);
                },
                readFile: (x) => x,
                useCaseSensitiveFileNames: () => true,
                writeFile: () => null,
            };

            program = ts.createProgram([fileCompileName], compilerOptions, compilerHost);
        }

        const lintOptions = {
            fix: false,
            formatter: "prose",
            formattersDirectory: "",
            rulesDirectory,
        };
        const linter = new Linter(lintOptions, program);
        // Need to use the true path (ending in '.lint') for "encoding" rule so that it can read the file.
        linter.lint(isEncodingRule ? fileToLint : fileCompileName, fileTextWithoutMarkup, tslintConfig);
        const failures = linter.getResult().failures;
        const errorsFromLinter: LintError[] = failures.map((failure) => {
            const startLineAndCharacter = failure.getStartPosition().getLineAndCharacter();
            const endLineAndCharacter = failure.getEndPosition().getLineAndCharacter();

            return {
                endPos: {
                    col: endLineAndCharacter.character,
                    line: endLineAndCharacter.line,
                },
                message: failure.getFailure(),
                startPos: {
                    col: startLineAndCharacter.character,
                    line: startLineAndCharacter.line,
                },
            };
        });

//.........这里部分代码省略.........
开发者ID:IllusionMH,项目名称:tslint,代码行数:101,代码来源:test.ts

示例2: resolve

import {resolve, join} from "path"
import {argv} from "yargs"

export const base_dir = resolve("./")

const BUILD_DIR = argv.buildDir ? resolve(argv.buildDir) : join(base_dir, "build")
const JS_BUILD_DIR = join(BUILD_DIR, "js")
const CSS_BUILD_DIR = join(BUILD_DIR, "css")

export const build_dir = {
  all: BUILD_DIR,
  js: JS_BUILD_DIR,
  css: CSS_BUILD_DIR,
  test: join(BUILD_DIR, "test"),
  types: join(JS_BUILD_DIR, "types"),
  lib: join(JS_BUILD_DIR, "lib"),
  compiler: join(JS_BUILD_DIR, "compiler"),
}

export const src_dir = {
  lib: join(base_dir, "src", "lib"),
  compiler: join(base_dir, "src", "compiler"),
  test: join(base_dir, "test"),
  examples: join(base_dir, "examples"),
}

export const lib = {
  bokehjs: {
    main: join(build_dir.lib, "main.js"),
    output: join(build_dir.js, "bokeh.js"),
  },
开发者ID:jsignell,项目名称:bokeh,代码行数:31,代码来源:paths.ts

示例3: test

 test('canLoad is false for a local file URL outside root', () => {
   assert.isFalse(new FsUrlLoader('/a/').canLoad(
       Uri.file(path.resolve('/b/foo.html')).toString() as ResolvedUrl));
 });
开发者ID:MehdiRaash,项目名称:tools,代码行数:4,代码来源:fs-url-loader_test.ts

示例4: loadRules

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import * as fs from "fs";
import * as path from "path";
import {camelize} from "underscore.string";

import {getRulesDirectories} from "./configuration";
import {IDisabledInterval, IRule} from "./language/rule/rule";

const moduleDirectory = path.dirname(module.filename);
const CORE_RULES_DIRECTORY = path.resolve(moduleDirectory, ".", "rules");

export interface IEnableDisablePosition {
    isEnabled: boolean;
    position: number;
}

export function loadRules(ruleConfiguration: {[name: string]: any},
                          enableDisableRuleMap: {[rulename: string]: IEnableDisablePosition[]},
                          rulesDirectories?: string | string[]): IRule[] {
    const rules: IRule[] = [];
    const notFoundRules: string[] = [];

    for (const ruleName in ruleConfiguration) {
        if (ruleConfiguration.hasOwnProperty(ruleName)) {
            const ruleValue = ruleConfiguration[ruleName];
开发者ID:DovydasNavickas,项目名称:tslint,代码行数:31,代码来源:ruleLoader.ts

示例5: express

import * as SocketIO from "socket.io";
import * as express from "express";
import * as http from "http";
import * as path from "path";
import * as lobby from "./lobby";

const port = process.env.PORT || 3000;

const app = express();
const server = http.createServer(app);
export const io = SocketIO(server, { transports: [ "websocket" ]});

const publicPath = path.resolve(`${__dirname}/../../public`);
app.use("/", express.static(publicPath));

app.get("/play/:room", (req, res) => {
  if (!lobby.nameRegex.test(req.params.room)) { res.send(400); return; }
  res.sendFile(path.join(publicPath, "index.html"));
});

server.listen(port, () => {
  console.log(`Server started on port ${port}.`);
});

io.on("connection", lobby.onConnection);
开发者ID:elisee,项目名称:make-game,代码行数:25,代码来源:index.ts

示例6: require

const path = require("path")
const { fork } = require("child_process")
const colors = require("colors")

const { readFileSync, writeFileSync } = require("fs")
const pkg = JSON.parse(
  readFileSync(path.resolve(__dirname, "..", "package.json"))
)

pkg.scripts.prepush = "npm run test:prod && npm run build"
// pkg.scripts.commitmsg = "validate-commit-msg"

writeFileSync(
  path.resolve(__dirname, "..", "package.json"),
  JSON.stringify(pkg, null, 2)
)

// Call husky to set up the hooks
fork(path.resolve(__dirname, "..", "node_modules", "husky", "bin", "install"))

console.log()
console.log(colors.green("Done!!"))
console.log()

if (pkg.repository.url.trim()) {
  console.log(colors.cyan("Now run:"))
  console.log(colors.cyan("  npm install -g semantic-release-cli"))
  console.log(colors.cyan("  semantic-release-cli setup"))
  console.log()
  console.log(
    colors.cyan('Important! Answer NO to "Generate travis.yml" question')
开发者ID:netzwerg,项目名称:react-svg-tooltip,代码行数:31,代码来源:semantic-release-prepare.ts

示例7: it

    it('should be able to compile multiple libraries with summaries', () => {
      // Note: we need to emit the generated code for the libraries
      // into the node_modules, as that is the only way that we
      // currently support when using summaries.
      // TODO(tbosch): add support for `paths` to our CompilerHost.fileNameToModuleName
      // and then use `paths` here instead of writing to node_modules.

      // Angular
      write('tsconfig-ng.json', `{
          "extends": "./tsconfig-base.json",
          "angularCompilerOptions": {
            "generateCodeForLibraries": true
          },
          "compilerOptions": {
            "outDir": "."
          },
          "include": ["node_modules/@angular/core/**/*"],
          "exclude": [
            "node_modules/@angular/core/test/**",
            "node_modules/@angular/core/testing/**"
          ]
        }`);

      // Lib 1
      write('lib1/tsconfig-lib1.json', `{
          "extends": "../tsconfig-base.json",
          "angularCompilerOptions": {
            "generateCodeForLibraries": false,
            "enableSummariesForJit": true
          },
          "compilerOptions": {
            "rootDir": ".",
            "outDir": "../node_modules/lib1_built"
          }
        }`);
      write('lib1/module.ts', `
          import {NgModule} from '@angular/core';

          export function someFactory(): any { return null; }

          @NgModule({
            providers: [{provide: 'foo', useFactory: someFactory}]
          })
          export class Module {}
        `);

      // Lib 2
      write('lib2/tsconfig-lib2.json', `{
          "extends": "../tsconfig-base.json",
          "angularCompilerOptions": {
            "generateCodeForLibraries": false,
            "enableSummariesForJit": true
          },
          "compilerOptions": {
            "rootDir": ".",
            "outDir": "../node_modules/lib2_built"
          }
        }`);
      write('lib2/module.ts', `
          export {Module} from 'lib1_built/module';
        `);

      // Application
      write('app/tsconfig-app.json', `{
          "extends": "../tsconfig-base.json",
          "angularCompilerOptions": {
            "generateCodeForLibraries": false
          },
          "compilerOptions": {
            "rootDir": ".",
            "outDir": "../built/app"
          }
        }`);
      write('app/main.ts', `
          import {NgModule, Inject} from '@angular/core';
          import {Module} from 'lib2_built/module';

          @NgModule({
            imports: [Module]
          })
          export class AppModule {
            constructor(@Inject('foo') public foo: any) {}
          }
        `);

      expect(main(['-p', path.join(basePath, 'tsconfig-ng.json')], errorSpy)).toBe(0);
      expect(main(['-p', path.join(basePath, 'lib1', 'tsconfig-lib1.json')], errorSpy)).toBe(0);
      expect(main(['-p', path.join(basePath, 'lib2', 'tsconfig-lib2.json')], errorSpy)).toBe(0);
      expect(main(['-p', path.join(basePath, 'app', 'tsconfig-app.json')], errorSpy)).toBe(0);

      // library 1
      // make `shouldExist` / `shouldNotExist` relative to `node_modules`
      outDir = path.resolve(basePath, 'node_modules');
      shouldExist('lib1_built/module.js');
      shouldExist('lib1_built/module.ngsummary.json');
      shouldExist('lib1_built/module.ngsummary.js');
      shouldExist('lib1_built/module.ngsummary.d.ts');
      shouldExist('lib1_built/module.ngfactory.js');
      shouldExist('lib1_built/module.ngfactory.d.ts');

//.........这里部分代码省略.........
开发者ID:MarkPieszak,项目名称:angular,代码行数:101,代码来源:ngc_spec.ts

示例8: getStylesConfig

export function getStylesConfig(wco: WebpackConfigOptions) {
  const { projectRoot, buildOptions, appConfig } = wco;

  const appRoot = path.resolve(projectRoot, appConfig.root);
  const entryPoints: { [key: string]: string[] } = {};
  const globalStylePaths: string[] = [];
  const extraPlugins: any[] = [];

  // discard comments in production
  const extraPostCssPlugins = buildOptions.target === 'production'
                              ? [postcssDiscardComments]
                              : [];

  // determine hashing format
  const hashFormat = getOutputHashFormat(buildOptions.outputHashing);

  // use includePaths from appConfig
  const includePaths: string [] = [];

  if (appConfig.stylePreprocessorOptions
    && appConfig.stylePreprocessorOptions.includePaths
    && appConfig.stylePreprocessorOptions.includePaths.length > 0
  ) {
    appConfig.stylePreprocessorOptions.includePaths.forEach((includePath: string) =>
      includePaths.push(path.resolve(appRoot, includePath)));
  }

  // process global styles
  if (appConfig.styles.length > 0) {
    const globalStyles = extraEntryParser(appConfig.styles, appRoot, 'styles');
    // add style entry points
    globalStyles.forEach(style =>
      entryPoints[style.entry]
        ? entryPoints[style.entry].push(style.path)
        : entryPoints[style.entry] = [style.path]
    );
    // add global css paths
    globalStylePaths.push(...globalStyles.map((style) => style.path));
  }

  // set base rules to derive final rules from
  const baseRules = [
    { test: /\.css$/, loaders: [] },
    { test: /\.scss$|\.sass$/, loaders: ['sass-loader'] },
    { test: /\.less$/, loaders: ['less-loader'] },
    // stylus-loader doesn't support webpack.LoaderOptionsPlugin properly,
    // so we need to add options in it's query
    { test: /\.styl$/, loaders: [`stylus-loader?${JSON.stringify({
      sourceMap: buildOptions.sourcemap,
      paths: includePaths
    })}`] }
  ];

  const commonLoaders = ['postcss-loader'];

  // load component css as raw strings
  let rules: any = baseRules.map(({test, loaders}) => ({
    exclude: globalStylePaths, test, loaders: ['raw-loader', ...commonLoaders, ...loaders]
  }));

  // load global css as css files
  if (globalStylePaths.length > 0) {
    rules.push(...baseRules.map(({test, loaders}) => ({
      include: globalStylePaths, test, loaders: ExtractTextPlugin.extract({
        remove: false,
        loader: ['css-loader', ...commonLoaders, ...loaders],
        fallbackLoader: 'style-loader',
        // publicPath needed as a workaround https://github.com/angular/angular-cli/issues/4035
        publicPath: ''
      })
    })));
  }

  // supress empty .js files in css only entry points
  if (buildOptions.extractCss) {
    extraPlugins.push(new SuppressExtractedTextChunksWebpackPlugin());
  }

  return {
    entry: entryPoints,
    module: { rules },
    plugins: [
      // extract global css from js files into own css file
      new ExtractTextPlugin({
        filename: `[name]${hashFormat.extract}.bundle.css`,
        disable: !buildOptions.extractCss
      }),
      new webpack.LoaderOptionsPlugin({
        options: {
          postcss: [autoprefixer()].concat(extraPostCssPlugins),
          cssLoader: { sourceMap: buildOptions.sourcemap },
          sassLoader: { sourceMap: buildOptions.sourcemap, includePaths },
          // less-loader doesn't support paths
          lessLoader: { sourceMap: buildOptions.sourcemap },
          // stylus-loader doesn't support LoaderOptionsPlugin properly, options in query instead
          // context needed as a workaround https://github.com/jtangelder/sass-loader/issues/285
          context: projectRoot,
        },
      })
    ].concat(extraPlugins)
//.........这里部分代码省略.........
开发者ID:jeremymwells,项目名称:angular-cli,代码行数:101,代码来源:styles.ts

示例9:

 appConfig.stylePreprocessorOptions.includePaths.forEach((includePath: string) =>
   includePaths.push(path.resolve(appRoot, includePath)));
开发者ID:jeremymwells,项目名称:angular-cli,代码行数:2,代码来源:styles.ts

示例10: getCaseFileName

function getCaseFileName(testCase: string, fileName: string): string
{
	return path.resolve(__dirname, "../../test/cases", testCase, fileName);
}
开发者ID:yaroslav0507,项目名称:CodeFormatter,代码行数:4,代码来源:TsCodeFormatterTests.ts


注:本文中的path.resolve函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。