jquery - Angular 2 + Typescript + jQuery + webpack : $ not defined

标签 jquery angular typescript webpack

正如标题所说,我正在使用 typescript、jquery 和 webpack 开发一个 Angular 2 应用程序(用于分离 js 和 css 文件)。

从 Controller 中,当我需要访问 jquery ($) 时,我必须始终导入它,如下所示:

var $: JQueryStatic = require('jquery');

位于每个需要 jQuery 函数的 Controller 的顶部。

有关更多信息,这是我的 webpack.config 文件:

const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const merge = require('webpack-merge');

module.exports = (env) => {
    const extractCSS = new ExtractTextPlugin('vendor.css');
    const isDevBuild = !(env && env.prod);
    const sharedConfig = {
        stats: { modules: false },
        resolve: { extensions: ['.js'] },
        module: {
            rules: [
                { test: /\.(png|woff|woff2|eot|ttf|svg)(\?|$)/, use: 'url-loader?limit=100000' },
                { test: /jquery-mousewheel/, loader: "imports-loader?define=>false&this=>window" },
                { test: /malihu-custom-scrollbar-plugin/, loader: "imports-loader?define=>false&this=>window" }
            ]
        },
        entry: {
            vendor: [
                '@angular/common',
                '@angular/compiler',
                '@angular/core',
                '@angular/flex-layout',
                '@angular/http',
                '@angular/material',
                '@angular/platform-browser',
                '@angular/platform-browser-dynamic',
                '@angular/router',
                '@angular/platform-server',
                'angular2-universal',
                'angular2-universal-polyfills',
                'bootstrap',
                //'bootstrap/dist/css/bootstrap.css',
                'es6-shim',
                'es6-promise',
                'font-awesome/css/font-awesome.css',
                'event-source-polyfill',
                'hammerjs',
                'jquery',
                'jquery-mousewheel',
                'malihu-custom-scrollbar-plugin',
                'malihu-custom-scrollbar-plugin/jquery.mCustomScrollbar.css',
                'swiper',
                'swiper/dist/css/swiper.css',
                'zone.js',
            ]
        },
        output: {
            publicPath: '/dist/',       // Specifies the public URL address of the output files when referenced in a browser
            filename: '[name].js',      // Specifies the name of each output file on disk
            library: '[name]_[hash]'    // Export the bundle as library with that name
        },
        plugins: [
            new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', jquery: 'jquery', Hammer: "hammerjs/hammer" }), // Maps these identifiers to the jQuery package (because Bootstrap expects it to be a global variable)
            new webpack.ContextReplacementPlugin(/\@angular\b.*\b(bundles|linker)/, path.join(__dirname, './ClientApp')), // Workaround for https://github.com/angular/angular/issues/11580
            new webpack.IgnorePlugin(/^vertx$/) // Workaround for https://github.com/stefanpenner/es6-promise/issues/100
        ]
    };

    const clientBundleConfig = merge(sharedConfig, {
        output: { path: path.join(__dirname, 'wwwroot', 'dist') },
        module: {
            rules: [
                { test: /\.css(\?|$)/, use: extractCSS.extract({ use: 'css-loader' }) }
            ]
        },
        plugins: [
            extractCSS,
            new webpack.DllPlugin({
                path: path.join(__dirname, 'wwwroot', 'dist', '[name]-manifest.json'),
                name: '[name]_[hash]'
            })
        ].concat(isDevBuild ? [] : [
            new webpack.optimize.UglifyJsPlugin()
        ])
    });

    const serverBundleConfig = merge(sharedConfig, {
        target: 'node',
        resolve: { mainFields: ['main'] },
        output: {
            path: path.join(__dirname, 'ClientApp', 'dist'),
            libraryTarget: 'commonjs2',
        },
        module: {
            rules: [{ test: /\.css(\?|$)/, use: ['to-string-loader', 'css-loader'] }]
        },
        entry: { vendor: ['aspnet-prerendering'] },
        plugins: [
            new webpack.DllPlugin({
                path: path.join(__dirname, 'ClientApp', 'dist', '[name]-manifest.json'),
                name: '[name]_[hash]'
            })
        ]
    });

    return [clientBundleConfig, serverBundleConfig];
}

有没有办法不必每次都进行该声明?

提前致谢

最佳答案

是的,如果您以这种方式更新 webpack.config.js 中的插件,您可以做到这一点:

plugins: [
    new webpack.ProvidePlugin({
      jQuery: 'jquery',
      $: 'jquery',
      jquery: 'jquery'
    })
  ]

在安装必要的依赖项之前不要忘记:

npm install jquery --save
npm install @types/jquery --save-dev

关于jquery - Angular 2 + Typescript + jQuery + webpack : $ not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42394377/

相关文章:

jquery - 可滚动容器内的粘性 header

javascript - 如何使用 jquery 调整 html 表的行和列的大小?

php - 我想在使用 JavaScript 和 PHP 键入时向用户建议一些数据。这怎么可能?

html - Angular 如何在 html 中显示数组中的单个对象

javascript - 如何在打字时实时应用验证 [Typescript]

javascript - 等待 ajax 请求完成

angular - 如何在 angular2 GA 中使用 Http 提供程序?

ios - 拒绝连接数据:text/html;charset=utf8 in iOS Safari

typescript - 键入所有可能的字符串以使用accessibilityRole?

Angular/rxjs : Why don't I have to import toPromise anymore?