How configure webpack optimization options in VUE - vue.js

I have developed a VUE SPA that employs Vuetify as UI.
The starting project was scaffolded using vue-cli and selecting all standard options.
My current vue.config.js file is as follow:
const path = require("path");
const webpack = require("webpack");
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer")
.BundleAnalyzerPlugin;
module.exports = {
publicPath: process.env.NODE_ENV == "production" ? "/" : "/",
css: {
sourceMap: true
},
devServer: {
headers: {
"Access-Control-Allow-Origin": "*",
https: true
}
},
productionSourceMap: false,
transpileDependencies: [
"vuetify",
"vue2-dropzone",
"vue-echarts",
"resize-detector"
],
configureWebpack: {
devtool: "source-map",
resolve: {
alias: {
//Api: path.resolve(__dirname, "src/api/"),
Components: path.resolve(__dirname, "src/components/"),
Constants: path.resolve(__dirname, "src/constants/"),
Container: path.resolve(__dirname, "src/container/"),
Views: path.resolve(__dirname, "src/views/"),
Helpers: path.resolve(__dirname, "src/helpers/"),
Themes: path.resolve(__dirname, "src/themes/")
//moment: "moment/src/moment"
},
extensions: ["*", ".js", ".vue", ".json"]
},
plugins: [
//jquery plugin
new webpack.ProvidePlugin({
$: "jquery",
jquery: "jquery",
"window.jQuery": "jquery",
jQuery: "jquery"
}),
new BundleAnalyzerPlugin(),
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
],
optimization: {
splitChunks: {
chunks: "all"
// minSize: 10000,
// maxSize: 200000
}
}
}
};
I would like to add webpack optimization for minifying css/sass, images, js code, woff2 font files (served locally and not from CDN), I suppose that this is not done automatically, am I wrong?
Could you share a basic configuration to achieve what described above (being able to debug code in development)?

Related

Uncaught ReferenceError: exports is not defined when using React-Native web

I am trying to use React-Native web to convert an existing React Native App to Web App.
The App is getting compiled successfully now, but the page appears blank and I get the following error on checking console.
It is working fine when we don't use the project files and make a simple screen with react native elements like View, Text etc.
rnw_blogpost.bundle.js:31234 Uncaught ReferenceError: exports is not defined
at eval (extends.js:2)
at Module../node_modules/react-redux/node_modules/#babel/runtime/helpers/esm/extends.js (rnw_blogpost.bundle.js:30586)
at __webpack_require__ (rnw_blogpost.bundle.js:31231)
at fn (rnw_blogpost.bundle.js:31457)
at eval (connectAdvanced.js:1)
at Object../node_modules/react-redux/es/components/connectAdvanced.js (rnw_blogpost.bundle.js:17465)
at __webpack_require__ (rnw_blogpost.bundle.js:31231)
at fn (rnw_blogpost.bundle.js:31457)
at eval (index.js:1)
at Object../node_modules/react-redux/es/index.js (rnw_blogpost.bundle.js:17585)
Here is my webpack.config.js
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const appDirectory = path.resolve(__dirname);
const {
presets
} = require(`${appDirectory}/babel.config.js`);
const compileNodeModules = [
// Node Modues come here!
].map((moduleName) => path.resolve(appDirectory, `node_modules/${moduleName}`));
const babelLoaderConfiguration = {
test: /\.js$/,
// Add every directory that needs to be compiled by Babel during the build.
include: [
path.resolve(__dirname, 'node_modules/react-native-uncompiled'),
path.resolve(__dirname, 'index.web.js'), // Entry to your application
path.resolve(__dirname, 'App.web.js'), // Change this to your main App file
path.resolve(__dirname, 'src'),
...compileNodeModules,
],
use: {
loader: 'babel-loader',
options: {
cacheDirectory: true,
// The 'metro-react-native-babel-preset' preset is recommended to match React Native's packager
presets: ['module:metro-react-native-babel-preset'],
// Re-write paths to import only the modules needed by the app
plugins: ['react-native-web']
}
}
};
const svgLoaderConfiguration = {
test: /\.svg$/,
use: [{
loader: '#svgr/webpack',
}, ],
};
const imageLoaderConfiguration = {
test: /\.(gif|jpe?g|png)$/,
use: {
loader: 'url-loader',
options: {
name: '[name].[ext]',
},
},
};
module.exports = {
entry: {
app: path.join(__dirname, 'index.web.js'),
},
output: {
path: path.resolve(appDirectory, 'dist'),
publicPath: '/',
filename: 'rnw_blogpost.bundle.js',
libraryTarget: 'umd'
},
resolve: {
extensions: ['.web.tsx', '.web.ts', '.tsx', '.ts', '.web.js', '.js'],
alias: {
'react-native$': 'react-native-web',
App: path.resolve("src"),
},
},
module: {
rules: [
babelLoaderConfiguration,
imageLoaderConfiguration,
svgLoaderConfiguration,
],
},
plugins: [
new HtmlWebpackPlugin({
template: path.join(__dirname, 'index.html'),
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.DefinePlugin({
// See: https://github.com/necolas/react-native-web/issues/349
__DEV__: JSON.stringify(true),
}),
],
target: ['node'],
};
& here is the code of my babel.config.js
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
};

You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file using Webpack 5.40.0

I am building web version from existing React Native project using react-native-web.
webpack.config.js
const path = require('path');
const webpack = require('webpack'); const HtmlWebpackPlugin =
require('html-webpack-plugin');
const appDirectory = path.resolve(__dirname); const {presets} =
require(`${appDirectory}/babel.config.js`);
const compileNodeModules = [ // Add every react-native package that
needs compiling // 'react-native-gesture-handler', ].map(moduleName
=> path.resolve(appDirectory, `node_modules/${moduleName}`));
const babelLoaderConfiguration = { test: /\.js$|(tsx|jsx)?$/, //
Add every directory that needs to be compiled by Babel during the
build. include: [
path.resolve(__dirname, 'index.web.js'), // Entry to your application
path.resolve(__dirname, 'App.web.tsx'), // Change this to your main App file
path.resolve(__dirname, 'src'),
...compileNodeModules, ], use: {
loader: 'babel-loader',
options: {
cacheDirectory: true,
presets,
plugins: ['react-native-web'],
}, }, };
const svgLoaderConfiguration = { test: /\.svg$/, use: [
{
loader: '#svgr/webpack',
}, ], };
const imageLoaderConfiguration = { test: /\.(gif|jpe?g|png)$/,
use: {
loader: 'url-loader',
options: {
name: '[name].[ext]',
}, }, };
module.exports = { entry: {
app: path.join(__dirname, 'index.web.js'), }, output: {
path: path.resolve(appDirectory, 'dist'),
publicPath: '/',
filename: 'fictionate.me.bundle.js', }, resolve: {
extensions: ['.web.tsx', '.web.ts', '.tsx', '.ts', '.web.js', '.js'],
alias: {
'react-native$': 'react-native-web',
}, }, module: {
rules: [
babelLoaderConfiguration,
imageLoaderConfiguration,
svgLoaderConfiguration,
], }, plugins: [
new HtmlWebpackPlugin({
template: path.join(__dirname, 'index.html'),
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.DefinePlugin({
// See: https://github.com/necolas/react-native-web/issues/349
__DEV__: JSON.stringify(true),
}), ], };
babel.config.js
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
};
When I am trying to build web, it failed with following issue.
enter image description here
Please help me if someone knows how to fix this issue.

index.html disappears after watch triggered recompilation

I have a Chrome Extension where I started using webpack. I can build it just fine, but in development mode when I am run npm run watch after the first recompilation is triggered the index.html disappears from the build directory.
Here is script part of my package.json:
"build": "node utils/build.js",
"watch": "webpack --watch & webpack-dev-server --inline --progress --colors"
}
My webpack.config.js: (I have a bunch of content scripts listed as separate entry point as well that I omitted)
path = require("path"),
env = require("./utils/env"),
CleanWebpackPlugin = require("clean-webpack-plugin").CleanWebpackPlugin,
CopyWebpackPlugin = require("copy-webpack-plugin"),
HtmlWebpackPlugin = require("html-webpack-plugin"),
WriteFilePlugin = require("write-file-webpack-plugin"),
MiniCssExtractPlugin = require('mini-css-extract-plugin');
const fileExtensions = ["jpg", "jpeg", "png", "gif", "eot", "otf", "svg", "ttf", "woff", "woff2"];
const options = {
mode: process.env.NODE_ENV || "development",
entry: {
// the single js bundle used by the single page that is used for the popup, options and bookmarks
index: path.join(__dirname, "src", "", "index.js"),
// background scripts
"js/backgroundScripts/background": path.join(__dirname, "src", "js/backgroundScripts", "background.js"),
"js/backgroundScripts/messaging": path.join(__dirname, "src", "js/backgroundScripts", "messaging.js")
},
output: {
publicPath: '',
path: path.join(__dirname, "build"),
filename: "[name].bundle.js"
},
module: {
rules: [
{
enforce: "pre",
test: /\.js$/,
exclude: /node_modules/,
loader: "eslint-loader",
options: {
cache: true,
emitWarning: true
},
},
{
test: /\.(sa|sc|c)ss$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
hmr: true,
},
},
'css-loader',
'sass-loader',
],
},
{
test: new RegExp('\.(' + fileExtensions.join('|') + ')$'),
loader: "file-loader?name=[name].[ext]",
exclude: /node_modules/
},
{
test: /\.html$/,
loader: "html-loader",
exclude: /node_modules/
},
{
test: /\.(js|jsx)$/,
loader: "babel-loader",
exclude: /node_modules/
},
]
},
resolve: {
modules: [path.resolve(__dirname, './src'), 'node_modules'],
extensions: fileExtensions.map(extension => ("." + extension)).concat([".jsx", ".js", ".css"])
},
plugins: [
// clean the build folder
new CleanWebpackPlugin(),
// expose and write the allowed env vars on the compiled bundle
new webpack.EnvironmentPlugin({
NODE_ENV: 'development', // use 'development' unless process.env.NODE_ENV is defined
DEBUG: false
}),
// copies assets that don't need bundling
new CopyWebpackPlugin([
"src/manifest.json",
{
from: "src/css",
to: 'css/'
},
{
from: "src/_locales",
to: '_locales/'
},
{
from: "src/images",
to: 'images/'
}
], { copyUnmodified: true }),
new HtmlWebpackPlugin({
template: path.join(__dirname, "src", "index.html"),
filename: "index.html",
chunks: ["index"]
}),
new WriteFilePlugin(),
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: '[name].css',
chunkFilename: '[id].css',
}),
],
devServer: {
writeToDisk: true,
contentBase: path.join(__dirname, "../build")
}
};
if (env.NODE_ENV === "development") {
options.devtool = "cheap-module-source-map";
}
module.exports = options;
I can see index.html listed in the initial build log, but not any of the ones after that.
I would appreciate any clues of why this is is happening and how I could fix it. Thanks.
In the plugins section, you should put this line conditional only for production environment:
new CleanWebpackPlugin()
As it's role is to clean the build folder.

Vue SFC styles not being extracted in webpack production build

Trying to add vue (and SFCs) to my webpack app. The <template> and <script> blocks work fine, but for some reason the styles in the <style> block are not being extracted for production build.
In the dev build, it's extracting the .vue <style> block to a separate css file (named for the entrypoint). Which is OK but I'd prefer they went into my main stylesheet.
But no matter what I try, I can't get any .vue styles to show up (in any file) for the production build.
This is an abbreviated version of my webpack config:
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const VueLoaderPlugin = require("vue-loader/lib/plugin");
...
module.exports = (env) => {
return {
entry: {
app: ["./src/polyfills.js", "./src/scss/styles.scss", "./src/app.js"],
...
testview: "./src/js/views/TestView.js"
},
output: {
path: assets,
filename: "[name].[hash].js",
publicPath: "/static/"
},
resolve: {
modules: ["node_modules", "src"],
alias: {
vue$: "vue/dist/vue.esm.js"
},
extensions: ["*", ".js", ".vue"]
},
module: {
rules: [
{
test: /\.vue$/,
loader: "vue-loader"
},
{
test: /\.js?$/,
exclude: /node_modules/,
use: [
{
loader: "babel-loader",
options: {
presets: [
[
"#babel/preset-env",
{
targets: {
browsers: ["> 1%", "last 2 versions", "ie >= 11"]
}
}
]
],
plugins: ["#babel/plugin-proposal-class-properties"],
code: true,
comments: true,
cacheDirectory: true,
babelrc: false
}
}
]
},
{
test: /\.s?[ac]ss$/,
use: [
"vue-style-loader",
MiniCssExtractPlugin.loader,
{
loader: "css-loader",
options: {
sourceMap: ifNotProduction()
}
},
{
loader: "postcss-loader",
options: {
ident: "postcss",
sourceMap: ifNotProduction(),
plugins: () =>
ifProduction([
require("autoprefixer")({
preset: "default"
}),
require("cssnano"),
require("css-mqpacker")
])
}
},
{
loader: "sass-loader",
options: {
sourceMap: ifNotProduction()
}
}
]
}
]
},
optimization: {
splitChunks: {
cacheGroups: {
commons: {
name: "commons",
chunks: "initial",
minChunks: 2,
minSize: 0
},
styles: {
name: "styles",
test: /\.css$/,
chunks: "all",
enforce: true
}
}
},
occurrenceOrder: true
},
plugins: [
new VueLoaderPlugin(),
new MiniCssExtractPlugin({
filename: "style.[hash].css"
}),
new HtmlWebpackPlugin({
hash: true,
inject: false,
template: "./src/jinja-templates/base.html.j2",
filename: `${templates}/base.html.j2`,
})
]
};
};
The .vue file I'm using is this demo one. I'm trying to import it into the entrypoint called 'testview' which contains simply:
import Vue from "vue";
import MainContent from "../components/main-content";
let MainComponent = Vue.extend(MainContent);
new MainComponent().$mount("#mainContent");
Did figure it out. I had to remove sideEffects: false from my package.json. This issue explains it further.
Still would like to know how to extract the .vue styles to my main stylesheet As it is now, the .vue styles are extracting to a separate stylesheet (dev and production).

Deploy vuejs application for relative path

I'm trying to deploy my vuejs application on relative path. I also add the homepage url in the package.json file but it doesn't work for me. How can i do that. Here are the some extra detail which might be easily understandable for you guy's. You can check this details and let me know if its understandable or not i'll try to add some more details.
Server- Apache
Url- "http://example.cpm/subpath/"
webpack.config.js
const path = require('path');
const fs = require('fs');
const webpack = require('webpack');
// plugins
const HtmlWebPackPlugin = require("html-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const CleanWebpackPlugin = require('clean-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin');
// the path(s) that should be cleaned
let pathsToClean = [
'dist'
]
// the clean options to use
let cleanOptions = {
root: __dirname,
verbose: false, // Write logs to console.
dry: false
}
// Webpack uses `publicPath` to determine where the app is being served from.
// In development, we always serve from the root. This makes config easier.
const publicPath = '/';
// Make sure any symlinks in the project folder are resolved:
const appDirectory = fs.realpathSync(process.cwd());
const resolveApp = relativePath => path.resolve(appDirectory, relativePath);
function resolve(dir) {
return path.join(__dirname, '..', dir)
}
module.exports = {
entry: ["babel-polyfill", "./src/index.js"],
output: {
// The build folder.
path: resolveApp('dist'),
// Generated JS file names (with nested folders).
// There will be one main bundle, and one file per asynchronous chunk.
// We don't currently advertise code splitting but Webpack supports it.
filename: 'static/js/[name].[chunkhash:8].js',
chunkFilename: 'static/js/[name].[chunkhash:8].chunk.js',
// We inferred the "public path" (such as / or /my-project) from homepage.
publicPath: publicPath
},
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js',
Api: path.resolve(__dirname, 'src/api/'),
Components: path.resolve(__dirname, 'src/components/'),
Constants: path.resolve(__dirname, 'src/constants/'),
Container: path.resolve(__dirname, 'src/container/'),
Views: path.resolve(__dirname, 'src/views/'),
Helpers: path.resolve(__dirname, 'src/helpers/'),
Themes: path.resolve(__dirname, 'src/themes/')
},
extensions: ['*', '.js', '.vue', '.json']
},
devServer: {
contentBase: false,
compress: true,
port: 8080, // port number
historyApiFallback: true,
quiet: true
},
module: {
rules: [
{
test: /\.(js|vue)$/,
loader: 'eslint-loader',
enforce: 'pre',
include: [resolve('src')],
options: {
formatter: require('eslint-friendly-formatter')
}
},
{
test: /\.vue$/,
loader: 'vue-loader'
},
{
test: /\.js$/,
loader: 'babel-loader',
include: [resolve('src'), resolve('test')]
},
{
test: /\.html$/,
use: [
{
loader: "html-loader",
options: { minimize: true }
}
]
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: 'static/img/[name].[hash:7].[ext]'
}
},
{
test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: 'media/[name].[hash:7].[ext]'
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: 'media/fonts/[name].[hash:7].[ext]'
}
},
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, "css-loader"]
},
{
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
"css-loader",
"sass-loader"
]
}
]
},
optimization: {
minimizer: [
// we specify a custom UglifyJsPlugin here to get source maps in production
new UglifyJsPlugin({
cache: true,
parallel: true,
uglifyOptions: {
compress: false,
ecma: 6,
mangle: true
},
sourceMap: true
})
]
},
plugins: [
new FriendlyErrorsWebpackPlugin({
compilationSuccessInfo: {
messages: ['You application is running here http://localhost:8080']
}
}),
new CleanWebpackPlugin(pathsToClean, cleanOptions),
new HtmlWebPackPlugin({
template: "./index.html",
filename: "./index.html",
favicon: './static/favicon.png'
}),
new CopyWebpackPlugin([{
from: 'static',
to: 'static'
}]),
new MiniCssExtractPlugin({
filename: "static/css/[name].[contenthash:8].css",
chunkFilename: "static/css/[name].[contenthash:8].css"
}),
//jquery plugin
new webpack.ProvidePlugin({
$: 'jquery',
jquery: 'jquery',
'window.jQuery': 'jquery',
jQuery: 'jquery'
})
]
}
// Webpack uses publicPath to determine where the app is being served from.
// In development, we always serve from the root. This makes config easier.
const publicPath = '/';
Did you try changing the path to './' ?