如何在客户端使用外部打字稿库?

时间:2019-08-01 14:19:00

标签: typescript requirejs

我遵循了以下指南:How to compile Typescript into a single file with amd modules with gulp

App.ts

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

这里最好的方法是什么?

2 个答案:

答案 0 :(得分:2)

在客户端代码中使用npm依赖关系的最佳方法可能是使用webpack

Webpack可以获取您的JS文件,解析导入,然后创建一个包含所有您依赖的代码的捆绑包(类似于您创建单个app.js JavaScript文件的过程。)看到一个解析为npm模块的导入,它将也自动包含该代码。

注意:您需要注意仅使用专为客户端使用的NPM软件包,而不依赖于Node.js环境。许多软件包设计为仅在服务器端使用,并且取决于节点库等。

此时使用require可能会变得不必要,并使事情变得更加复杂,因为webpack的自动捆绑功能会执行类似的操作,此外,将所有代码导出为单个打字稿文件可能会使事情复杂化。

我建议以下构建过程:

  1. 编译所有打字稿代码,并导出到临时目录(例如.tmp
  2. 使用webpack处理.js中的.tmp文件,并指定main入口点。

对于类似这样的事情,最好使用gulp之类的构建系统,而不是使用运行构建项目所需的单独命令。您还可以使用"scripts"中的package.json属性来编写构建命令,这样您就不必手动运行许多不同的命令。

答案 1 :(得分:0)

我最终听了Sam Lanning的回答,现在可以了!

文件夹结构

├── Scripts
|   ├── Ts-build
|   ├── Typescripts
|       ├── Subfolders
|       App.ts
|   App.js
└── index.html
tsconfig.json
webpack.config.js

package.json

{
  "name": "MyProject",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "ts.validator.fluent": "^1.3.0"
  },
  "devDependencies": {
    "@types/bootstrap": "^4.3.1",
    "@types/jquery": "^3.3.30",
    "@types/node": "^12.6.9",
    "jquery": "^3.4.1",
    "lodash": "^4.17.15",
    "popper.js": "^1.15.0",
    "source-map-loader": "^0.2.4",
    "typescript": "^3.5.3",
    "webpack": "^4.39.0",
    "webpack-cli": "^3.3.6"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack"
  },
  "author": "",
  "license": "ISC"
}

webpack.config.js

var path = require('path');
var webpack = require('webpack');

module.exports = {
    devtool: 'source-map',
    entry: './Scripts/Ts-build/App',
    mode: 'development',
    target: 'web',
    watch: true,

    output: {
        filename: 'app.js',
        path: path.resolve(__dirname, './Scripts')
    },

    module: {
        rules: [{
            test: /\.(js)?$/,
            include: path.resolve(__dirname, './Scripts/Ts-build/'),
            exclude: /node_modules/
        },
        {
            enforce: "pre",
            test: /\.js$/,
            loader: "source-map-loader"
        }]
    },

    resolve: {
        extensions: [".webpack.js", ".web.js", ".js"]
    },

    externals: {
        // require("jquery") is external and available
        //  on the global var jQuery
        "jquery": "jQuery"
    },

    plugins: [
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery',
            'window.jQuery': 'jquery'
        })
    ]
};