简体   繁体   中英

Require in Typescript

Can someone explain how would this look in TypeScript. Can it be done via imports?

JS:

var casper = require('casper').create({})

CoffeeScript:

casper = require("casper").create()

Visual Studio error: Error 1 The name ''casper'' does not exist in the current scope

import something = module('something');
var somevar = something.create({});

The point to note here I think is that TS today doesn't allow dotting off of module('something') so you have to break your statement into two.

If you use a module flag when you compile your TypeScript:

--module commonjs

Or

--module amd

It will convert imports into the appropriate module loading statement:

import something = module('something');
var somevar = something.create();

I've put together a blog on using require.js with Typescript.
http://blorkfish.wordpress.com/2012/10/23/typescript-organizing-your-code-with-amd-modules-and-require-js/ You will be able to write code like this:

require["casper", (casper) => {
    var item = casper.create();
};

If that casper thing is something written in JavaScript, you need to declare a module for it too (or else it won't compile).

By convention, you put such declaration in a separate file named casper.d.ts:

declare module casper {
    export class SomeClassInCasper {
    }

    export function someFunctionInCasper();
}

And you would include a reference to that casper.d.ts at the top above your import/module:

/// <reference path="casper.d.js" />

import casper = import("casper");

casper is installed through npm on the global scope.

  1. typings install dt~casperjs --global --save
  2. declare var casper; (on your code)

A short casper with typescript how to can be seen here:

https://medium.com/@guyavraham/smoke-tests-casper-js-with-typescript-8b01b504f3a4

I wrote a fairly comprehensive post on using Require in TypeScript. My approach does NOT require you to use the ugly

require(['dependency'], function() {

}

syntax. Instead, in TypeScript you get to use the convenient import x = module("x") syntax.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM