How to load Highcharts using Webpack - javascript

I'm using Highcharts lib component of V5.0.10
highcharts.min.js
highcharts.more.min.js
highcharts.prototype-adapter.min.js
and I'm importing them in my lib.js which is entry point for webpack.config.js
require('../customLibs/highcharts/js/highcharts.min.js');
require('../customLibs/highcharts/js/highcharts.more.min.js');
require('../customLibs/highcharts/js/highcharts.prototype-adapter.min.js');
Here is my Webpack.config.js
var path = require('path');
var webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
var config = {
entry: [
'angular',
'./src/lib.js',
'./src/app.js'
],
output: {
path: path.join(__dirname, 'mcdist'),
filename: '[name].js',
},
module: {
rules: [{
test: /\.(jpe?g|png|gif|svg)$/i,
loader: 'file-loader?name=[name].[ext]&outputPath=images/',
}, {
test: /\.css|scss$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: ['css-loader', "sass-loader"]
})
}, {
test: /\.html$/,
exclude: [
path.join(__dirname, '/src/index.html')
],
use: [
{ loader: 'ngtemplate-loader?relativeTo=' + (path.resolve(__dirname, './src')) },
{ loader: 'html-loader' },
]
}],
},
plugins: [
new HtmlWebpackPlugin({
title: 'Demo',
minify: {
collapseWhitespace: true,
},
cache: true,
hash: true,
inject: true,
filename: './index.html',
template: 'src/index.html'
}),
new ExtractTextPlugin({
filename: "app.css",
disable: false,
allChunks: true
}),
new webpack.ProvidePlugin({
$: 'jquery',
jquery: 'jquery',
Holder: 'holderjs',
moment: 'moment',
loadash: 'loadash.min',
})
],
devServer: {
proxy: [{
context: [
'/mcdist/api',
'/mcdist/appConfig',
'/mcdist/logout',
'/mcaid/j_spring_security_logout'
],
target: 'http://localhost:8080',
secure: false
}],
port: 9000
},
};
module.exports = config;
but I'm getting 'ReferenceError: Highcharts is not defined' when JS file referring to Highcharts loads up.
Can you please suggest correct way to load Highcharts with Webpack and load them in application to use ?

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.

Webpack is creating test and snapshot bundles

I've recently tried to add proper code splitting for the first time to one of my projects.
It's worked, however I think it's worked a little TOO well!
When I run bundle-analyser, my dist folder contains a bunch of other bundles that contain snapshots and test files and I can't find any information that would explain why this is happening!
here is my webpack.config.base.js
const path = require('path');
const postcssNested = require('postcss-nested');
const postcssSimpleVars = require('postcss-simple-vars');
const postcssPresetEnv = require('postcss-preset-env');
const postcssImport = require('postcss-import');
const postcssFor = require('postcss-for');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractCssPluginConfig = new ExtractTextPlugin({
filename: '[name].[hash].css',
disable: false,
});
const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
template: './src/index.html',
filename: 'index.html',
inject: 'body',
});
module.exports = {
entry: {
main: './src/index.jsx',
},
output: {
path: path.resolve('_dist'),
chunkFilename: '[name].[hash].bundle.min.js',
filename: '[name].[hash].min.js',
publicPath: '/',
},
module: {
rules: [
{
test: /\.(js|jsx)?$/,
loader: 'babel-loader',
exclude: /node_modules\/(?!(dom7|ssr-window|swiper)\/).*/,
},
{
test: /\.css$/,
loader: 'style-loader',
},
{
test: /\.css$/,
loader: 'css-loader',
query: {
modules: true,
importLoaders: 1,
localIdentName: '[path]___[name]__[local]___[hash:base64:5]',
},
},
{
test: /\.css$/,
loader: 'postcss-loader',
options: {
plugins: () => [
postcssNested,
postcssImport,
postcssFor,
postcssPresetEnv({
browsers: '>1%',
autoprefixer: {
grid: true,
browsers: ['>1%'],
},
insertBefore: {
'all-property': postcssSimpleVars,
},
}),
],
},
},
{
test: /\.(png|jp(e*)g|svg)$/,
use: [{
loader: 'url-loader',
options: {
limit: 8000,
name: 'images/[hash]-[name].[ext]',
},
}],
},
{
test: /\.(woff|woff2|ttf|eot|otf)$/,
use: 'file-loader?name=fonts/[name].[ext]',
},
{
test: /\.(pdf)$/,
use: [{
loader: 'url-loader',
options: { limit: 8000, name: 'documents/[hash]-[name].[ext]' },
}],
},
],
},
resolve: {
extensions: ['.js', '.jsx', '.css', '.svg'],
modules: [path.resolve('./node_modules')],
alias: {
Pages: path.resolve(__dirname, 'src/pages/'),
Sections: path.resolve(__dirname, 'src/sections/'),
Components: path.resolve(__dirname, 'src/components/'),
Images: path.resolve(__dirname, 'src/images/'),
Downloads: path.resolve(__dirname, 'src/downloads/'),
Services: path.resolve(__dirname, 'src/services/'),
Enum: path.resolve(__dirname, 'src/enum/'),
Data: path.resolve(__dirname, 'src/data/'),
Utils: path.resolve(__dirname, 'src/utils/'),
Config: path.resolve(__dirname, 'src/config/'),
},
},
plugins: [
ExtractCssPluginConfig,
HtmlWebpackPluginConfig,
],
};
and here is my webpack.config.build.js
const webpack = require('webpack');
const merge = require('webpack-merge');
const WebpackCleanupPlugin = require('webpack-cleanup-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const baseConfig = require('./webpack.config.base');
const WebpackCleanupPluginConfig = new WebpackCleanupPlugin({
exclude: ['webpack.stats.json'],
quiet: true,
});
const CopyWebpackPluginConfig = new CopyWebpackPlugin([
{ from: './src/documents', to: './documents' },
]);
module.exports = () => {
const DefinePluginConfig = new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'production'),
});
return (
merge(baseConfig, {
optimization: {
runtimeChunk: 'single',
splitChunks: {
cacheGroups: {
commons: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'initial',
enforce: true,
},
},
},
noEmitOnErrors: true,
concatenateModules: true,
minimizer: [
new UglifyJsPlugin({
cache: true,
parallel: true,
sourceMap: false,
}),
],
},
plugins: [
DefinePluginConfig,
WebpackCleanupPluginConfig,
CopyWebpackPluginConfig,
],
})
);
};
I've tried adding a regex that matches any files with .test.js/jsx and .snap to my module.rules object but that did nothing.
Any help would be greatly appreciated!
If your test files are in a different directory, you might want to consider adding exclude property within the modules rules for js files.
Refer the following document: https://webpack.js.org/configuration/module/?_sm_au_=iVVKrMW7ZsbHQPbq#rule-exclude
or the following example: https://webpack.js.org/configuration/?_sm_au_=iVVKrMW7ZsbHQPbq#options
Another solution would be to use the IgnorePlugin. Docs for IgnorePlugin here: https://webpack.js.org/plugins/ignore-plugin/?_sm_au_=iVVKrMW7ZsbHQPbq

Pass JSON to pug template

I can't figure out how to access JSON data in my pug templates.
Here is my pug layout
title #{htmlWebpackPlugin.pages[page].title}
Pug page which is initializing page variable
block vars
- var page = "catalog"
Webpack part
new HtmlWebpackPlugin({
filename: 'catalog.html',
chunks: ['main'],
template: PATHS.source + '/views/pages/catalog.pug',
inject: true,
data: {
pages: require('./dev/util/options.json')
}
})
JSON
"pages": {
"catalog": {
"title": "Catalog",
"description": "",
"keywords": ""
}
}
Each page is a separate pug and json.
First, I declare the entry, in my case it is a separate js file entry.js
module.exports.html = {
     'index': 'index',
     'about': 'o-mnie',
     'contact': 'kontakt'
};
Webpack part
Include entry:
const entry = require('./entry.js');
Next add entry to HtmlWebpackPlugin:
const entryHtmlPlugins = Object.keys(entry.html).map(entryName => {
return new HtmlWebpackPlugin({
filename: `${entry.html[entryName]}.html`,
template: `./source/templates/containers/${entryName}/${entryName}.pug`,
chunks: [entryName],
file: require(`../source/templates/containers/${entryName}/${entryName}.json`)
})
});
See the full code how to use json data from pug and webpack -> github
const webpack = require("webpack");
const path = require('path');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const SimpleProgressWebpackPlugin = require('simple-progress-webpack-plugin');
const entry = require('./entry.js');
const entryHtmlPlugins = Object.keys(entry.html).map(entryName => {
return new HtmlWebpackPlugin({
filename: `${entry.html[entryName]}.html`,
template: `./source/templates/containers/${entryName}/${entryName}.pug`,
path: path.join(__dirname, "../dist/"),
chunks: [entryName],
// inject: true,
// cache: true,
file: require(`../source/templates/containers/${entryName}/${entryName}.json`),
mode: 'development'
})
});
const output = {
path: path.resolve(__dirname, "source"),
filename: "[name].[hash].js",
publicPath: "/"
}
const config = {
devtool: "eval-source-map",
mode: "development",
entry: entry.site,
output: output,
module: {
rules: [
{
// JS
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
}
},
{
// CSS | SCSS
test: /\.(css|scss)$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [{
loader: 'css-loader'
},
{
loader: 'postcss-loader',
options: {
plugins: () => [require('autoprefixer')({
'browsers': ['> 1%', 'last 2 versions']
})],
}
},
{
loader: 'sass-loader'
},
{
loader: 'sass-resources-loader', // style-resources-loader then we can use sass, less, stylus
options: {
resources: [
path.resolve(__dirname, '../source/scss/main.scss')
]
},
}
]
})
},
{
// IMAGES
test: /\.(jpe?g|png|gif|svg)$/i,
loader: "file-loader"
},
{
// PUG
test: /\.pug$/,
loader: 'pug-loader',
options: {
pretty: true,
self: true
}
}
],
},
plugins: [
new SimpleProgressWebpackPlugin({
format: 'compact'
}),
new ExtractTextPlugin({
filename: '[name].[hash].css',
// disable: false,
allChunks: true
}),
new webpack.DefinePlugin({
PRODUCTION: JSON.stringify(false)
}),
].concat(entryHtmlPlugins)
};
module.exports = config;

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 add owl.carousel

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) {

Categories