簡體   English   中英

如何在客戶端使用外部打字稿庫?

[英]How to use external typescript libraries on client side?

我遵循了本指南: 如何使用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可能變得不必要,並且使事情變得更復雜,此外,將所有代碼導出為單個打字稿文件可能會使事情復雜化。

我建議以下構建過程:

  1. 編譯所有打字稿代碼,並導出到臨時目錄(例如.tmp
  2. 使用webpack處理.tmp中的.js文件,並指定main入口點。

對於這樣的事情,開始使用gulp之類的構建系統可能是個好主意,而不是使用運行構建項目所需的單獨命令。 您還可以使用package.json"scripts"屬性來編寫構建命令,這樣您就不必手動運行許多不同的命令。

我最后聽了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'
        })
    ]
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM