无法使用 TypeScript 解析 'jquery'
我在项目中将 TypeScript 与 jQuery 集成时遇到了问题。我使用 npm 安装了 @types/jquery 和 jquery,但无法在我的 .ts 文件中使用。我尝试使用以下方式导入:
import jquery from "jquery";
import * as $ from "jquery";
import jquery = require("jquery");
const jquery = require("jquery");
import jquery = require("@types/jquery");
这些导入在编译时显示错误:
Module not found: Error: Can't resolve 'jquery'
我的 webpack 配置:
module.exports = {
entry: './src/App.ts',
plugins: [
new CleanWebpackPlugin(['dist']),
new HtmlWebpackPlugin({
title: 'DQuiz'
})
],
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
},
{ test: /\.hbs$/, loader: "handlebars-loader" }
]
},
resolve: {
mainFields: ['browserify'],
extensions: ['.tsx', '.ts', '.js']
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
答案#1
我在另一台安装了 Ubuntu 的机器上测试构建我的项目。我得到相同的错误:
Module not found: Error: Can't resolve 'jquery'
通过一些搜索,我找到了一个解决方案。对于 Jquery 3.x,你需要使用 'jquery/src/jquery' 导入模块。
我使用了 Tan Duong 建议的带有提供插件的解决方案,我认为这个解决方案对于 jQuery 来说更优雅,然后要导入,你可以使用:
const webpack = require('webpack');
module.exports = {
plugins: [
new webpack.ProvidePlugin({
$: 'jquery/src/jquery',
jquery: 'jquery/src/jquery'
})
]
}
谢谢大家的回答 :)
答案#2
试试
plugins: [
new CleanWebpackPlugin(['dist']),
new HtmlWebpackPlugin({
title: 'DQuiz'
}),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery'
})
],
或者你可以按照这里的结构
