Yarn run watch/dev not picking up changes - vue.js

I have a scenario where by im trying to make changes to Vue files and yarn run watch/dev has stopped working and tracking any changes made.
Im running a docker environment and any changes made after a successful yarn run dev are not being shown and also any changes made to my vue files are not triggering a rebuild in yarn run watch.
I have even tried yarn run watch-poll and that has also had no success.
Ill attached my webpack file and package.json
{
"private": true,
"scripts": {
"docs:dev": "vuepress dev docs",
"docs:build": "vuepress build docs",
"dev": "npm run development",
"development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
"watch": "npm run development -- --watch",
"watch-poll": "npm run watch -- --watch-poll",
"hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
"prod": "npm run production",
"production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
"cover": "cross-env NODE_ENV=coverage nyc --reporter=lcov --reporter=text npm run test:cover",
"test": "cross-env NODE_ENV=test mocha-webpack --webpack-config=node_modules/laravel-mix/setup/webpack.config.js --require tests/unit/setup.js --recursive --glob \"*.spec.js\" 'tests/unit'",
"test:cover": "mocha-webpack --webpack-config=node_modules/laravel-mix/setup/webpack.config.js --require tests/unit/setup.js --recursive --glob \"*.spec.js\" 'tests/unit' -- --compilers js:babel/register ",
"test:single": "cross-env NODE_ENV=test mocha-webpack --webpack-config=node_modules/laravel-mix/setup/webpack.config.js --require tests/unit/setup.js ",
"e2e": "cypress run",
"e2e-open": "cypress open"
},
"devD
Webpack file:
const mix = require('laravel-mix');
require('laravel-mix-purgecss');
let webpack = require('webpack');
const replace = require('replace-in-file');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
var isCoverage = process.env.NODE_ENV === 'coverage';
mix.webpackConfig({
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'#image': __dirname + '/resources/images/',
'#svg': __dirname + '/resources/images/svgs',
'#theme': __dirname + '/resources/images/svgs/' + process.env.THEME_NAME,
},
},
});
const { GenerateSW } = require('workbox-webpack-plugin');
mix.extend('gmShared', webpackConfig => {
const { rules } = webpackConfig.module;
rules
.filter(rule => rule.exclude && rule.exclude.toString() === '/(node_modules|bower_components)/')
.forEach(rule => (rule.exclude = /node_modules\/(?!(greenmotion-shared)\/).*/));
});
const plugins = [];
// plugins.push(new BundleAnalyzerPlugin);
plugins.push(
new webpack.DefinePlugin({
API_BASE_URL: JSON.stringify(process.env.API_BASE_URL),
AUTH_URL: JSON.stringify(process.env.AUTH_URL),
RDPS_BASE_URL: JSON.stringify(process.env.RDPS_BASE_URL),
HOOYU_REDIRECT_URL: JSON.stringify(process.env.HOOYU_REDIRECT_URL),
BUGSNAG_KEY: JSON.stringify(process.env.BUGSNAG_KEY),
ALGOLIA_APP_ID: JSON.stringify(process.env.ALGOLIA_APP_ID),
ALGOLIA_READ_KEY: JSON.stringify(process.env.ALGOLIA_READ_KEY),
ALGOLIA_PREFIX: JSON.stringify(process.env.ALGOLIA_PREFIX),
ROUTER_MODE: JSON.stringify(process.env.ROUTER_MODE),
STRIPE_PUBLIC_KEY: JSON.stringify(process.env.STRIPE_PUBLIC_KEY),
DEV_MODE: JSON.stringify(process.env.DEV_MODE || false),
IS_DEMO_MODE: JSON.stringify(process.env.IS_DEMO_MODE || false),
ENABLE_DEMO_SHORTCUTS: process.env.ENABLE_DEMO_SHORTCUTS || false,
ANALYTICS_URCHIN: JSON.stringify(process.env.ANALYTICS_URCHIN),
MINIMUM_APP_VERSION: JSON.stringify(process.env.MINIMUM_APP_VERSION),
SOURCE_ID: JSON.stringify(process.env.SOURCE_ID) || 1,
PUSHER_KEY: JSON.stringify(process.env.PUSHER_KEY),
PUSHER_AUTH_URL: JSON.stringify(process.env.PUSHER_AUTH_URL),
SUPPORT_TELEPHONE: JSON.stringify(process.env.SUPPORT_TELEPHONE),
SUPPORT_TELEPHONE_LABEL: JSON.stringify(process.env.SUPPORT_TELEPHONE_LABEL),
SUPPORT_EMAIL: JSON.stringify(process.env.SUPPORT_EMAIL),
})
);
plugins.push(new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/));
if (!['test', 'coverage'].includes(process.env.NODE_ENV)) {
plugins.push(
new webpack.optimize.CommonsChunkPlugin({
names: ['common'],
filename: 'js/[name].js',
minChunks: function (module, count) {
// Extract the libs in node_modules
return false;
},
})
);
plugins.push(
new webpack.optimize.CommonsChunkPlugin({
names: ['common'],
filename: 'js/[name].js',
minChunks: function (module, count) {
// Extract the libs in node_modules
return (
(module.context && module.context.includes('node_modules')) ||
(module.resource && module.resource.includes('bootstrap.js')) ||
count > 3
);
},
})
);
plugins.push(
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest',
filename: 'js/[name].js',
chunks: 'infinity',
})
);
}
plugins.push(
new GenerateSW({
swDest: 'sw.js',
// skipWaiting: true,
importsDirectory: 'sw-assets',
runtimeCaching: [
{
urlPattern: '/',
handler: 'networkFirst',
},
{
urlPattern: '/bookings',
handler: 'networkFirst',
},
{
urlPattern: '/profile',
handler: 'networkFirst',
},
{
urlPattern: '/search',
handler: 'networkFirst',
},
{
urlPattern: '/login',
handler: 'networkFirst',
},
{
urlPattern: new RegExp('.*.js'),
handler: 'networkFirst',
},
{
urlPattern: new RegExp('.*.css'),
handler: 'staleWhileRevalidate',
},
{
urlPattern: new RegExp('.*.svg'),
handler: 'staleWhileRevalidate',
},
{
urlPattern: new RegExp('^https://api.staging.greenmotion.com/api/user'),
handler: 'networkFirst',
options: {
cacheName: 'api-cache',
cacheableResponse: {
statuses: [0, 200],
},
},
},
],
})
);
Mix.listen('configReady', function (config) {
const rules = config.module.rules;
const targetRegex = /(\.(png|jpe?g|gif)$|^((?!font).)*\.svg$)/;
for (let rule of rules) {
if (rule.test.toString() == targetRegex.toString()) {
rule.exclude = /\.svg$/;
break;
}
}
});
let webpackRules = [
{
test: /\.svg$/,
use: [
{
loader: 'html-loader',
options: {
minimize: true,
},
},
],
},
];;
if (isCoverage) {
webpackRules = webpackRules.concat(
{
test: /\.(js|ts)/,
include: path.resolve('resources/js'), // instrument only testing sources with Istanbul, after ts-loader runs
loader: 'istanbul-instrumenter-loader',
query: {
esModules: true
},
exclude: [
/node_modules/,
/tests/
],
},
{
test: /\.m?js$/,
include: path.resolve('resources/js'),
exclude: [
/node_modules/,
/tests/
],
use: {
loader: 'babel-loader',
options: {
presets: [
['es2015', { targets: "defaults" }]
],
plugins: [
"syntax-dynamic-import",
"transform-class-properties",
"transform-object-rest-spread"
],
}
}
}
);
}
mix.webpackConfig({
devtool: 'source-map',
output: {
publicPath: '',
},
plugins: plugins,
module: {
rules: webpackRules,
},
});
mix.setPublicPath('public')
.gmShared()
.copy('resources/webroot/', 'public/')
.copy('resources/images/', 'public/images/')
.copy('resources/font/', 'public/font/')
.js('resources/js/app.js', 'public/js/')
.sass('resources/sass/app.scss', 'public/css/');
if (!['test', 'coverage'].includes(process.env.NODE_ENV)) {
mix.version()
.copy('resources/html/index.html', 'public/')
.then(stats => {
let manifest = require('./public/mix-manifest.json');
let from = [];
let to = [];
Object.keys(manifest).forEach(key => {
from.push(key);
to.push(manifest[key]);
});
let changes = replace.sync({
files: 'public/index.html',
from: from,
to: to,
});
let missedFiles = replace.sync({
files: 'public/index.html',
from: /{{mix\('(.*)'\)}}/gim,
to: '$1',
});
})
.browserSync({
server: './public',
proxy: null,
notify: false,
open: false,
})
.sourceMaps();
} else {
mix.copy('resources/html/index.html', 'public/')
.then(stats => {
let manifest = require('./public/mix-manifest.json');
let from = [];
let to = [];
Object.keys(manifest).forEach(key => {
from.push(key);
to.push(manifest[key]);
});
let changes = replace.sync({
files: 'public/index.html',
from: from,
to: to,
});
let missedFiles = replace.sync({
files: 'public/index.html',
from: /{{mix\('(.*)'\)}}/gim,
to: '$1',
});
})
.browserSync({
server: './public',
proxy: null,
notify: false,
open: false,
})
.sourceMaps();
}

Related

Webpack optimise and compress CSS and Javascript based on production mode inside webpack.config.js

I have the following NPM scripts inside package.json:
"scripts": {
"start": "cross-env NODE_ENV=development webpack --mode development",
"build": "cross-env NODE_ENV=production webpack --mode production"
},
if I run npm run build (production mode) I want to add optimization (see below) to compress my CSS and Uglify the Javascript. How do I achieve that?
optimization: {
minimizer: [new TerserJSPlugin({}), new OptimizeCSSAssetsPlugin({})],
},
if I run npm start I want to watch the files and further the same as production mode except optimization. I am building a Drupal site so I need to build the assets also in development.
My webpack.config.js looks like this now:
const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CopyPlugin = require('copy-webpack-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const webpack = require('webpack');
const autoprefixer = require('autoprefixer');
const config = {
entry: {
main: "./src/index.js",
courses: "./src/courses.js",
vendor: "./src/vendor.js"
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
},
plugins: [
new MiniCssExtractPlugin({ filename: '[name].css' }),
new CopyPlugin([
{ from: './src/assets/images', to: 'assets/images' },
{ from: './src/assets/icons', to: 'assets/icons' }
]),
],
module: {
rules: [
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
{ loader: 'css-loader', options: { importLoaders: 1 } },
'postcss-loader',
]
},
{
test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
use: {
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: './assets/fonts',
},
},
}
]
}
};
module.exports = (env, argv) => {
if (argv.mode === 'development') {
//...
}
if (argv.mode === 'production') {
//...
}
return config;
};
How do I build this in?
I fix it by adjusting webpack.config.js like below:
const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CopyPlugin = require('copy-webpack-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const webpack = require('webpack');
const autoprefixer = require('autoprefixer');
const config = {
//Entry Point
entry: {
main: "./src/index.js",
courses: "./src/courses.js",
vendor: "./src/vendor.js"
},
//Output
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
},
//Watch
watch: false,
watchOptions: {
ignored: ['node_modules']
},
//Loader
module: {
rules: [
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
{ loader: 'css-loader', options: { importLoaders: 1 } },
'postcss-loader',
]
},
{
//For fonts
test: /\.(woff|woff2|ttf|otf|eot)$/,
use: [
{
//using file-loader too
loader: "file-loader",
options: {
outputPath: "fonts"
}
}
]
}
]
},
//plugin
plugins: [
new MiniCssExtractPlugin({ filename: '[name].css' }),
new CopyPlugin([
{ from: './src/assets/images', to: 'assets/images' },
{ from: './src/assets/icons', to: 'assets/icons' }
]),
],
};
module.exports = (env, argv) => {
if (argv.mode === 'development') {
//...
config.mode = "development";
config.watch = true;
}
if (argv.mode === 'production') {
//...
config.mode = "production";
config.optimization = {
splitChunks: {
chunks: "all"
},
minimize: true,
minimizer: [
new OptimizeCssAssetsPlugin(),
new TerserPlugin({
cache: true
})
]
};
}
return config;
};
If anybody have improvements on above, please let me know.

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.

webpack run build but not exit command

Webpack successfully run build, but can't auto exit command after. How to exit?
remove --progress and webpack-dashboard,still can't
webpack.base.conf.js
...// require
module.exports = {
mode: process.env.NODE_ENV,
entry: {
app: './src/main.js',
},
output: {
path: util.resolve('dist'),
filename: 'js/[name].[hash].js',
chunkFilename: 'js/[id].[chunkhash].js',
},
module: {
rules: [
...util.eslint,
...util.cssLoaders,
// more loaders
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: path.resolve(__dirname, '../public/index.html'),
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true,
},
}),
new DllLinkPlugin({
htmlMode: true,
config: require('./webpack.dll.conf.js'),
}),
],
stats: {
children: false,
builtAt: true,
cached: true,
cachedAssets: true
}
};
webpack.prod.conf.js
// requere...
const config = require('./webpack.base.conf');
const env = require('../env.production')
module.exports = merge(config, {
bail: true,
watch:false,
devtool: 'cheap-module-source-map',
plugins: [
// ... mini css html
new CompressionWebpackPlugin({
filename: '[path].gz[query]',
algorithm: 'gzip',
test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'),
threshold: 10240,
minRatio: 0.8
})
],
optimization: {
... options
}
});
package.json
"build": "cross-env NODE_ENV=production webpack --progress --config build/webpack.prod.conf.js",
link run this
npm run build
i expect exit command after Successfully build ,not like this image
add this to your webpack.base.conf.js
plugins: [
// your plugins...
{
apply: (compiler) => {
compiler.hooks.done.tap('DonePlugin', (stats) => {
console.log('Compile is done !')
setTimeout(() => {
process.exit(0)
})
});
}
}
]
This use webpack's compiler hooks,
https://webpack.js.org/api/compiler-hooks/#done

Configure Vue to have a development and a production build

I inherited a Vue project that only builds production builds and uglifies everything. It doesn't have a webpack.config.js like I'm used to, it only has a vue.config.js file. When I do npm run build it builds a production. The build command is "build": "vue-cli-service build" and I don't see a way to do something like --mode=development.
I tried adding a webpack.config.js file which built, but at the same time broke the webpage, because it no longer built the same.
Here is my vue.config.js file:
const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = {
lintOnSave: true,
baseUrl: 'http://localhost:8080',
configureWebpack: {
entry: './src/main.js',
module: {
rules: [
{
test: /libs\.js$/,
use: {
loader: 'script-loader'
}
},
{
test: /angLibs\.js$/,
use: {
loader: 'script-loader'
}
},
{
test: /welcome\.js$/,
use: {
loader: 'script-loader'
}
},
{
test: /app\.js$/,
use: {
loader: 'script-loader'
}
}
]
},
output: {
publicPath: process.env.VUE_APP_ROOT_API + '/',
chunkFilename: '[name].bundle.js'
},
plugins: [
new CopyWebpackPlugin([
{ from: path.resolve(__dirname, './static/App/i18n/*.*'), to: path.resolve(__dirname, './dist/'), force: true }
], { copyUnmodified: true, context: 'static/' }),
new CopyWebpackPlugin([
{ from: path.resolve(__dirname, './static/Content/*/*.*'), to: path.resolve(__dirname, './dist/'), force: true }
], { copyUnmodified: true, context: 'static/' }),
new CopyWebpackPlugin([
{ from: path.resolve(__dirname, './static/fonts/*.*'), to: path.resolve(__dirname, './dist/'), force: true }
], { copyUnmodified: true, context: 'static/' }),
new CopyWebpackPlugin([
{ from: path.resolve(__dirname, './static/react/*.*'), to: path.resolve(__dirname, './dist/'), force: true }
], { copyUnmodified: true, context: 'static/' })
]
}
};
I would like to have a development build that is quicker and is not uglified/minified (or retains the map files of files it includes in the webpack).
That's a Vue CLI v3 build. For a webpack dev-server with hot-reload, use npm run serve.
Otherwise, you can build in development mode via
npx vue-cli-service build --mode development
or, if you don't have npx
./node_modules/.bin/vue-cli-service build --mode development
See https://cli.vuejs.org/guide/mode-and-env.html
Another option is to add a new script to package.json, eg
"buildDev": "vue-cli-service build --mode development"
and run
npm run buildDev
For configuring Webpack, see https://cli.vuejs.org/guide/webpack.html.
For example
// vue.config.js
module.exports = {
configureWebpack: {
// config goes here
}
}

NODE_ENV is undefined in express

So I am just getting started in learning webpack(2.2.1) and react and I am encountering a bit of a problem with NODE_ENV. I set it in package.json like so:
"scripts": {
"start": "set NODE_ENV=production&& webpack",
"test": "echo \"Error: no test specified\" && exit 1"
}
Then I put a console.log(process.env.NODE_ENV) into the entry file for webpack to see if it set and it does as expected.
However when I go to run express in a file called server.js in the project's root directory:
const express = require('express');
const path = require('path');
const app = new express;
console.log(process.env.NODE_ENV);
const port = process.env.PORT || 3000;
app.use(express.static('public'));
app.get('/',(req,res)=>{
res.sendFile(path.join(__dirname, "public/index.html"));
});
app.listen(port, ()=>{
console.log("listening...", process.env.NODE_ENV);
});
process.env.NODE_ENV is undefined.
Here is the webpack.config
const webpack = require('webpack');
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const VENDOR_LIBS = ['react', 'react-dom', 'bootstrap', 'jquery'];
module.exports = {
entry: {
bundle: './src/index.js',
vendor: VENDOR_LIBS
},
output: {
path: __dirname + '/public',
filename: '[name].js'
},
module: {
rules: [
{
use: 'babel-loader',
test: /\.(js|jsx)$/,
exclude: /node_modules/
},
{
loader: ['style-loader', 'css-loader'],
test: /.css$/
},
{
test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url?limit=10000&mimetype=application/octet-stream'
},
{
loader: 'url?limit=10000!img?progressive=true',
test: /\.(jpe?g|png|gif|svg)$/i
}
]
},
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jquery: 'jquery',
jQuery: 'jquery'
}),
new webpack.optimize.CommonsChunkPlugin({name: "vendor", filename: "vendor.js"}),
new ExtractTextPlugin("./styles/bootstrap.css"),
new webpack.DefinePlugin({'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)})
]
}
Any help would be greatly appreciated.