2

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')
  }
};
2
  • I have created simple project, installed @types/jquery, and TypeScript has compiled well without any import. Also, it works well with import * as $ from 'jquery'. Is your issue webpack specific? Commented Mar 29, 2018 at 5:05
  • I think is webpack specific. The problem maybe is when webpack bundle application in a unique .js file. Commented Mar 29, 2018 at 17:29

2 Answers 2

4

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 :)

Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

I continue to get the same problem when run webpack: Module not found: Error: Can't resolve 'jquery'. I will try to execute my project in another machine to test this.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.