我遵循了本指南:如何使用gulp将amd模块编译成Typescript到单个文件中。
应用程式
import { CreateModel } from "./Models/CreateModel";
import { CreateView } from "./Views/CreateView";
import { CreateController } from "./Controllers/CreateController";
export class App {
public init() {
const model = new CreateModel();
const view = new CreateView(model);
const controller = new CreateController(model, view);
}
}
CreateController.ts
export class CreateController {
private model: CreateModel;
private view: CreateView;
constructor(model: CreateModel, view: CreateView) {
this.model = model;
this.view = view;
this.init();
}
more code...
}
CreateView.ts
import { CreateModel } from "../Models/CreateModel";
export class CreateView {
private model: CreateModel;
constructor(model: CreateModel) {
this.model = model;
this.init();
}
more code...
}
CreateModel.ts
export class CreateModel {
more code...
}
index.html
<script src="~/Scripts/config.js"></script>
<script data-main="main" src="~/Scripts/require.js"></script>
config.js
var require = {
baseUrl: "../../Scripts/",
paths: {
'App': 'app'
}
};
main.js
requirejs(['App'], function (MyApp) {
var app = new MyApp.App();
app.init();
});
tsconfig.json
{
"compileOnSave": true,
"compilerOptions": {
"lib": [ "es2017", "dom" ],
"moduleResolution": "node",
"module": "amd",
"noImplicitAny": true,
"noEmitOnError": true,
"noUnusedLocals": false,
"noUnusedParameters": false,
"outFile": "./Scripts/app.js",
"removeComments": false,
"sourceMap": true,
"target": "es5"
},
"files": [
"Scripts/Typescripts/App.ts"
],
"exclude": [
"node_modules"
],
"include": [
"./Scripts/Typescripts/**/*"
]
}
这可以正常工作,所有内容都可以编译为〜/ Scripts / app.js。现在,我想为此添加一个外部库。它是ts.validator.fluent,在npm上。如何在客户端使用此功能?
我试图从Github下载文件,将其放在单独的文件夹中,然后导入:
CreateController.ts
import { IValidator, Validator, ValidationResult } from './Plugins/ts.validator.fluent';
export class CreateController {
...
private checkEmail(validateVm: ValidateVm) {
let validationResult = new Validator(validateVm.value).Validate(ValidateRules.email);
...
}
}
但是当我运行它时,出现以下错误:
Failed to load resource: the server responded with a status of 404 (Not Found)
Uncaught Error: Script error for "Plugins/ts.validator.fluent", needed by: Controllers/CreateController
最好的方法是什么?
在客户端代码中使用npm依赖关系的最佳方法可能是使用webpack。
Webpack可以提取您的JS文件,解析导入,然后创建一个包含所有您依赖的代码的捆绑包(类似于您创建单个app.js
JavaScript文件时所做的事情。当webpack看到解析为npm的导入时,模块,它也会自动包含该代码。
注意:您需要注意仅使用专为客户端使用的NPM软件包,而不依赖于Node.js环境。许多软件包设计为仅在服务器端使用,并且取决于节点库等。
由于webpack的自动捆绑功能会做类似的事情,因此此时使用require可能变得不必要,并且使事情变得更复杂,此外,将所有代码导出为单个打字稿文件可能会使事情复杂化。
我建议以下构建过程:
.tmp
).js
文件.tmp
,指定main
入口点。对于这样的事情,开始使用gulp之类的构建系统可能是个好主意,而不是使用运行构建项目所需的单独命令。您还可以使用中的"scripts"
属性package.json
来编写构建命令,这样您就不必手动运行许多不同的命令。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句