當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。