[英]Typescript ReferenceError: exports is not defined
嘗試按照官方手冊實現模塊,我收到此錯誤消息:
未捕獲的 ReferenceError:未定義導出
在 app.js:2
但在我的代碼中,我從未使用過名稱exports
。
我怎樣才能解決這個問題?
let a = 2;
let b:number = 3;
import Person = require ('./mods/module-1');
export class Person {
constructor(){
console.log('Person Class');
}
}
export default Person;
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"noImplicitAny": false,
"sourceMap": true,
"outDir": "scripts/"
},
"exclude": [
"node_modules"
]
}
此問題的其他解決方案很少
<script>var exports = {};</script>
編輯:
如果您不再針對es5
,此答案可能不起作用,我將嘗試使答案更完整。
原始答案
如果 CommonJS 沒有安裝(它定義了exports
),你必須從你的tsconfig.json
中刪除這一行:
"module": "commonjs",
根據評論,僅此一項可能不適用於更高版本的tsc
。 如果是這種情況,您可以安裝一個模塊加載器,如 CommonJS、SystemJS 或 RequireJS,然后指定它。
筆記:
查看tsc
生成的main.js
文件。 你會在最上面找到這個:
Object.defineProperty(exports, "__esModule", { value: true });
它是錯誤信息的根源,刪除"module": "commonjs",
后,它就會消失。
從package.json
中刪除"type": "module"
。
通過將module
編譯器選項設置為es6
可以解決此問題:
{
"compilerOptions": {
"module": "es6",
"target": "es5",
}
}
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。
幾周前我遇到了這個問題,並在短期內使用了上面的exports hack,但最終找到了另一種對我有用的方法。
因此,與上面的其他一些響應不同,我實際上希望我正在編譯的代碼是一個模塊。 通過設置"target": "es6",
"module": "esnext"
,然后使用type="module"
而不是type="text/javascript"
鏈接到我編譯的 JS 文件,我的編譯代碼不再有Object.defineProperty(exports, "__esModule", { value: true });
行,它仍然是一個模塊🎉
我的 tsconfig:
{
"compilerOptions": {
"target": "es6",
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"module": "esnext",
"moduleResolution": "node",
"lib": ["es2016", "esnext", "dom"],
"outDir": "build",
"strict": true,
"strictNullChecks": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"declaration": true,
},
"include": ["src/index.ts"],
"exclude": ["build"]
}
我在 HTML head
標簽中指向我的編譯代碼的鏈接:
<script src="../build/index.js" type="module" defer></script>
作為獎勵,現在我還可以在 HTML body
代碼下方的單獨type="module"
腳本中導入我在 index.js 文件中導出的任何內容:
<script type="module">
import { coolEncodingFunction, coolDecodingFunction } from "../build/index.js";
/* Do stuff with coolEncodingFunction and coolDecodingFunction */
/* ... */
</script>
我遇到了同樣的問題並解決了它,將“ es5 ”庫添加到 tsconfig.json,如下所示:
{
"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"
]
}
}
我也有同樣的錯誤。 就我而言,這是因為我們在 TypeScript AngularJS 項目中有一個老式的 import 語句,如下所示:
import { IAttributes, IScope } from "angular";
像這樣編譯成 JavaScript:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
這在過去是需要的,因為我們在代碼中使用了IAttributes
,否則 TypeScript 將不知道如何處理它。 但是在刪除 import 語句並將IAttributes
轉換為ng.IAttributes
之后,這兩行 JavaScript 行消失了 - 錯誤消息也消失了。
對於仍然有這個問題的人,如果你的編譯器目標設置為 ES6,你需要告訴 babel 跳過模塊轉換。 為此,請將其添加到您的.babelrc
文件中
{
"presets": [ ["env", {"modules": false} ]]
}
我有與問題的原始海報類似的問題:
我最好告訴你我犯了哪些錯誤以及我如何糾正它,這可能會對某人有所幫助。
我有 javascript nodejs 項目並將其轉換為打字稿。
以前在 package.json 中,當我在 JavaScript 中運行時,我有“type”:“module”。
當我將其轉換為 TypeScript 項目並開始轉換 .ts 文件中的文件並開始使用以下命令運行時:
npx tsc test.ts && node test.ts
我會得到上述錯誤。
我通過簡單地從 package.json 中刪除 "type":"module" 擺脫了錯誤
我的 tsconfig.json 如下所示:
{
"compilerOptions": {
"target": "esnext",
"lib": ["es6", "es5", "es7", "dom"],
"allowJs": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "es6",
"outDir": "./build",
"moduleResolution": "node",
"resolveJsonModule": true,
"skipLibCheck": true
},
"exclude": ["node_modules", "build"]
我正在使用節點 14 和 TypeScript 4.2.4
對我來說,從 tsconfig.json 中刪除"esModuleInterop": true
就可以了。
只需添加libraryTarget: 'umd'
,就像這樣
const webpackConfig = {
output: {
libraryTarget: 'umd' // Fix: "Uncaught ReferenceError: exports is not defined".
}
};
module.exports = webpackConfig; // Export all custom Webpack configs.
在 package.json 中添加"type": "module"
in terminal type in
npx tsc --init
它將創建一個 tsconfig.json 將"target": "es5"
更改為"target": "es6"
注釋掉//"module": "commonjs",
取消注釋"moduleResolution": "node",
你應該很好地進入 package.json 創建一個構建腳本
"build": "tsc -p tsconfig.json"
然后當你想構建你只需編譯npm run build
然后執行,應該是好的
對於某些 ASP.NET 項目,您的 Typescripts 中可能根本不使用import
和export
。
當我嘗試這樣做時出現了問題的錯誤,后來我才發現我只需要將生成的 JS 腳本添加到視圖中,如下所示:
<script src="~/scripts/js/[GENERATED_FILE].Index.js" asp-append-version="true"></script>
注意:這可能不適用於 OP 的答案,但我收到了這個錯誤,這就是我解決它的方法。
因此,我面臨的問題是,當我從特定 CDN 檢索“js”庫時出現此錯誤。
我做的唯一錯誤的事情是從 CDN 的cjs
目錄導入,如下所示: https://cdn.jsdelivr.net/npm/@popperjs/core@2.4.0/dist/cjs/popper.min.js
://cdn.jsdelivr.net/npm/@popperjs/core@2.4.0/dist/cjs/popper.min.js
注意dist/cjs
部分? 這就是問題所在。
在我的案例中,我回到 CDN (jsdelivr) 並導航到umd
文件夾。 我可以找到另一組popper.min.js
,這是要導入的正確文件: https://cdn.jsdelivr.net/npm/@popperjs/core@2.4.0/dist/umd/popper.min.js
://cdn.jsdelivr.net/npm/@popperjs/core@2.4.0/dist/umd/popper.min.js .
要解決此問題,請將這兩行放在您的index.html頁面中。
<script>var exports = {"__esModule": true};</script>
<script type="text/javascript" src="/main.js">
確保檢查您的main.js文件路徑。
所以這是一個超級通用的 TypeScript 錯誤,這個 StackOverflow 問題是我研究我的問題時進行的各種查詢的第一個結果。 它有 385k 的瀏覽量。
對於那些使用 Angular/TypeScript 和使用 ng-packagr 的 Angular 庫的人來說,看到一個通用的“ ReferenceError: exports is not defined ”,你需要為每個特性/組件/服務定義public-api.ts
,這樣你就可以將它包含在index.ts
例如在這篇文章的這個repo中找到的
幾個淺顯的例子就像這樣引用創建庫
ng new workspace --no-create-application
cd workspace
ng generate app home --routing=true --style=scss
ng generate app admin --routing=true --style=scss
ng generate library lib
... # include your library 'lib' into your application 'home'
ng build lib --watch &
ng serve home --open
沒有直接解釋的是您的index.ts
和public-api.ts
文件需要在每個功能/組件/服務中。 如果您有一個復雜的庫,例如下面 repo 中的這些示例功能 A、B 和 C。 回購具有以下內容:
./public-api
)./public-api
)./public-api
)試試上面的@iFreilicht 建議。 如果在你安裝了 webpack 之后還是不行,你可能只是從網上某個地方復制了一個 webpack 配置,並在那里配置了你希望輸出錯誤地支持 CommonJS 的配置。 確保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"
}
};
有同樣的問題並通過更改 JS 包加載順序來修復它。
檢查調用所需包的順序並以適當的順序加載它們。
在我的特定情況下(不使用模塊捆綁器)我需要加載Redux
,然后是Redux Thunk
,然后是React Redux
。 在Redux Thunk
給我導出之前加載React Redux
exports is not defined
。
我有同樣的問題,但我的設置需要不同的解決方案。
我正在使用帶有config-overrides.js
文件的create-react-app-rewired
包。 以前,我使用 custom customize-cra
中的addBabelPresets
導入(在override()
方法中)並決定將這些預設抽象到一個單獨的文件中。 巧合的是,這解決了我的問題。
我將useBabelRc()
添加到config-overrides.js
中的override()
方法,並創建了一個babel.config.js
文件,其中包含以下內容:
module.exports = {
presets: [
'@babel/preset-react',
'@babel/preset-env'
],
}
我在SSR
客戶端部分遇到了這樣的錯誤,因為它使用了一個使用tsconfig.json
compilerOptions
作為target: ES5
使用CommonJS
進行模塊解析帶來了什么tsc CLI Options Compiler Options : target === "ES3" or "ES5" ? "CommonJS" : "ES6"
target === "ES3" or "ES5" ? "CommonJS" : "ES6"
。 雖然它使用了目標ESNext
。
首先,在您的公共文件夾中找到您的index.html
,找到腳本<script src="myScript.js"></script>
的引用並添加type="module"
像這樣:
<script type="module" src="myScript.js"></script>
其次,在您的tsconfig.json
中確保目標設置為es5
,模塊設置為es2015
"compilerOptions": {
"target": "es5", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
/* Modules */
"module": "es2015", /* Specify what module code is generated. */
}
重要:確保使用.js
擴展名導入,例如import Piece from './classes/piece.js'
沒有直接回答這個問題,但是沒有提到這個案例的 stackoverflow 線程,我花了一些時間來調試,所以在這里添加它以防將來對某人有所幫助。
我收到來自導入的 NPM 模塊的錯誤“未定義導出”。 更改我的 typescript 配置什么也沒做,因為我無法控制導入的第三方代碼。 問題是該 package 的導入語法無效。 例如,我導入了“@mui/material/TextField/TextField”,但正確的導入應該是“@mui/material/TextField”。
我也有這個問題。 然后我只需將"module": "commonjs"
更改為"module": "ESNext"
一切正常。
這是我的tsconfig.json
:
{
"compilerOptions": {
"module": "ESNext",
"esModuleInterop": true,
"target": "ESNext",
"moduleResolution": "node",
"sourceMap": true,
"outDir": "dist",
},
"lib": ["ESNext"],
}
我希望它能解決你的問題!
在所有配置之后,只需使用這些命令,在此處輸入圖像描述首先運行此tsc
第二次運行這個,如果你的文件名是 index node index.js
我在切換到“Node 16 + ESM + strict”tsconfig.json 后不久遇到了這個錯誤。
我認為 ESM 的變化是導致它的原因。
我必須將文件一分為二才能找出根本原因:
exports.webhookTaskProcessor = functions.firestore
.document("items/{itemId}/tasks/{taskId}")
.onCreate((_change, context) => {
processItemTasks(context.params.itemId);
});
這修復了它:
export const webhookTaskProcessor = functions.firestore
.document("items/{itemId}/tasks/{taskId}")
.onCreate((_change, context) => {
processItemTasks(context.params.itemId);
});
如果錯誤信息能提供更多幫助,那就太好了。 我希望這個面包屑對你有用。
我認為問題可能是配置不匹配。
為了清楚起見,我只是在這里發布部分內容。 Github 項目https://github.com/jmmvkr/ts-express/有一套完整的文件演示了工作解決方案 1 和解決方案 2。
工作方案1,ES模塊
/* Configuration for ES Module */
// tsconfig.json
{
"compilerOptions": {
"module": "es6", // or "esnext"
}
}
// package.json
{
"type": "module", // type is module
}
工作解決方案 2,CommonJS
/* Configuration for CommonJS */
// tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
}
}
// package.json
{
"type": "", // type is NOT module
}
混合,不工作
/* Mixed, got ReferenceError: exports is not defined in ES module scope */
// tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
}
}
// package.json
{
"type": "module", // type is module
}
{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist",
"sourceMap": true,
"declaration": false,
"module": "esnext",
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es5",
"typeRoots": ["node_modules/@types"],
"lib": ["es2018", "dom"]
}
}
如果您只是將接口用於類型,請省略export
關鍵字,ts 可以選擇類型而無需導入。 他們的關鍵是您不能在任何地方使用import
/ export
。
export interface Person {
name: string;
age: number;
}
進入
interface Person {
name: string;
age: number;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.