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

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
}
}

Related

The debugger adapter not works after vsce package

I developed a debug extension which uses an external js debugger adapter. I put the js file to the bin directory looks like this.
rootDir
--bin
----adapter.js
And I used it like this in my development environment.
{
"label": "ThingIO Debugger",
"program": "./bin/adapter.js",
"runtime": "node",
"type": "thingio-debug"
}
The code works well in my development mode, but when I packaged it to a .vsix file and install to another machine, it failed immediately.
The webpack file is below
//#ts-check
'use strict';
const path = require('path');
//#ts-check
/** #typedef {import('webpack').Configuration} WebpackConfig **/
/** #type WebpackConfig */
const extensionConfig = {
target: 'node', // vscode extensions run in a Node.js-context πŸ“– -> https://webpack.js.org/configuration/node/
mode: 'none', // this leaves the source code as close as possible to the original (when packaging we set this to 'production')
entry: './src/extension.ts', // the entry point of this extension, πŸ“– -> https://webpack.js.org/configuration/entry-context/
output: {
// the bundle is stored in the 'dist' folder (check package.json), πŸ“– -> https://webpack.js.org/configuration/output/
path: path.resolve(__dirname, 'dist'),
filename: 'extension.js',
libraryTarget: 'commonjs2'
},
externals: {
vscode: 'commonjs vscode' // the vscode-module is created on-the-fly and must be excluded. Add other modules that cannot be webpack'ed, πŸ“– -> https://webpack.js.org/configuration/externals/
// modules added here also need to be added in the .vscodeignore file
},
resolve: {
// support reading TypeScript and JavaScript files, πŸ“– -> https://github.com/TypeStrong/ts-loader
extensions: ['.ts', '.js']
},
module: {
rules: [
{
test: /\.ts$/,
exclude: /node_modules/,
use: [
{
loader: 'ts-loader'
}
]
}
]
},
devtool: 'nosources-source-map',
infrastructureLogging: {
level: "log", // enables logging required for problem matchers
},
};
module.exports = [ extensionConfig ];
And the vscode:prepublish command is webpack --mode production --devtool hidden-source-map
I think it looks like the debugger adapter program is not found. So I checked the ~/.vscode/extensions, and the adapter js file exists in the right path.
Now I'm very confused about what wrong is with the extension. Maybe the path is wrong or the webpack did not compile the right file in some situation?
Can anyone give some solution or suggestion about this?

In NuxtJS How to configure different paths for publicPath, outputDir, and indexPath

I have situation when i deploy NuxtJS App for production that I need put files in different paths.
I used this configurations before in Vue App in vue.config.js and it’s works fine:
module.exports = {
publicPath:'/assets/my_app/my_page/',
outputDir: path.resolve('../my_app/public/my_page'),
indexPath: path.resolve('../my_app/www/my_page.html'),
devServer: {
allowedHosts: ["my_site.com"],
proxy: {
'^/api': serverProxy,
'^/assets': serverProxy,
'^/files': serverProxy
}
}
};
How can do the same configurations in NuxtJS?
I tried this in nuxt.config.js but it not working:
build: {
publicPath:'/assets/my_app/my_page/',
// outputDir: path.resolve('../my_app/public/my_page'),
},
generate: {
dir: path.resolve('../my_app/www/my_page.html'),
},
there are different Dir properties that you can use in nuxt.config. I think
buildDir ,rootDir or srcDir can help you. However, you can access vue configuration and use your old solution by :
nuxt.config vue.config property

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?

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

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.