Program Tip

Typescript ReferenceError : 내보내기가 정의되지 않았습니다.

programtip 2020. 10. 30. 20:31
반응형

Typescript ReferenceError : 내보내기가 정의되지 않았습니다.


공식 핸드북에 따라 모듈을 구현하려고 하면이 오류 메시지가 나타납니다.

포착되지 않은 ReferenceError : 내보내기가 정의되지 않았습니다.

app.js : 2에서

하지만 내 코드 어디에도 이름을 사용하지 않습니다 exports.

이 문제를 어떻게 해결할 수 있습니까?


파일

app.ts

let a = 2;
let b:number = 3;

import Person = require ('./mods/module-1');

module-1.t

 export class Person {
  constructor(){
    console.log('Person Class');
  }
}
export default Person;

tsconfig.json

{
   "compilerOptions": {
        "module": "commonjs",
        "target": "es5",
        "noImplicitAny": false,
        "sourceMap": true,
        "outDir": "scripts/"
    },
    "exclude": [
        "node_modules"
    ]
}

편집하다:

이 답변은 es5더 이상 타겟팅 하지 않으면 작동하지 않을 수 있으므로 답변을 더 완벽하게 만들려고 노력할 것입니다.

원래 답변

CommonJS가 설치되어 있지 않은 경우 ( 정의exports ) 다음 행을 제거해야합니다 tsconfig.json.

 "module": "commonjs",

주석에 따르면 이것만으로는 이후 버전에서 작동하지 않을 수 있습니다 tsc. 이 경우 CommonJS, SystemJS 또는 RequireJS와 같은 모듈 로더를 설치 한 다음 지정할 수 있습니다.

노트 :

생성 된 main.js파일을 보십시오 tsc. 이것은 맨 위에 있습니다.

Object.defineProperty(exports, "__esModule", { value: true });

오류 메시지의 근원 "module": "commonjs",이며을 제거한 후에 는 사라집니다.


이 문제에 대한 몇 가지 다른 해결책

  • Javascript에 대한 다른 참조 앞에 다음 행을 추가하십시오. 이것은 멋진 작은 해킹입니다.
   <script>var exports = {};</script>
  • 이 문제는 최신 버전의 TypeScript에서 발생합니다.이 오류는 typescript 버전 2.1.6을 참조하여 제거 할 수 있습니다.

여전히이 문제가있는 사람들을 위해 컴파일러 대상이 ES6으로 설정되어 있으면 babel에게 모듈 변환을 건너 뛰도록 지시해야합니다. 이렇게하려면 .babelrc파일에 추가하세요.

{
  "presets": [ ["env", {"modules": false} ]]
}

npm install @babel/plugin-transform-modules-commonjs

.babelrc 플러그인에 추가하면 내 질문이 해결되었습니다.


내 솔루션은 내가 추가 한 약간의 트릭으로 위의 모든 것을 요약 한 것입니다. 기본적으로 이것을 HTML 코드에 추가했습니다.

<script>var exports = {"__esModule": true};</script>
<script src="js/file.js"></script>

이것은 심지어 당신이 전자 또는 무언가 를 사용하는 import대신 사용할 수 있도록 허용 require하며 typescript 3.5.1, target : es3-> esnext에서 잘 작동합니다.


나는 같은 문제가 있었고 다음과 같이 tsconfig.json에 " es5 "라이브러리를 추가하여 해결했습니다 .

{
    "compilerOptions": {
        "target": "es5", //defines what sort of code ts generates, es5 because it's what most browsers currently UNDERSTANDS.
        "module": "commonjs",
        "moduleResolution": "node",
        "sourceMap": true,
        "emitDecoratorMetadata": true, //for angular to be able to use metadata we specify in our components.
        "experimentalDecorators": true, //angular needs decorators like @Component, @Injectable, etc.
        "removeComments": false,
        "noImplicitAny": false,
        "lib": [
            "es2016",
            "dom",
            "es5"
        ]
    }
}

간단히 추가하십시오 libraryTarget: 'umd'.

const webpackConfig = {
  output: {
    libraryTarget: 'umd' // Fix: "Uncaught ReferenceError: exports is not defined".
  }
};

module.exports = webpackConfig; // Export all custom Webpack configs.

나도 같은 오류가 발생했습니다. 제 경우에는 TypeScript AngularJS 프로젝트에 다음과 같은 구식 import 문이 있었기 때문입니다.

import { IAttributes, IScope } from "angular";

다음과 같이 JavaScript로 컴파일되었습니다.

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

우리 IAttributes가 코드에서 사용 했고 TypeScript가 그렇지 않으면 무엇을 해야할지 알지 못했기 때문에 이것은 옛날에 필요 했습니다. 그러나 import 문을 제거하고, 변환 한 후 IAttributesng.IAttributes두 자바 스크립트 라인 사라 - 그래서 오류 메시지가 않았다.


For some ASP.NET projects import and export may not be used at all in your Typescripts.

The question's error showed up when I attempted to do so and I only discovered later that I just needed to add the generated JS script to the View like so:

<script src="~/scripts/js/[GENERATED_FILE].Index.js" asp-append-version="true"></script>

Try what @iFreilicht suggested above. If that didn't work after you've installed webpack and all, you may have just copied a webpack configuration from somewhere online and configured there that you want the output to support CommonJS by mistake. Make sure this isn't the case in webpack.config.js:

module.exports = {
  mode: process.env.NODE_ENV || "development",
  entry: { 
    index: "./src/js/index.ts"
  },
  ...
  ...
  output: {
    libraryTarget: 'commonjs',         <==== DELETE THIS LINE
    path: path.join(__dirname, 'build'),
    filename: "[name].bundle.js"
  }
};

참고URL : https://stackoverflow.com/questions/43042889/typescript-referenceerror-exports-is-not-defined

반응형