【问题标题】:import owl.carousel from webpack从 webpack 导入 o​​wl.carousel
【发布时间】:2017-03-21 20:52:14
【问题描述】:

我是 F2​​E 世界的新手。 我刚刚使用 create-react-app 创建了一个 Web 应用程序。 (https://github.com/facebookincubator/create-react-app)

我想将owl.carousel导入到我的项目中,所以我按照NPM的指导(https://www.npmjs.com/package/owl.carousel),语法是:

import $ from 'jquery';
import 'imports?jQuery=jquery!owl.carousel';

但调试器控制台显示错误:

Unexpected '!' in 'imports?jQuery=jquery!owl.carousel'. Do not use      import syntax to configure webpack loaders import/no-webpack-loader-syntax

我尝试了另一种语法:

import owlCarousel from 'owl.carousel' 

错误是:

Uncaught TypeError: Cannot read property 'fn' of undefined

有人能帮我弄清楚发生了什么吗?谢谢。

更新:我的 webpack 加载器设置:

loaders: [
  // Process JS with Babel.
  {
    test: /\.(js|jsx)$/,
    include: paths.appSrc,
    loader: 'babel-loader',
    query: {
      cacheDirectory: findCacheDir({
        name: 'react-scripts'
      })
    }
  },
  {
    test: /\.css$/,
    loader: 'style!css?importLoaders=1!postcss'
  },
  {
    test: /\.json$/,
    loader: 'json'
  },
  {
    test: /\.(ico|jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2)(\?.*)?$/,
    loader: 'file',
    query: {
      name: 'static/media/[name].[hash:8].[ext]'
    }
  },
  {
    test: /\.(mp4|webm|wav|mp3|m4a|aac|oga)(\?.*)?$/,
    loader: 'url',
    query: {
      limit: 10000,
      name: 'static/media/[name].[hash:8].[ext]'
    }
  }
]

我的组件代码:

import React, { Component } from 'react';
import './App.css';
import './css/style.css';
import './css/bootstrap.min.css';
import './css/owl.carousel.css';
import FruitSelector from './containers/fruit_Selector';
import FruitDetail  from './containers/fruit_Detail';
import $ from 'jquery';
import 'owl.carousel';

class App extends Component {
render() {
$(document).ready(function(){

  $(".content-slider").owlCarousel({
      slideSpeed: 350,
      singleItem: true,
      autoHeight: true,
      navigation: true,
      navigationText: ["<i class='fa fa-angle-left'></i>", "<i class='fa fa-angle-right'></i>"]
  });
});

return (
  <div className="App">
  <div className="row">
    <div className="col-sm-4 col-md-3 sidebar">
      <FruitSelector/>
    </div>
    <div className="col col-md-8">
        <FruitDetail/>
    </div>
    </div>
  </div>
);
}
}

export default App;

我的 webpack.config.dev.js 插件设置:

plugins: [

new InterpolateHtmlPlugin({
  PUBLIC_URL: publicUrl
}),

new HtmlWebpackPlugin({
  inject: true,
  template: paths.appHtml,
}),
new webpack.DefinePlugin(env),
new webpack.HotModuleReplacementPlugin(),
// Watcher doesn't work well if you mistype casing in a path so we use
// a plugin that prints an error when you attempt to do this.
// See https://github.com/facebookincubator/create-react-app/issues/240
new CaseSensitivePathsPlugin(),
// If you require a missing module and then `npm install` it, you still have
// to restart the development server for Webpack to discover it. This plugin
// makes the discovery automatic so you don't have to restart.
// See https://github.com/facebookincubator/create-react-app/issues/186
new WatchMissingNodeModulesPlugin(paths.appNodeModules),
new webpack.ProvidePlugin({
      $: "jquery",
      jQuery: "jquery",
      "window.jQuery": "jquery"
  })]

错误弹出:

App.js:71 Uncaught TypeError: (0 , _jquery2.default)(...).owlCarousel is not a function(…)

【问题讨论】:

    标签: jquery webpack carousel frontend


    【解决方案1】:

    删除阻止导入语法的插件

    问题在于 import 语法不是默认的 webpack 语法。你已经在你的项目中安装了https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-webpack-loader-syntax.md 来阻止它,确保它是 react-create-app 的一部分。请删除它以启用此语法。

    Owl.carousel 需要在其中导入 jQuery 库,因为它使用 $ 变量,所以这是个问题,这就是为什么必须删除 webpack-loader-syntax

    如果我们尝试以标准方式导入owl,那么jQuery 没有在那里定义(webpack 中的每个文件都有自己的范围),所以它会抛出错误:

    Uncaught TypeError: Cannot read property 'fn' of undefined
    

    (替代)使用匀场模块

    如果删除插件有问题,那么您可以尝试将 jQuery 添加到每个模块中,并将其用作 shimming 模块 - https://webpack.github.io/docs/shimming-modules.html

    在 webpack 配置中它看起来像:

    module.exports = {
      plugins: [
        new webpack.ProvidePlugin({
        $: "jquery",
        jQuery: "jquery",
        "window.jQuery": "jquery"
        })
    ]
    //other config vars
    };
    

    只需通过以下方式添加它:

    import 'owl.carousel'
    

    【讨论】:

    • 谢谢,但是如何在 owl 之前定义 jQuery 或 $?我已经安装了包 'imports-loader' 但仍然是同样的错误。
    • 检查我的更新答案问题是你安装了这个github.com/benmosher/eslint-plugin-import/blob/master/docs/… 并且它阻止了语法,所以标准的 webpack 可以工作,你的项目有插件来阻止它。
    • @AirNoir 使用匀场模块解决方案检查我编辑的答案
    • 在我使用 "window.jQuery" : "jquery" 设置 webpack.ProviderPlugin 后它可以工作,非常感谢! :)
    • 我遇到了新问题... owlCarousel 不是函数,似乎无法加载 owl.carousel 库。 :(
    【解决方案2】:
      new webpack.ProvidePlugin({
                $: path.resolve(path.join(__dirname, 'node_modules/jquery')),
                jQuery: path.resolve(path.join(__dirname, 'node_modules/jquery')),
                'window.jQuery': path.resolve(path.join(__dirname, 'node_modules/jquery')),
            }),
    

    它帮助了我

    因为轮播有自己的模块(node_modules/owl.carousel/node_modules/jquery),插件从那里获取 jQuery 并将轮播写入这个模块

    【讨论】:

    • 谢谢,它也帮助了我。我有new webpack.ProvidePlugin({'window.jQuery': 'jquery'});,但在我使用 path.resolve 之前它不起作用。
    【解决方案3】:
     dont import jquery as (import $ from 'jquery') as owl.carousel need jquery, instead in webpack.config file :
        const webpack = require("webpack");
        .....
        
        
        ----------
        
        module.exports={
        plugins: [
        new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery',
        'window.jQuery': 'jquery'
        }),
        ]
    }
        
        this works perfectly alright.
    

    【讨论】:

    • 此问题已包含多个答案和一个已接受的答案。您能否解释(通过编辑您的答案)您的答案与其他答案的不同之处?也知道从长远来看,仅代码的答案没有用处。
    【解决方案4】:

    我遇到了同样的错误“无法读取未定义的属性 'fn'”,但请确保首先使用 Jquery 引用,然后为我修复它。

    <!-- Webjar References -->
      <script src="webjars/jquery/3.3.1/jquery.min.js"></script>
      <script src="webjars/bootstrap/4.3.1/js/bootstrap.min.js"></script>
      <link href="webjars/bootstrap/4.3.1/css/bootstrap.min.css"
            rel="stylesheet">
    

    【讨论】:

      猜你喜欢
      • 2020-05-16
      • 2020-02-01
      • 2018-09-06
      • 2018-03-12
      • 2019-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多