【问题标题】:Uncaught ReferenceError: $ is not defined Webpack and embedded scriptUncaught ReferenceError: $ is not defined Webpack and embedded script
【发布时间】:2018-05-13 00:17:48
【问题描述】:

我正在使用 webpack 创建一个 *.js 包

var path = require('path');
var webpack = require('webpack');

const ExtractTextPlugin = require("extract-text-webpack-plugin");

module.exports = {
    entry: {
        site: [
            './wwwroot/js/site.js',
            './node_modules/jquery/dist/jquery.js',
            './Scripts/jquery.global.js',
            './node_modules/jquery-validation/dist/jquery.validate.js',
            './node_modules/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js',
            './node_modules/popper.js/dist/popper.js',
            './node_modules/bootstrap/dist/js/bootstrap.js',
        ]
    },
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'wwwroot/dist/')
    },
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                loader: 'ts-loader',
                exclude: /node_modules/,
            },
            {
                test: /\.css$/,
                loader: ExtractTextPlugin.extract({
                    fallback: 'style-loader',
                    use: 'css-loader'
                })
            },
        ]
    },
    resolve: {
        extensions: [".tsx", ".ts", ".js", ".css"]
    },
    plugins: [
        new ExtractTextPlugin('../css/bundle.css'),
        new webpack.ProvidePlugin({
            $: "jquery",
            jQuery: "jquery",
            Popper: ['popper.js', 'default']
        })
    ]
};

然后在_Layout.cshtml我有以下代码:

 ...

    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; 2017 - MVC_Movie</p>
        </footer>
    </div>

    <environment include="Development">
        <script src="~/js/site.js" asp-append-version="true"></script>
        <script src="~/dist/bundle.js" asp-append-version="true"></script>
    </environment>
    <environment exclude="Development">
        <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"
                asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
                asp-fallback-test="window.jQuery"
                crossorigin="anonymous"
                integrity="">
        </script>
        <script src="http://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/bootstrap.min.js"
                asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
                asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
                crossorigin="anonymous"
                integrity="">
        </script>
        <script src="~/js/site.min.js" asp-append-version="true"></script>
    </environment>

    @RenderSection("Scripts", required: false)

    <script>
        $(document).ready(function () {
            debugger;
            //Ask ASP.NET what culture we prefer, because we stuck it in a meta tag
            var data = $("meta[name='accept-language']").attr("content")
            //Tell jQuery to figure it out also on the client side.
            $.global.preferCulture(data);
            //Tell the validator, for example,
            // that we want numbers parsed a certain way!
            $.validator.methods.number = function (value, element) {
                if ($.global.parseFloat(value)) {
                    return true;
                }
                return false;
            }
        });
    </script>
</body>
</html>

到目前为止,我在生成 bundle.js 文件时没有遇到任何错误,看起来不错,但 _Layout.cshtml 底部的部分引发了异常

未捕获的引用错误:$ 未定义

我认为通过在 webpack.config.js 插件部分定义符号 $ 将被识别:

plugins: [
        new ExtractTextPlugin('../css/bundle.css'),
        new webpack.ProvidePlugin({
            $: "jquery",
            jQuery: "jquery",
            Popper: ['popper.js', 'default']
        })
    ]

知道如何让它工作吗?

【问题讨论】:

    标签: javascript jquery asp.net webpack webpack-2


    【解决方案1】:

    在 JS Bundle 之前附加 jquery.js 文件

    【讨论】:

    • 如果你检查我的代码,你会看到 jquery.js 文件被添加到包中。
    • 它发生捆绑加载所有 JS 文件作为一个,所以其他文件使用 "$" 这就是 $ 未定义的原因
    【解决方案2】:

    根据here 的长时间讨论,您似乎需要使用别名为$jQuery 来解析jquery 模块,而不是将其定义为插件。

    这里是 webpack 的配置:

     resolve : {
        alias: {
            jquery: "./vendor/jquery/jquery.js",
        }
    },
    

    WebPack 文档page

    【讨论】:

    • 其实在使用插件的时候,bundle的生成是没有错误的。我曾尝试使用别名,但没有帮助。 stackoverflow.com/questions/28969861/… 尝试在此处实现选项也没有用。
    • 你是说你得到了同样的别名错误?
    • 是的,我得到了同样的未定义错误。我找到了使用暴露加载器的解决方案。我会发布答案,以防其他解决方案更适合它。
    【解决方案3】:

    一个似乎可行的解决方案是将 jQuery 模块暴露在 webpack 包之外。

    module: {
        rules: [
            {
                test: /\.tsx?$/,
                loader: 'ts-loader',
                exclude: /node_modules/,
            },
            {
                test: /\.css$/,
                loader: ExtractTextPlugin.extract({
                    fallback: 'style-loader',
                    use: 'css-loader'
                })
            },
            {
                // Exposes jQuery for use outside Webpack build
                test: require.resolve('jquery'),
                use: [{
                    loader: 'expose-loader',
                    options: 'jQuery'
                }, {
                    loader: 'expose-loader',
                    options: '$'
                }]
            }
        ]
    },
    

    在这里找到解决方案:Managing jQuery plugin dependency in webpack@harlemsquirrel

    【讨论】:

      猜你喜欢
      • 2020-05-10
      • 1970-01-01
      • 1970-01-01
      • 2018-08-03
      • 1970-01-01
      • 2020-03-25
      • 2019-01-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多