WebPack TypeScript-如何将导入的非UMD模块隔离到一个文件



在使用Typescript和WebPack的项目中,我想强制执行通常将全局库(例如jQuery(视为UMD Globals。

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

考虑以下文件:

first.ts

import * as $ from "jquery";
import * as _ from "lodash";
import { second } from "./second";
$(() => {
    const message = _.identity("first.ts");
    $(".first").html(message);
    second.Test();
});

second.ts

//import * as $ from "jquery";
//import * as _ from "lodash";
export const second = {
    Test: () => {
        const message = _.identity("second.ts");
        $(".second").html(message);
    }
}

index.html

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

package.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文件中执行导入语句?

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

我想它的目的与您的用例相匹配。

最新更新