简体   繁体   中英

Can't resolve 'jquery' with typescript

I have a problem to integrate typescript with jquery in my project. I install both @types/jquery and jquery using npm, but I can't use in my .ts. I try to import with:

import jquery from "jquery";
import * as $ from "jquery";
import jquery = require("jquery");
const jquery = require("jquery");
import jquery = require("@types/jquery");

These imports show error in compile time:

Module not found: Error: Can't resolve 'jquery'

My webpack config:

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')
  }
};

Try it

plugins: [
    new CleanWebpackPlugin(['dist']),
    new HtmlWebpackPlugin({
      title: 'DQuiz'
    }),
    new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery',
        'window.jQuery': 'jquery'
    })
],

or you can follow structure in here

I tested build my project in another machine with ubuntu. I get same error:

Module not found: Error: Can't resolve 'jquery'

With some searchs I found a solution. For Jquery 3.x, you need to import module with 'jquery/src/jquery' .

I use the solution suggested by Tan Duong with provide plugin, I think this solution is more elegant for jquery, then to import, you can use:

const webpack = require('webpack');
module.exports = {
    plugins: [
        new webpack.ProvidePlugin({
            $: 'jquery/src/jquery',
            jquery: 'jquery/src/jquery'
        })
    ]
}

Thank you all for answers :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM