最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Require in Typescript - Stack Overflow

programmeradmin6浏览0评论

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

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

Share Improve this question edited Nov 14, 2012 at 21:06 asked Nov 14, 2012 at 19:05 user1647411user1647411
Add a ment  | 

6 Answers 6

Reset to default 8
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.

I've put together a blog on using require.js with Typescript.
http://blorkfish.wordpress./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 you use a module flag when you pile your TypeScript:

--module monjs

Or

--module amd

It will convert imports into the appropriate module loading statement:

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

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

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./@guyavraham/smoke-tests-casper-js-with-typescript-8b01b504f3a4

I wrote a fairly prehensive 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.

发布评论

评论列表(0)

  1. 暂无评论