在使用 Typescript 和 Webpack 的项目中,我想强制将通常的全局库(例如 jQuery)视为 UMD 全局变量。
现在,如果我在引用 $
的文件中省略 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/
我想它的用途非常符合您的用例。
关于javascript - Webpack + Typescript - 如何将导入的非 UMD 模块隔离到一个文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44349393/