I want `npm run build` generate the dist assets files in the static directory - npm

In my src/config/index.js, the build settings is bellow:
const path = require('path')
module.exports = {
build: {
env: require('./env'),
index: path.resolve(__dirname, '../dist/index.html'),
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: './',
productionSourceMap: true,
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
},
but after I npm run build, I get the results:
shouldn't the assets file in the static directory? where is the error of config?
I want the dist directory like this:
my webpack.prod.config.js default code is bellow:
......
new HtmlWebpackPlugin({
filename: '/index.html',
template: './src/template/index.ejs',
inject: false
})
]
});
the filename: '/index.html', so, the index.html is in the above of dist directory.

Related

Vue & Webpack - make files unreadable after build [duplicate]

My app is created with the vue cli. I can't find any option to disable source maps in production.
The npm build step in my package.json looks like this:
"build": "vue-cli-service build",
In angular, i can just add --prod to my build step to make it work.
Is there any such option for vue.js? Or do I have to change the webpack config (which is hidden by the cli)?
You make changes to the internal webpack config with the vue.config.js file at the project root (you may need to create it manually).
There is a productionSourceMap option so you can disable source maps when building for production:
module.exports = {
productionSourceMap: false
};
like #yuriy636 's answer, if you want only for production :
module.exports = {
productionSourceMap: process.env.NODE_ENV != 'production'
};
In my case the file vue.config.js wasn't taking effect. I had to change config/index.js changing productionSourceMap to false.
Please note that the project was generated a time ago. For the record, I am using a template from Vuetify.
'use strict'
// Template version: 1.2.8
// see http://vuejs-templates.github.io/webpack for documentation.
const path = require('path')
module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {},
// Various Dev Server settings
host: 'localhost', // can be overwritten by process.env.HOST
port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
autoOpenBrowser: false,
errorOverlay: true,
notifyOnErrors: true,
poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
/**
* Source Maps
*/
// https://webpack.js.org/configuration/devtool/#development
devtool: 'cheap-module-eval-source-map',
// If you have problems debugging vue-files in devtools,
// set this to false - it *may* help
// https://vue-loader.vuejs.org/en/options.html#cachebusting
cacheBusting: true,
cssSourceMap: true,
},
build: {
// Template for index.html
index: path.resolve(__dirname, '../dist/index.html'),
// Paths
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: './',
assetsPublicPath: './',
/**
* Source Maps
*/
productionSourceMap: false, // <---- Here
// https://webpack.js.org/configuration/devtool/#production
devtool: '#source-map',
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
}
}

Use sharp on lambda#edge

I'm trying to use sharp on a couple of AWS lambda#edge. The idea is to resize and cache an image when requested (see this).
I'm also using serverless with serverless-webpack to deploy the lambdas.
I can deploy the lambdas and everything goes well if I test them in AWS console.
However, these are lamda#edge and they will be used as cloudwatch request/response triggers. Therefore, the maximum lambda size is 1Mb.
My problem is I can't seem to get even near that size, the best I could achieve was 11.6Mb. And, it seems it's possible as seen in that first link.
This is the serverless configuration which results in 34.7Mb lambda:
custom:
webpack:
includeModules:
forceExclude:
- aws-sdk
packagerOptions:
scripts:
- rm -rf node_modules/sharp && docker run -v "$PWD":/var/task lambci/lambda:build-nodejs10.x npm install sharp
package:
exclude:
- .env
- .git/**
- .gitlab-ci.yml
- tests*
excludeDevDependencies: true
individually: true
And with this I got 11.6Mb:
custom:
webpack:
includeModules:
forceExclude:
- aws-sdk
packagerOptions:
scripts:
- npm rebuild sharp --target=10.15.0 --target_arch=x64 --target_platform=linux
package:
exclude:
- .env
- .git/**
- .gitlab-ci.yml
- tests*
excludeDevDependencies: true
individually: true
I've also played around with the package.exclude, but with no luck:
- node_modules/**
- '!node_modules/sharp/**'
and this is my webpack config:
const path = require('path');
const slsw = require('serverless-webpack');
const nodeExternals = require('webpack-node-externals');
const entries = {};
Object.keys(slsw.lib.entries).forEach(key => (entries[key] = ['./source-map-install.js', slsw.lib.entries[key]]));
module.exports = {
mode: slsw.lib.webpack.isLocal ? 'development' : 'production',
entry: slsw.lib.entries,
devtool: 'source-map',
resolve: {
extensions: ['.js', '.jsx', '.json', '.ts', '.tsx'],
},
// externals: ['sharp'], #tried that too
externals: [nodeExternals()],
output: {
libraryTarget: 'commonjs',
path: path.join(__dirname, '.webpack'),
filename: '[name].js',
},
target: 'node',
module: {
rules: [
// all files with a `.ts` or `.tsx` extension will be handled by `ts-loader`
{ test: /\.ts?$/, loader: 'ts-loader', options: { happyPackMode: true } },
],
},
};
When running locally, I can see what it's packaging... the node_modules folder has sharp and its dependencies, it seems. But the biggest folder is sharp.
I suspect I'm packaging stuff inside sharp folder that I don't need... but I can't seem to understand what.
Any help?
Thanks
UPDATE:
Reading more carefully, it seems the function where I need sharp (origin-response) size limit is 5Mb.
I just need to find a way to package sharp only for that function. Webpack seems to put it in both, even though I don't need it on the other function (viewer request).
Any help on this?
I ended up running a script in custom.webpack.packagerOptions.scripts that will ignore sharp where it's not needed.
This is the script I used:
custom:
webpack:
includeModules:
forceExclude:
- aws-sdk
packagerOptions: # uncomment this block if invoking locally
scripts:
- if [ -f "src/handlers/myfunction.js" ]; then rm -rf node_modules/sharp && docker run -v "$PWD":/var/task lambci/lambda:build-nodejs10.x npm install sharp; else rm -rf node_modules; fi

Vue CLI 3 remove console.log and code comments with Terser

I'm using VUE CLI 3 and I need to remove the console.log and code comments from the production built. This is my Terser setup:
webpack.config.js in src folder
module.exports = {
mode: 'production',
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
terserOptions: {
ecma: undefined,
warnings: false,
parse: {},
compress: {drop_debugger},
mangle: true, // Note `mangle.properties` is `false` by default.
module: false,
output: null,
toplevel: false,
nameCache: null,
ie8: false,
keep_classnames: undefined,
keep_fnames: false,
safari10: false,
},
}),
],
},
};
My production workflow: Run npm run build -> cd dist -> npm run serve
The production build still outputs all console.log statements and shows code comments (<!-- -->).
What do I need to change to remove them?
First of all: make sure you are configuring Terser correctly:
terserOptions: {
ecma: 6,
compress: { drop_console: true },
output: { comments: false, beautify: false }
}
npm run serve
is usually a shortcut for:
vue-cli-service
vue-cli-service --help
Usage: vue-cli-service <command> [options]
Commands:
serve start development server
build build for production
inspect inspect internal webpack config
lint lint and fix source files
So when your workflow is the above mentioned npm run build -> cd dist -> npm run serve then you are actually starting the dev server, which does not apply Terser.
In order to run the production build you can use any webserver capable of serving static content:
NodeJs examples:
npm install -g serve
serve -s dist
or
npm install -g node-static
static dist

How to configure Production build and Development Build vue-cli

I want to setup a npm script for production build and one for development build. like npm run build for production and npm run buildDev for development.
I have some configurations in each env file like:
ROOT_API: '"url for the production"' and something else in the development env.
The build will be added to the dist folder.
I want the Production Build to be added to the dist folder and the Development Build to be added to a distDev folder.
I have tried to make a copy of the build.js file but without luck.
config/index.js:
'use strict'
// see http://vuejs-templates.github.io/webpack for documentation.
const path = require('path')
module.exports = {
build: {
env: require('./prod.env'),
index: path.resolve(__dirname, '../dist/index.html'),
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',
productionSourceMap: true,
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
},
dev: {
env: require('./dev.env'),
port: 8080,
autoOpenBrowser: true,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {},
// CSS Sourcemaps off by default because relative paths are
"buggy"
// with this option, according to the CSS-Loader README
// (https://github.com/webpack/css-loader#sourcemaps)
// In our experience, they generally work as expected,
// just be aware of this issue when enabling this option.
cssSourceMap: false
}
}
config/prod.env.js
module.exports = {
NODE_ENV: '"production"',
ROOT_API: '"url for production"'
}
config/dev.env.js
'use strict'
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')
module.exports = merge(prodEnv, {
NODE_ENV: '"development"',
ROOT_API: '"url for development"'
})
build/build.js
'use strict'
require('./check-versions')()
process.env.NODE_ENV = 'production'
const ora = require('ora')
const rm = require('rimraf')
const path = require('path')
const chalk = require('chalk')
const webpack = require('webpack')
const config = require('../config')
const webpackConfig = require('./webpack.prod.conf')
const spinner = ora('building for production...')
spinner.start()
rm(path.join(config.build.assetsRoot,
config.build.assetsSubDirectory), err => {
if (err) throw err
webpack(webpackConfig, function (err, stats) {
spinner.stop()
if (err) throw err
process.stdout.write(stats.toString({
colors: true,
modules: false,
children: false,
chunks: false,
chunkModules: false
}) + '\n\n')
console.log(chalk.cyan(' Build complete.\n'))
console.log(chalk.yellow(
' Tip: built files are meant to be served over an HTTP
server.\n' +
' Opening index.html over file:// won\'t work.\n'
))
})
})
Any suggestions?
Didn't you try to use vue.config.js file to configure Vue build behavior?
You could specify an outputDir according to process.env.NODE_ENV at vue.config.js.
All environment-specific parameters would be set at .env.development and .env.production files accordingly.
Of course you can modify Webpack config through vue.config.js if you need, examples here.
Output directory parameter changing example is here.
At the end, your configuration file will depend only on environment variables and maybe some logic, e.g.:
module.exports = {
NODE_ENV: process.env.NODE_ENV,
ROOT_API: process.env.VUE_APP_ROOT_API_URL,
ANY_PARAM: process.env.VUE_APP_ANY_DOT_ENV_PARAM,
}
But remember, that your custom .env params should start with VUE_APP_ prefix, if you use them at templates.
Add --mode development entry in your package.json file like this:

Vue Cli 3: defined output paths

I need to configure the output paths of the final build as described below:
My Vue project is default from structure but the output paths are outside this structure:
Output HTML file is: ../main/resources/
Output of all asset files: ../main/assets/[js/css/img]
And in the index.html file the path where to find the assets has to be "js/name.js" and similar.
My current vue.config.js does not provides this:
module.exports = {
chainWebpack: config => {
config.module
.rule('vue')
.use('vue-loader')
.tap(options => {
return options;
});
},
css: {
sourceMap: true
},
baseUrl: '/',
outputDir: '../main/resources/',
assetsDir: '../main/assets/',
runtimeCompiler: undefined,
productionSourceMap: undefined,
parallel: undefined,
configureWebpack: {
module: {
rules: [
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {
outputPath: '../main/assets/img',
name: '../main/assets/img/[name].[ext]'
}
}
]
}
]
}
}
}
Can someone help to configure this file? Thank you!
With kind regards
tschaefermedia
Sorry, I was busy with other projects. Now back to VueJS.
UPDATE:
I tried what was indicated in the GIT posts. My vue.config.js files looks now like this:
const path = require('path');
module.exports = {
css: {
sourceMap: true
},
devServer: {
proxy: {
'/api': {
target: 'http://localhost:8080',
'changeOrigin': true,
'secure': false
}
}
},
baseUrl: '',
outputDir: '../main/resources/',
assetsDir: '../main/assets/',
chainWebpack: config => {
config.module
.rule('vue')
.use('vue-loader')
.tap(options => {
return options
})
config.module
.rule('images')
.test(/\.(png|jpe?g|gif|ico)(\?.*)?$/)
.use('url-loader')
.loader('url-loader')
.options({
name: path.join('../main/assets/', 'img/[name].[ext]')
})
}
}
Everything works now, as I want it to, but the images are not copied to the correct folder.
In ".../assets/" I have the css and js folder but no img folder. In ".../ressources" next to my index.html file I have this folder.
After testing the problem on my build, I think you need two changes:
vue.config.js
module.exports = {
...
outputDir: '../main/resources/',
assetsDir: '../assets/',
...
}
and forget about the webpack plugin!
Ref config:assetsDir
assetsDir
Type: string
Default: ''
A directory (relative to outputDir) to nest generated static assets (js, css, img, fonts) under.
so assets will end up in ../main/resources/../assets/ which equates to ../main/assets/.
Image location in project
The optimum location IMO (from testing) is to use <project folder>/static which is the old CLI2 folder for static resources. In fact, any folder outside of src will do. This makes then handled as-is rather than 'webpacked'.
See Handling Static Assets
"Real" Static Assets ... In comparison, files in static/ are not processed by Webpack at all: they are directly copied to their final destination as-is, with the same filename.
Note quite true, they do get a versioning hash (see below).
This gives the following build folder structure:
../main
assets/
css/
fonts/
images/
js/
resources/
index.html
With CLI 3 the /static folder was changed to /public/static, but if you put your images there, an extra copy is made under ../main/resources/static.
If you prefer this location (to stay standard) you could remove that copy with a postbuild script in package.json, for example using npm run under Windows,
package.json
{
...
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"postbuild": "rd /s /q \"../main/resources/static/images\"",
"lint": "vue-cli-service lint",
"test:unit": "vue-cli-service test:unit"
},
"dependencies": {
Image references
In the source, I found that relative image references work fine.
For example,
import myPic from '../public/static/images/myPic.png'
gets changed to
../assets/img/myPic.ec4d96e7.png
in the built app.js.
Note the hash added for versioning.
Serving the build
I note that the folder structure you use cannot be served with a simple http-server, as index.html is in main/resources and this server cannot fetch from main/assets.
I presume your deploy mechanism takes care of that?