[英]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.