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
Related
I am trying to create a production build with the following configureWebpack but Terser doesnt run during build.
Code is not minimized or uglified. Ialso tried hidden-source-map
Using "terser-webpack-plugin": "^5.3.3" with #vue/cli#5.0.7
isProd is correctly set to true.
const TerserPlugin = require('terser-webpack-plugin');
const isProd = process.env.NODE_ENV === 'production';
module.exports = {
publicPath: '/',
devServer: {
host: 'staging-beta.myDomain.com',
port: 9000,
allowedHosts: 'all',
},
transpileDependencies: ['vuetify'],
chainWebpack: (config) => {
// reducted code
},
configureWebpack: {
devtool: 'source-map',
optimization: {
minimize: isProd,
minimizer: isProd
? [
new TerserPlugin({
minify: TerserPlugin.uglifyJsMinify,
terserOptions: {
compress: {
drop_console: true,
},
output: {
comments: false,
},
},
}),
]
: [],
},
},
};
The correct setup is:
module.exports = defineConfig({
terser: {
minify: 'uglifyJs',
terserOptions: {
compress: {
drop_console: true,
},
},
},
})
You also need to npm install uglify-js
comments under output is deprecated.
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();
}
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.
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
}
}
I have an npm module named sidebar. I use webpack to compile the es2015 src files into a single file. So far running webpack does not output any problem and creates a file, lib/sidebar.min.js
I have set the it to be the main file in package.json
...
"description": "",
"main": "lib/sidebar.min.js",
"scripts": {
...
I have this in my src/index.js file
export const foo = 'foo'
export const bar = 'bar'
I tried using this module in my main project
import { foo, bar } from 'sidebar'
console.log(foo)
console.log(bar)
Both console log calls outputs undefined
After searching the internet for hours, I am totally stumped as to why this is a problem.
Any ideas?
EDIT: Here is the webpack config for the main repository
var webpackConfig = {
entry: {
app: './src/app/main.app.js',
vendor: ['angular']
},
output: {
path: DIST_DIRECTORY + '/scripts/',
publicPath: '/scripts/',
filename: '[name].min.js',
chunkFilename: '[name].min.js'
},
devtool: 'source-map',
module: {
loaders: [{
test: /\.js$/,
loader: 'babel'
}, {
test: /\.html$/,
loader: 'raw'
}]
},
plugins: [
new webpack.NoErrorsPlugin(),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: {
unused: true,
dead_code: true
},
sourceMap: true
}),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}),
new webpack.optimize.CommonsChunkPlugin("vendor", "vendor.bundle.js")
],
devServer: {
contentBase: DIST_DIRECTORY + '/'
}
};