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')
  }
};
Elton Serra
  • 497
  • 2
  • 5
  • 11
  • 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? – Pavel Mar 29 '18 at 05:05
  • I think is webpack specific. The problem maybe is when webpack bundle application in a unique .js file. – Elton Serra Mar 29 '18 at 17:29

2 Answers2

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

Elton Serra
  • 497
  • 2
  • 5
  • 11
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

Tan Duong
  • 2,124
  • 1
  • 11
  • 17
  • 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. – Elton Serra Mar 30 '18 at 04:19