[英]typescript and sweetalert2 Uncaught ReferenceError: exports is not defined
開始了一個全新的.net core 2.0項目以開始學習,我選擇使用並學習打字稿。 我一直在遵循這里的指南: 打字稿指南
這樣可以編譯並正常工作。
然后,我想利用我過去使用過的sweetalert2,並按照以下說明進行操作sweetalert2
我在ts文件中創建了一個簡單的helloWorld()
import swal from 'sweetalert2'
function swalHelloWorld() {
swal('hello world!');
}
也可以在我的www文件夾的js文件中編譯
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var sweetalert2_1 = require("sweetalert2");
function swalHelloWorld() {
sweetalert2_1.default('hello world!');
}
並包含在_layout頁面上
現在,當我運行我的項目時,我得到以下錯誤
未捕獲的ReferenceError:未在app.js:2(匿名)@ app.js:2處定義導出
第2行如下
Object.defineProperty(exports,“ __esModule”,{value:true});
我嘗試按照此處的指南進行糾正,但這並沒有幫助
我的tsconfig.json是
{
"compilerOptions": {
"noImplicitAny": true,
"noEmitOnError": true,
"sourceMap": true,
"target": "es5",
"module": "commonjs",
"moduleResolution": "node"
},
"files": [
"./scripts/app.ts"
],
"exclude": [
"node_modules",
"wwwroot"
],
"compileOnSave": true
}
我不確定如何解決此問題
webpack配置
var path = require('path');
module.exports = {
entry: {
site: [
'./Scripts/app.ts']
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'wwwroot/dist/')
},
module: {
rules: [
{
test: /\.tsx?$/,
loader: 'ts-loader',
exclude: /node_modules/,
},
]
},
resolve: {
extensions: [".tsx", ".ts", ".js"]
}
};
git repo: https : //github.com/iamthebarnsley/TSExample
看來您的HTML頁面仍在引用app.js
如果要遵循鏈接的指南 ,則HTML頁面應改為引用bundle.js
生成的bundle.js
文件。
如果要使用<input id="swalalert" type="button" value="swal alert" onclick="swalHelloWorld();" />
從HTML調用swalHelloWorld
,請<input id="swalalert" type="button" value="swal alert" onclick="swalHelloWorld();" />
<input id="swalalert" type="button" value="swal alert" onclick="swalHelloWorld();" />
,那么您需要全局定義swalHelloWorld
:
import swal from 'sweetalert2'
function swalHelloWorld() {
swal('hello from sweet alert');
}
(<any>window).swalHelloWorld = swalHelloWorld;
沒有這個,Webpack就變得聰明了,並且意識到沒有辦法調用swalHelloWorld
(因為它也不是從模塊中導出的),並且從輸出中省略了它。 dist/bundle.js
,當我進行此更改並用HTML中的dist/bundle.js
替換build/app.js
時,警報對我也有效。
我了解了一個更清潔的解決方案:將library
選項添加到Webpack配置中,如此處所示,並帶有您選擇的名稱(例如swalHelloWorld
),這將定義一個名為swalHelloWorld
的全局變量,代表整個入口點模塊。 然后,如果您從模塊導出函數:
import swal from 'sweetalert2'
export function swalHelloWorld() {
swal('hello from sweet alert');
}
HTML可以將其稱為swalHelloWorld.swalHelloWorld(...)
或類似名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.