无法重新声明块作用域变量(打字稿)

问题描述 投票:51回答:6

我正在构建一个节点应用程序,并且.js中的每个文件内部用于执行此操作以在各种包中要求。

let co = require("co");

但是得到

enter image description here

所以使用打字稿似乎在整个项目中只能有一个这样的声明/要求?我对此感到困惑,因为我认为let的范围是当前文件。

我刚刚有一个正在运行的项目但是在重构之后我现在正在处理这些错误。

谁能解释一下?

typescript require
6个回答
42
投票

关于错误本身,let用于声明block scopes中存在的局部变量而不是函数作用域。它也比var更严格,所以你不能做这样的事情:

if (condition) {
    let a = 1;
    ...
    let a = 2;
}

另请注意,case块中的switch子句不会创建自己的块作用域,因此您无法在多个cases中重新声明相同的局部变量,而无需使用{}来创建块。


至于导入,您可能会收到此错误,因为TypeScript无法将您的文件识别为实际模块,而看似模型级别的定义最终会成为它的全局定义。

尝试使用标准ES6方式导入外部模块,该方式不包含显式赋值,并且应使TypeScript将您的文件正确识别为模块:

import * as co from "./co"

如果你已经按照预期命名co,这仍然会导致编译错误。例如,这将是一个错误:

import * as co from "./co"; // Error: import definition conflicts with local definition
let co = 1;

如果您收到错误“找不到模块co”...

TypeScript正在对模块运行完全类型检查,因此如果您没有为要导入的模块定义TS定义(例如,因为它是没有定义文件的JS模块),您可以在.d.ts定义文件中声明您的模块不包含模块级导出:

declare module "co" {
    declare var co: any;
    export = co;
}

6
投票

我能得到的最好的解释是来自Tamas Piro's post

TLDR; TypeScript使用DOM类型表示全局执行环境。在您的情况下,全局窗口对象上有一个'co'属性。

要解决这个问题:

  1. 重命名变量,或
  2. 使用TypeScript模块,并添加一个空导出{}:
export{};

要么

  1. 通过不添加DOM类型来配置编译器选项:

在TypeScript项目目录中编辑tsconfig.json。

{
    "compilerOptions": {
        "lib": ["es6"]
      }
}

6
投票

编译我的Node.JS Typescript应用程序时,我收到了类似的错误:

node_modules/@types/node/index.d.ts:83:15 - error TS2451: Cannot redeclare block-scoped variable 'custom'.

解决方法是删除此:

"files": [
  "./node_modules/@types/node/index.d.ts"
]

并将其替换为:

"compilerOptions": {
  "types": ["node"]
}

5
投票

使用IIFE(Immediately Invoked Function Expression)IIFE

(function () {
    all your code is here...

 })();

1
投票

我遇到了同样的问题,我的解决方案如下:

// *./module1/module1.ts*
export module Module1 {
    export class Module1{
        greating(){ return 'hey from Module1'}
    }
}


// *./module2/module2.ts*
import {Module1} from './../module1/module1';

export module Module2{
    export class Module2{
        greating(){
            let m1 = new Module1.Module1()
            return 'hey from Module2 + and from loaded Model1: '+ m1.greating();
        }
    }
}

现在我们可以在服务器端使用它:

// *./server.ts*
/// <reference path="./typings/node/node.d.ts"/>
import {Module2} from './module2/module2';

export module Server {
    export class Server{
        greating(){
            let m2 = new Module2.Module2();
            return "hello from server & loaded modules: " + m2.greating();
        }
    }
}

exports.Server = Server;

// ./app.js
var Server = require('./server').Server.Server;
var server = new Server();
console.log(server.greating());

在客户端也是如此:

// *./public/javscripts/index/index.ts*

import {Module2} from './../../../module2/module2';

document.body.onload = function(){
    let m2 = new Module2.Module2();
    alert(m2.greating());
}

// ./views/index.jade
extends layout

block content
  h1= title
  p Welcome to #{title}
  script(src='main.js')
  //
    the main.js-file created by gulp-task 'browserify' below in the gulpfile.js

而且,当然,所有这一切的gulp文件:

// *./gulpfile.js*
var gulp = require('gulp'),
    ts = require('gulp-typescript'),
    runSequence = require('run-sequence'),
    browserify = require('gulp-browserify'),
    rename = require('gulp-rename');

gulp.task('default', function(callback) {

    gulp.task('ts1', function() {
        return gulp.src(['./module1/module1.ts'])
            .pipe(ts())
            .pipe(gulp.dest('./module1'))
    });

    gulp.task('ts2', function() {
        return gulp.src(['./module2/module2.ts'])
            .pipe(ts())
            .pipe(gulp.dest('./module2'))
    });

    gulp.task('ts3', function() {
        return gulp.src(['./public/javascripts/index/index.ts'])
            .pipe(ts())
            .pipe(gulp.dest('./public/javascripts/index'))
    });

    gulp.task('browserify', function() {
        return gulp.src('./public/javascripts/index/index.js', { read: false })
            .pipe(browserify({
                insertGlobals: true
            }))
            .pipe(rename('main.js'))
            .pipe(gulp.dest('./public/javascripts/'))
    });

    runSequence('ts1', 'ts2', 'ts3', 'browserify', callback);
})

更新。当然,没有必要单独编译打字稿文件。 qazxsw poi完美无缺。


0
投票

升级时出现此错误

gulp-typescript 3.0.2→3.1.0

把它恢复到3.0.2修复它

© www.soinside.com 2019 - 2024. All rights reserved.