2

在使用 Typescript 和 Webpack 的项目中,我想强制将通常的全局库(例如 jQuery)视为 UMD 全局变量。

现在,如果我import * as $ from 'jQuery'在我引用的文件中省略$,webpack 会成功,但脚本在运行时会失败。但是,import * as _ from 'lodash'在省略时会导致 webpack 构建失败,从而具有预期的行为。

考虑以下文件:

第一个.ts

import * as $ from "jquery";
import * as _ from "lodash";

import { second } from "./second";

$(() => {
    const message = _.identity("first.ts");
    $(".first").html(message);
    second.Test();
});

第二个.ts

//import * as $ from "jquery";
//import * as _ from "lodash";

export const second = {
    Test: () => {
        const message = _.identity("second.ts");
        $(".second").html(message);
    }
}

索引.html

<html>
    <head>
        <script type="text/javascript" src="./bundle.js">
        </script>
    </head>
<body>
<div class="first"></div>
<div class="second"></div>
</body>
</html>

包.json

{
  "name": "webpack-typescript-test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@types/jquery": "^2.0.46",
    "@types/lodash": "^4.14.65",
    "jquery": "^3.2.1",
    "lodash": "^4.17.4",
    "ts-loader": "^2.1.0",
    "typescript": "^2.3.3",
    "webpack": "^2.6.1"
  }
}

tsconfig.json

{
    "compilerOptions": {
        "target": "ES5",
        "sourceMap": true,
        "module": "commonjs",
        "types": []
    },
    "include": [
        "./*.ts"
    ],
    "exclude": [
        "./node_modules"
    ]
}

webpack.config.js

const path = require('path');

module.exports = {
    entry: './first.ts',
    resolve: {
        extensions: ['.webpack.js', '.web.js', '.ts', '.tsx', '.js']
    },
    module: {
        loaders: [
            {
                test: /\.ts$/,
                loader: 'ts-loader',
                exclude: /node_modules/
            }
        ]
    },
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname)
    }
}

有没有办法可以在所有 .ts 文件中强制执行导入语句?

4

1 回答 1

1

考虑externals在 webpack 配置中使用选项: https ://webpack.js.org/configuration/externals/

我想它的用途非常适合您的用例。

于 2017-06-09T13:04:31.707 回答