Webpack add owl.carousel - javascript

webpack.config.js:
const path = require('path');
const glob = require('glob');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin;
const CleanWebpackPlugin = require('clean-webpack-plugin');
const PurifyCSSPlugin = require('purifycss-webpack');
module.exports = function (env) {
return {
devServer: {
inline: true
},
resolve: {
extensions: ['.html', '.css', '.js', '.json'],
modules: ['node_modules'],
},
devtool: 'source-map',
context: __dirname,
entry: {
landing: [
'./js/landing.js'
]
},
output: {
path: path.resolve(__dirname, './app/'),
filename: '[name].js',
chunkFilename: '[id].js',
pathinfo: true,
sourceMapFilename: '[file].map'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['es2015'],
plugins: ['transform-runtime']
}
}
},
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader']
})
},
{
test: /\.html$/,
use: 'html-loader'
},
{
test: /\.(eot|woff|ttf|svg|png|jpg)$/,
use: 'url-loader?limit=50000&name=assets/[name]-[hash].[ext]'
}
]
},
plugins: [
new CleanWebpackPlugin(['app']),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
_: 'lodash',
jPlayer: 'jplayer'
}),
new ExtractTextPlugin({
filename: (getPath) => {
return getPath('css/[name].css');
},
allChunks: true
}),
new HtmlWebpackPlugin({
filename: 'index.html',
chunks: ['landing', 'bundle'],
favicon: './img/favicon.png',
template: './pages/index.html',
inject: true
}),
new HtmlWebpackPlugin({
filename: 'terms.html',
chunks: ['terms', 'bundle'],
favicon: './img/favicon.png',
template: './pages/terms.html',
inject: true
}),
new CommonsChunkPlugin('bundle')
]
};
};
landing.js:
import $ from '../node_modules/jquery';
window.$ = $;
window.jQuery = $;
jQuery = $;
import '../node_modules/owl.carousel';
I used the command: webpack --env=prod --config=webpack.config.js
After running the command I open the page /app/index.html in the browser
But the error on the page:
Uncaught TypeError: Cannot read property 'fn' of undefined
at owl.carousel.js:1658
1658: $.fn.owlCarousel = function(option) {

Related

Is there a way to generate a single JS file using Webpack instead of main.bundle.css and main.bundle.js?

Currently, my yarn build script generates 2 files, main.[hash].js and main.[hash].css. Is there any way that I can bundle even my css file to the main.[hash].js so that I only have one js file?
Here are my config files:
webpack.common.js
const webpack = require('webpack');
module.exports = {
entry: {
main: './src/index.js',
vendor: './src/vendor.js',
},
module: {
rules: [
{
test: /\.html$/,
use: ['html-loader'],
},
{
test: /\.(svg|png|jpg|gif)$/,
use: {
loader: 'file-loader',
options: {
name: '[name].[hash].[ext]',
outputPath: 'imgs',
},
},
},
{
enforce: 'pre',
test: /\.js$/,
exclude: /node_modules/,
loader: 'eslint-loader',
options: {
cache: true,
emitWarning: true,
failOnError: true,
},
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
},
],
},
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.$': 'jquery',
'window.jQuery': 'jquery',
}),
],
};
webpack.dev.js
const path = require('path');
const merge = require('webpack-merge');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const common = require('./webpack.common');
module.exports = merge(common, {
mode: 'development',
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
},
plugins: [
new HtmlWebpackPlugin({
template: './src/template.html',
}),
],
module: {
rules: [
{
test: /\.scss$/,
use: ['style-loader', 'css-loader', 'sass-loader'],
},
],
},
});
webpack.prod.js
const path = require('path');
const merge = require('webpack-merge');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const common = require('./webpack.common');
module.exports = merge(common, {
mode: 'production',
output: {
filename: '[name].[contentHash].bundle.js',
path: path.resolve(__dirname, 'dist'),
},
optimization: {
minimizer: [
new OptimizeCssAssetsPlugin(),
new TerserPlugin(),
new HtmlWebpackPlugin({
template: './src/template.html',
minify: {
removeAttributeQuotes: true,
collapseWhitespace: true,
removeComments: true,
},
}),
],
},
plugins: [
new MiniCssExtractPlugin({filename: '[name].[contentHash].css'}),
new CleanWebpackPlugin(),
],
module: {
rules: [
{
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader, // 3. Extract css into files
'css-loader', // 2. Turns css into commonjs
'sass-loader', // 1. Turns sass into css
],
},
],
},
});
I have also tried adding some plugins to achieve this but had not had any luck so far.
If there is a plugin or some other way that you have, please help me with it.

adding directory with webpack

I decided to give webpack a shot and am using a starter kit for a small project. I'm not sure where I am going wrong but I want to add a new directory of files and access them like any other build.In this case it is the folder "particles.js-master". When I add a directory I cannot seem to access anything in the folder. I'm assuming I have to add an output or the like to the webpack config? Any advice would be greatly appreciated, thanks :)
here is my project structure
webpack:
const path = require('path');
const webpack = require('webpack');
const HtmlWebPackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const PreloadWebpackPlugin = require('preload-webpack-plugin');
const CssUrlRelativePlugin = require('css-url-relative-plugin');
const glob = require('glob');
const IS_DEV = process.env.NODE_ENV === 'dev';
const config = {
mode: IS_DEV ? 'development' : 'production',
devtool: IS_DEV ? 'eval' : 'source-map',
entry: './src/js/index.js',
output: {
filename: 'js/[name].[hash].js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
},
{
test: /\.scss$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
hmr: IS_DEV,
},
},
'css-loader',
'sass-loader',
],
},
{
test: /\.(gif|png|jpe?g|svg)$/i,
use: [
{
loader: 'url-loader',
options: {
limit: 8192,
name: '[name].[ext]',
fallback: 'file-loader',
outputPath: 'public/images',
},
},
{
loader: 'image-webpack-loader',
options: {
mozjpeg: {
progressive: true,
quality: 65,
},
pngquant: {
quality: '65-90',
speed: 4,
},
gifsicle: {
interlaced: false,
},
webp: {
quality: 75,
},
},
},
],
},
],
},
plugins: [
new CleanWebpackPlugin(),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'windows.jQuery': 'jquery',
}),
new CopyWebpackPlugin([
{
from: './src/public',
to: 'public',
},
]),
new MiniCssExtractPlugin({
filename: IS_DEV ? 'css/[name].css' : 'css/[name].[contenthash].css',
chunkFilename: 'css/[id].css',
}),
new webpack.HashedModuleIdsPlugin(),
new PreloadWebpackPlugin({
include: 'initial',
}),
new CssUrlRelativePlugin(),
],
devServer: {
contentBase: path.join(__dirname, 'src'),
},
optimization: {
runtimeChunk: 'single',
splitChunks: {
cacheGroups: {
vendor: {
test: /node_modules/,
chunks: 'initial',
name: 'vendor',
priority: 10,
enforce: true,
},
},
},
minimizer: [],
},
};
if (!IS_DEV) {
const TerserPlugin = require('terser-webpack-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
config.optimization.minimizer.push(
new TerserPlugin(),
new OptimizeCSSAssetsPlugin({})
);
}
const files = glob.sync('./src/*.html');
files.forEach(file => {
config.plugins.push(
new HtmlWebPackPlugin({
filename: path.basename(file),
template: file,
favicon: path.resolve(__dirname, './src/public/icon.ico'),
minify: !IS_DEV,
})
);
});
module.exports = config;

Webpack: not producing expected bundles

Well, as the title says, webpack is not producing what I expect.
Here's my config:
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const extractPlugin = new ExtractTextPlugin({
filename: 'main.css',
});
process.env.NODE_ENV = 'production';
module.exports = {
entry: {
main: './src/main.js',
algo: './src/algo.js',
},
entry: './src/main.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js',
},
module: {
rules: [
{
test: /\.js$/,
use: [
{
loader: 'babel-loader',
options: {
presets: ['es2015'],
}
}
],
},
{
test: /\.scss$/,
use: extractPlugin.extract({
use: [
'css-loader',
'sass-loader',
]
})
},
{
test: /\.html$/,
use: ['html-loader']
},
{
test: /\.php$/,
use: [
{
loader: 'file-loader',
options: {
name: '[path][name].[ext]',
outputPath: '/'
}
}
]
},
{
test: /\.(jpg|png|gif|jpeg)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[path][name].[ext]',
outputPath: 'images/',
}
}
]
}
],
},
resolve: {
alias: {
vue: 'vue/dist/vue.min'
}
},
plugins: [
extractPlugin,
new HtmlWebpackPlugin({
template: 'src/index.html',
filename: 'index.html',
chunks: ['main'],
}),
new HtmlWebpackPlugin({
template: 'src/algo.html',
filename: 'algo.html',
chunks: ['algo']
}),
new CleanWebpackPlugin([
'dist',
]),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
Vue: 'vue',
}),
new CopyWebpackPlugin([
{
from: 'src/*.php',
to: '[name].[ext]',
test: /\.php$/
}
]),
],
mode: 'production',
};
Both main.js and algo.js are simply a set of #import 'something's (Please let me know if this a good practice in the comment).
I want to insert the resulting bundles, main.js and algo.js to go into
index.html and algo.html, respectively.
However, so far it's been only producing main.js for index.html so far.
Previously, the output was as follows:
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js',
},
However, that didn't work either.
Can someone help me achieve the desired outcome?
You've specified entry twice in your configuration:
entry: {
main: './src/main.js',
algo: './src/algo.js',
},
entry: './src/main.js',
The second entry here is overwriting the first, which means you've only configured ./src/main.js.

Can't load templates with routeprovider when using webpack

I recentley migrated from grunt to webpack and I can't figure how to require/import my templates. I have looked at several similar issues with no luck.
Here is my webpack.config file:
var webpack = require('webpack');
var globby = require('globby');
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var CleanWebpackPlugin = require('clean-webpack-plugin');
var AssetsPlugin = require('assets-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: {
app: globby.sync(['./app/app.js','./app/app.run.js', './app/app.config.js', './app/**/*.js']),
styles: globby.sync(['./content/styles/*.css']),
images: globby.sync(['./content/images/*.*']),
vendor: [
// removed to save space
]
},
output: {
filename: './scripts/[name].bundle.js',
path: path.join(__dirname, "public")
},
devServer: {
port: 1384,
contentBase: './public/'
},
// Enable sourcemaps for debugging webpack's output.
devtool: 'source-map',
module: {
rules: [
{ test: /\.less$/,
loader: "less-loader",
include: path.resolve(__dirname, "content", "styles", "less")
},
{
test: /\.html$/,
use: [
{
loader: 'ngtemplate-loader',
options: {
angular: true,
},
},
{
loader: 'raw-loader',
},
{
loader: 'html-loader'
},
{
loader: "ngtemplate!html?module=myTemplates&relativeTo=" +
(path.resolve(__dirname, './app/**'))
},
],
/*
exclude: [/node_modules/]
*/
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract({ fallback: 'style-loader', use: 'css-loader' }),
},
{
test: /\.(ico)$/,
loader: "url-loader?name=./[name].[ext]",
include: path.resolve(__dirname, "content", "images")
},
{
test: /\.(jpg|jpeg|gif|png|tiff|svg)$/,
loader: "file-loader?name=./images/[name].[ext]",
include: path.resolve(__dirname, "content", "images")
},
{
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url-loader?minetype=application/font-woff&name=./fonts/[name].[ext]'
},
{
test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'file-loader?name=./fonts/[name].[ext]'
},
{
test: require.resolve('adal-angular/lib/adal'),
loader: 'expose-loader?AuthenticationContext'
},
{
test: /\.js$/,
enforce: "pre",
loader: 'source-map-loader'
}
],
},
plugins: [
new webpack.DefinePlugin({
ADMIN_API_URL: JSON.stringify('http://localhost:41118/api/'),
API_URL: JSON.stringify('http://localhost:32605/api/'),
GLOBAL_ADMIN_URL: JSON.stringify('https://adminapi.tradesolution.no/')
}),
new HtmlWebpackPlugin({
template: './app/layout.ejs',
filename: 'index.html'
}),
new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', filename: './scripts/vendor.bundle.js' }),
new ExtractTextPlugin({ filename: './styles/[name].bundle.css' }),
/*new CleanWebpackPlugin(['public'], {
verbose: false
}),
*/
new AssetsPlugin({
filename: 'webpack.assets.json',
path: './public/scripts',
prettyPrint: true
}),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
'window.$': 'jquery',
"window.AuthenticationContext": "AuthenticationContext",
_: 'underscore'
}),
],
externals: [
{ xmlhttprequest: '{XMLHttpRequest:XMLHttpRequest}' }
],
}
The public folder builds as it should with .js, styles, images etc. But simple navigation results in this error:
ERROR in ./app/app.config.js
Module not found: Error: Can't resolve 'app/varegruppe/templates/index.html' in 'C:\Users\oystein\work\EPD.SPA\EpdSPA\app'
# ./app/app.config.js 50:25-71
Here is an example of how the routes are defined:
$routeProvider.when('/produkteier', {
templateUrl: require('app/produkteier/templates/view.html')
})
Using this plugin I managed to copy all the html files in to the public directory, with the following config:
var CopyWebpackPlugin = require('copy-webpack-plugin');
new CopyWebpackPlugin([
{from: './app/**/*.html', to: './'}
])

Webpack aliases do not work

I set resolve.alias in webpack.config.js
alias: {
'$': 'jquery',
'_': 'underscore'
}
and require modules in my javascript file like this.
var $ = require('$');
var _ = require('_');
then there comes an error
Module not found: Error: Cannot resolve module '$'
I try to display error details and I find out that it still try to looking for modules named $ or _, not jquery or underscore.
So why doesn't the alias config work? Do I set a wrong config?
webpack.config.js
var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var config = require('../config');
var projectRoot = path.resolve(__dirname, '../');
var buildPath = path.resolve(__dirname, 'demo');
module.exports = {
// eval-source-map is faster for development
devtool: '#eval-source-map',
entry: {
miceui: ['webpack-dev-server/client?http://localhost:3000',
'webpack/hot/dev-server',
path.resolve(projectRoot, 'index')]
},
output: {
path: buildPath,
filename: '[name].js'
},
plugins: [
new webpack.DefinePlugin({
'process.env': config.dev.env
}),
new ExtractTextPlugin('[name].css'),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: true
})
],
module: {
loaders: [
{ test: /\.htm(l?)$/, loader: 'html-loader' },
{ test: /\.css$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader') },
{ test: /\.css$/, loader: 'style-loader!css-loader' },
{ test: /\.(png|jpg|gif)$/, loader: 'url-loader?limit=8192' }
]
},
resolve: {
extensions: ['', '.js', '.jsx', '.coffee', '.html', '.css', '.scss'],
alias: {
'$': 'jquery',
'_': 'underscore'
}
}
};

Categories