我在我的项目中将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')
}
};
答案 0 :(得分:2)
我测试了用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'
})
]
}
谢谢大家的答案:)
答案 1 :(得分:1)
试试吧
plugins: [
new CleanWebpackPlugin(['dist']),
new HtmlWebpackPlugin({
title: 'DQuiz'
}),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery'
})
],
或者您可以按照here
中的结构进行操作