npm - Yakalanmamış ReferenceError: require tanımlanmadı TypeScript


Bir .ts dosyasından namespace'i dışa aktarmaya ve diğer .ts dosyasından içe aktarmaya çalışıyorum ve NewMain.ts:2 Uncaught ReferenceError: require is not defined hatası alıyorum. Ben yeniyim ve aslında TypeScript öğreniyordum. İşte benim tsconfig.json dosyam

{
 "compilerOptions": {
     "module": "commonjs",
     "noImplicitAny": true,
     "removeComments": true,
     "preserveConstEnums": true,
     "sourceMap": true
 },
 "files": [
     "greeter.ts",
     "Main.ts",
     "RajIsh.ts",
     "NewMain.ts"        
  ],
 "exclude": [
    "node_modules"
  ]
}

İşte isim alanını içe aktardığım NewMain.ts dosyam

 import {DepartmentSection} from "./RajIsh"
 class Employee{
     name: string;
     //Function
     Display(username:string)
     {
         this.name=username;
         console.log(this.name);
     }
 }
 var person = new Employee();
 var itCell= new DepartmentSection.ITCell("Information Technology Section");
 console.log("Displaying from NewMain.ts by importing......");
 console.log(person.Display("XYZ")+" belongs to "+  itCell.DisplaySectionName("Finance Revenue and Expenditure Section"));
 console.log("Wooooooooo Hurrey!!!!!!!!!!!!!!!......");

ve işte RajIsh.ts dosyasındaki ad alanım

 export namespace DepartmentSection {
    export class Section  {
        //===================Class Property by default public
        name: string;

        //==================Constructor of Section Class taking parameter of Employee Name
        constructor(theName: string) {

                this.name = theName;
            }
        //====================Function which displays the department name of a person
        Department(depatmentName: string = "") {
            console.log(`${this.name} ,  ${depatmentName} !!`);
        }

    }
      //============================================================================================
      //=========================Inheritance

    export class ITCell extends Section{
        constructor(SectionName: string) { 
            super(SectionName); 
        }
        DisplaySectionName(DepartmentName:string) {
            console.log("Printing Section name...");
            super.Department(DepartmentName);
        }

    }
     export class LoanAndAccount extends Section {
        constructor(SectionName: string) { 
            super(SectionName); 
        }
        DisplaySectionName(DepartmentName:string) {
            console.log("Printing another Section name...");
            super.Department(DepartmentName);
        }
    }

 }

Hatalı olduğum yer neresi? Bunu şu şekilde de import etmeyi denedim import DepartmentSection=require('./RajIsh'); ama sınıfa ve fonksiyona erişmeye çalıştığımda Property 'ITCell' does not exist on type 'typeof' RajIsh şeklinde bir hata veriyor. Ne yapmam gerekiyor?

Cevap #1

Birkaç zaman önce aynı sorunla karşılaştım ve SystemJs kullanarak çözdüm. Systemjs kullanmayı deneyin. Komut satırından npm ile SystemJs yükleyin: npm install systemjs ve Index.html dosyanızda head bölümünde bu şekilde uygulayın

 <script src="node_modules/systemjs/dist/system.js"></script>

 <script>
    SystemJS.config({
    baseURL:"/", //Can write the path like /script and the browser will look inside the script folder
    packages:{
        ".":{
            defaultExtension:'js'
        }
    }
  })
  SystemJS.import("./main.js")
 <script>

Bunu dene, çalışması gerekir. Umarım sana yardımcı olur.

Cevap #2

TypeScript derleyicisini .ts dosyalarınızı tek bir main.js dosyasında birleştirmek için kullandığınızda, import ve exporte hiç ihtiyacınız yok!

require ve import yalnızca bir modül paketleyici kullandığınızda çalışır - typescript'e dahil değildir!

Kodunuzu düzenlemek için namespace kullanmayı seçebilirsiniz, ama bu gerekli değildir.

dosya thing.ts

namespace Test {
    class Thing {
    }
}

dosya app.ts

namespace Main {
    class App {
        constructor(){
             // you can make a new Thing instance here without import!
             let n = new Test.Thing()
        }
    }
}

Bu işe yarıyor çünkü ad alanları aslında global kapsamda, bu yüzden onlara her yerden erişebilirsiniz. Webpack gibi modül paketleyiciler kodunuzu özel tutar (global kapsamda kullanılamaz) ve bu yüzden webpack ile import ve export kullanmanız gerekir.