0
votes

I'm new in reactjs and webpack. I want to load a library from CDN in my project using webpack external, like sample in https://webpack.js.org/configuration/externals/#externals but it doesn't work. can you help me?

It's my index.html

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<link rel="stylesheet" href="https://cdn.cdncode.com/twitter-    bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.cdncode.com/bootstrap-rtl/3.2.0-rc2/css/bootstrap-rtl.min.css"/>
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
</head>
<body class="content_main">
<div id="root"></div>
<script type="text/javascript" src="https://cdn.cdncode.com/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.cdncode.com/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript" src="https://cdn.cdncode.com/html5shiv/r29/html5.min.js"></script>
<script type="text/javascript" src="https://cdn.cdncode.com/respond.js/1.4.2/respond.min.js"></script>
        </script>
</body>
</html>

and it's my webpack.config.js

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

module.exports = {
entry: "./src/index.js",
output: {
    path: "/js/",
    publicPath: 'http://jwplayer.k-cdn.net/',
    filename: "bundle.js"
},
module: {
    loaders: [
        {test: /\.js$/, loader: 'babel-loader', query: {presets: ['es2015', 'react']}},
        {test: /\.css$/, loader: 'style-loader!css-loader'},
        {test: /\.(png|svg|jpg|gif)$/, loader: 'file-loader'},
        {test: /\.(woff|woff2|eot|ttf|otf)$/, loader: 'file-loader'}
    ]
},
resolve: {
    extensions: ['.js']
},
externals: {
    jquery: 'jQuery'
}
};
1
what error are you getting? - Piyush Dhamecha
i'm using import $ from 'jquery'; in one of my components and i get this error Module not found: Can't resolve 'jquery' in 'C:\Users\PC-R-Nematollahi\Desktop\livez-react\src\components\channels' - Rana Nematollahi

1 Answers

0
votes

To execute $ function of JQuery into React, i did following steps.

1) Install JQuery from npm

npm install --save jquery

2) Changes in webpack.config.js, Remove external, add plugins

module.exports = {
entry: "./src/index.js",
output: {
    path: "/js/",
    publicPath: 'http://jwplayer.k-cdn.net/',
    filename: "bundle.js"
},
module: {
    loaders: [
        {test: /\.js$/, loader: 'babel-loader', query: {presets: ['es2015', 'react']}},
        {test: /\.css$/, loader: 'style-loader!css-loader'},
        {test: /\.(png|svg|jpg|gif)$/, loader: 'file-loader'},
        {test: /\.(woff|woff2|eot|ttf|otf)$/, loader: 'file-loader'}
    ]
},
resolve: {
    extensions: ['.js']
},
plugins: [
    new webpack.ProvidePlugin({
        $: "jquery",
    }),
]
};

Now we can use $ in React