npm run build = 无图像 [英] npm run build = no images
问题描述
这里遇到了我的项目 vuejs2 + webpack 的问题……
当我进行生产构建(npm run build)时,我的图像没有出现..
我没有在 webpack 配置中找到插件修改构建的地方,或者我可以用 vuejs 做什么来实现它.
如果有人有想法或已经遇到过这个问题,那就太好了!
截图:
感谢您的回复,
vuejs 的 3 种方式可以运行 dev 但不能运行 build
<div id="测试"><img :src="urlLogo"/>
</模板><脚本>导出默认{name: '授权',数据 () {返回 {urlLogo: require('../../static/img/mylogo.png')}}}
或
<div id="测试"><img src="/static/img/mylogo.png"/>
</模板>
或
<div id="测试"><img src="~@/assets/img/mylogo.png"/>
</模板>
这里是我的 config/index.js
'使用严格'//模板版本:1.3.1//有关文档,请参阅 http://vuejs-templates.github.io/webpack.const path = require('path')模块.出口 = {开发:{//la config de dev},建造: {//index.html 的模板索引:path.resolve(__dirname, '../www/dist/index.html'),//路径assetsRoot: path.resolve(__dirname, '../www/dist'),资产子目录:'静态',资产公共路径:'',/*** 源地图*/生产源映射:真,//https://webpack.js.org/configuration/devtool/#productiondevtool: '#source-map',//默认情况下 Gzip 关闭许多流行的静态主机,例如//Surge 或 Netlify 已经为您压缩了所有静态资产.//在设置为 `true` 之前,请确保://npm install --save-dev compression-webpack-plugin生产Gzip:假,productionGzipExtensions: ['js', 'css'],//运行带有额外参数的构建命令//在构建完成后查看包分析器报告://`npm run build --report`//设置为 `true` 或 `false` 以始终打开或关闭它bundleAnalyzerReport:process.env.npm_config_report}}
build/webpack.prod.conf.js:
'使用严格'const path = require('path')const utils = require('./utils')const webpack = require('webpack')const config = require('../config')const merge = require('webpack-merge')const baseWebpackConfig = require('./webpack.base.conf')const CopyWebpackPlugin = require('copy-webpack-plugin')const HtmlWebpackPlugin = require('html-webpack-plugin')const ExtractTextPlugin = require('extract-text-webpack-plugin')const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')const UglifyJsPlugin = require('uglifyjs-webpack-plugin')const env = process.env.NODE_ENV === '测试'?要求('../config/test.env'): 需要('../config/prod.env')const webpackConfig = merge(baseWebpackConfig, {模块: {规则:utils.styleLoaders({sourceMap: config.build.productionSourceMap,摘录:真实,usePostCSS: 真})},开发工具: config.build.productionSourceMap ?config.build.devtool :假,输出: {路径:config.build.assetsRoot,文件名:utils.assetsPath('js/[name].[chunkhash].js'),chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')},插件: [//http://vuejs.github.io/vue-loader/en/workflow/production.html新的 webpack.DefinePlugin({'process.env':环境}),新的 UglifyJsPlugin({丑化选项:{压缩:{警告:错误}},sourceMap: config.build.productionSourceMap,平行:真}),//将 css 提取到它自己的文件中新的提取文本插件({文件名:utils.assetsPath('css/[name].[contenthash].css'),//将以下选项设置为 `false` 将不会从代码拆分块中提取 CSS.//当 webpack 加载 codesplit 块时,它们的 CSS 将改为使用 style-loader 动态插入.//当前设置为 `true` 因为我们看到 sourcemaps 也包含在 codesplit bundle 中,当它为 `false` 时,//增加文件大小:https://github.com/vuejs-templates/webpack/issues/1110allChunks:真的,}),//压缩提取的 CSS.我们正在使用这个插件,以便可能//可以删除来自不同组件的重复 CSS.新的 OptimizeCSSPlugin({cssProcessorOptions: config.build.productionSourceMap?{安全:真,地图:{内联:假}}:{安全:真实}}),//生成带有正确资产哈希的 dist index.html 用于缓存.//您可以通过编辑/index.html 自定义输出//参见 https://github.com/ampedandwired/html-webpack-plugin新的 HtmlWebpackPlugin({文件名:process.env.NODE_ENV === '测试'?'index.html': config.build.index,模板:'index.html',注入:真实,缩小:{删除评论:真实,折叠空白:真,removeAttributeQuotes: 真//更多选择://https://github.com/kangax/html-minifier#options-quick-reference},//必须通过 CommonsChunkPlugin 一致地处理多个块chunksSortMode: '依赖'}),//当供应商模块没有改变时保持 module.id 稳定//new webpack.HashedModuleIdsPlugin(),//启用范围提升新的 webpack.optimize.ModuleConcatenationPlugin(),//将 vendor js 拆分成自己的文件新的 webpack.optimize.CommonsChunkPlugin({name: '供应商',minChunks(模块){//node_modules 中的任何必需模块都被提取到供应商返回 (module.resource &&/\.js$/.test(module.resource) &&module.resource.indexOf(path.join(__dirname, '../node_modules')) === 0)}}),//将 webpack 运行时和模块清单提取到它自己的文件中,以便//每当应用程序包更新时,防止供应商哈希值更新新的 webpack.optimize.CommonsChunkPlugin({name: '清单',minChunks:无穷大}),//此实例从代码拆分的块中提取共享块并捆绑它们//在一个单独的块中,类似于供应商块//参见:https://webpack.js.org/plugins/commons-chunk-plugin/#extra-async-commons-chunk新的 webpack.optimize.CommonsChunkPlugin({名称:'应用',异步:'供应商异步',孩子们:真的,最小块数:3}),//复制自定义静态资源新的 CopyWebpackPlugin([{来自:path.resolve(__dirname, '../static'),到:config.build.assetsSubDirectory,忽略: ['.*']}])]})如果(config.build.productionGzip){const CompressionWebpackPlugin = require('compression-webpack-plugin')webpackConfig.plugins.push(新的 CompressionWebpackPlugin({资产:'[路径].gz[查询]',算法:'gzip',测试:新的正则表达式('\\.(' +config.build.productionGzipExtensions.join('|') +')$'),阈值:10240,最小比率:0.8}))}如果(config.build.bundleAnalyzerReport){const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPluginwebpackConfig.plugins.push(new BundleAnalyzerPlugin())}module.exports = webpackConfig
build/build.js:
'使用严格'require('./check-versions')()process.env.NODE_ENV = '生产'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('构建生产...')微调器.start()rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {如果(错误)抛出错误webpack(webpackConfig, (err, stats) => {Spinner.stop()如果(错误)抛出错误process.stdout.write(stats.toString({颜色:真实,模块:假,children: false,//如果您使用 ts-loader,将其设置为 true 将使 TypeScript 错误在构建期间出现.块:假,块模块:假}) + '\n\n')如果(stats.hasErrors()){console.log(chalk.red(' Build failed with errors.\n'))process.exit(1)}console.log(chalk.cyan('构建完成.\n'))控制台.日志(粉笔.黄色(' 提示:构建的文件旨在通过 HTTP 服务器提供服务.\n' +' 通过 file://打开 index.html 将不起作用.\n'))})})
您提供的代码有两个问题,第一个是信息",第二个是问题的原因.
首先,Android 上的cordova 应用程序托管在file:///android_asset/www/
上,而不是像浏览器或iOS 上那样的根目录.这意味着:绝对网址不适用于 Android 上的cordova.您需要更改 src
属性以使用相对于包含模板的磁盘文件(例如您的 .vue
文件)的相对 URL.当 webpack 处理文件时,它会正确地将相对 URL 替换为包中图像的 1.
其次(也是更重要的),你的 webpack 配置似乎没有提到关于 .vue
文件的任何内容,我假设你在那里存储 Vue.js 2 模板,所以 webpack 是不实际处理 .vue
文件.您需要使用诸如 vue-loader webpack 插件 之类的东西来允许 webpack 处理您的单文件组件.
查看 vue-loader 的文档,或者使用类似
您可以运行以下命令以快速获得包含热重载的示例:
npm install -g @vue/cliVue 创建你好你好npm 运行服务
这是我在 Webpack 2 中使用的相应配置(看起来您出于某种原因正在使用 Webpack 1)是:
模块:{规则: [...{测试:/\.vue$/,loader: 'vue-loader',选项: {加载器:utils.cssLoaders({sourceMap: isProduction?config.build.productionSourceMap: config.dev.cssSourceMap,提取:isProduction})}},...]}
如果您仍有问题或无法解决,请尝试使用 Chrome 开发工具调试在 Android 模拟器中运行的应用 以探索最终在模拟器中运行的内容.这将为您(我和其他人)提供更多关于可能出错的线索!
Here I meet a problem with my project vuejs2 + webpack…
When I make a build for production (npm run build) my images do not appear..
I don't find the place in the webpack config, which the plugin makes a modification to build or what can i do with vuejs to make it.
If anyone has an idea or has already encountered this problem - it would be great!
Screenshots:
Run on dev is Ok no matter with 3 ways below
After build no images, no icons
Thx all for your responses,
3 ways with vuejs run dev ok but not in run build
<template>
<div id="test">
<img :src="urlLogo" />
</div>
</template>
<script>
export default {
name: 'Auth',
data () {
return {
urlLogo: require('../../static/img/mylogo.png')
}
}
}
</script>
Or
<template>
<div id="test">
<img src="/static/img/mylogo.png" />
</div>
</template>
Or
<template>
<div id="test">
<img src="~@/assets/img/mylogo.png" />
</div>
</template>
Here my config/index.js
'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.
const path = require('path')
module.exports = {
dev: {
// la config de dev
},
build: {
// Template for index.html
index: path.resolve(__dirname, '../www/dist/index.html'),
// Paths
assetsRoot: path.resolve(__dirname, '../www/dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '',
/**
* Source Maps
*/
productionSourceMap: true,
// 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
}
}
build/webpack.prod.conf.js:
'use strict'
const path = require('path')
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const env = process.env.NODE_ENV === 'testing'
? require('../config/test.env')
: require('../config/prod.env')
const webpackConfig = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({
sourceMap: config.build.productionSourceMap,
extract: true,
usePostCSS: true
})
},
devtool: config.build.productionSourceMap ? config.build.devtool : false,
output: {
path: config.build.assetsRoot,
filename: utils.assetsPath('js/[name].[chunkhash].js'),
chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
},
plugins: [
// http://vuejs.github.io/vue-loader/en/workflow/production.html
new webpack.DefinePlugin({
'process.env': env
}),
new UglifyJsPlugin({
uglifyOptions: {
compress: {
warnings: false
}
},
sourceMap: config.build.productionSourceMap,
parallel: true
}),
// extract css into its own file
new ExtractTextPlugin({
filename: utils.assetsPath('css/[name].[contenthash].css'),
// Setting the following option to `false` will not extract CSS from codesplit chunks.
// Their CSS will instead be inserted dynamically with style-loader when the codesplit chunk has been loaded by webpack.
// It's currently set to `true` because we are seeing that sourcemaps are included in the codesplit bundle as well when it's `false`,
// increasing file size: https://github.com/vuejs-templates/webpack/issues/1110
allChunks: true,
}),
// Compress extracted CSS. We are using this plugin so that possible
// duplicated CSS from different components can be deduped.
new OptimizeCSSPlugin({
cssProcessorOptions: config.build.productionSourceMap
? { safe: true, map: { inline: false } }
: { safe: true }
}),
// generate dist index.html with correct asset hash for caching.
// you can customize output by editing /index.html
// see https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: process.env.NODE_ENV === 'testing'
? 'index.html'
: config.build.index,
template: 'index.html',
inject: true,
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
// more options:
// https://github.com/kangax/html-minifier#options-quick-reference
},
// necessary to consistently work with multiple chunks via CommonsChunkPlugin
chunksSortMode: 'dependency'
}),
// keep module.id stable when vendor modules does not change
//new webpack.HashedModuleIdsPlugin(),
// enable scope hoisting
new webpack.optimize.ModuleConcatenationPlugin(),
// split vendor js into its own file
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks (module) {
// any required modules inside node_modules are extracted to vendor
return (
module.resource &&
/\.js$/.test(module.resource) &&
module.resource.indexOf(
path.join(__dirname, '../node_modules')
) === 0
)
}
}),
// extract webpack runtime and module manifest to its own file in order to
// prevent vendor hash from being updated whenever app bundle is updated
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest',
minChunks: Infinity
}),
// This instance extracts shared chunks from code splitted chunks and bundles them
// in a separate chunk, similar to the vendor chunk
// see: https://webpack.js.org/plugins/commons-chunk-plugin/#extra-async-commons-chunk
new webpack.optimize.CommonsChunkPlugin({
name: 'app',
async: 'vendor-async',
children: true,
minChunks: 3
}),
// copy custom static assets
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.build.assetsSubDirectory,
ignore: ['.*']
}
])
]
})
if (config.build.productionGzip) {
const CompressionWebpackPlugin = require('compression-webpack-plugin')
webpackConfig.plugins.push(
new CompressionWebpackPlugin({
asset: '[path].gz[query]',
algorithm: 'gzip',
test: new RegExp(
'\\.(' +
config.build.productionGzipExtensions.join('|') +
')$'
),
threshold: 10240,
minRatio: 0.8
})
)
}
if (config.build.bundleAnalyzerReport) {
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}
module.exports = webpackConfig
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, (err, stats) => {
spinner.stop()
if (err) throw err
process.stdout.write(stats.toString({
colors: true,
modules: false,
children: false, // If you are using ts-loader, setting this to true will make TypeScript errors show up during build.
chunks: false,
chunkModules: false
}) + '\n\n')
if (stats.hasErrors()) {
console.log(chalk.red(' Build failed with errors.\n'))
process.exit(1)
}
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'
))
})
})
There are two problems in the code you provided, the first one 'for information', and the second one the cause of your problem.
First off, cordova apps on Android are hosted at file:///android_asset/www/
, not the root like in the browser, or on iOS. This means that: absolute URLs won't work with cordova on Android. You need to change the src
attribute to use a relative URL, relative to the file on disk containing your template (e.g. your .vue
file). When webpack processes the file, it will correctly replace the relative URL with one to the image in the bundle.
Secondly (and more importantly), your webpack config doesn't seem to mention anything about .vue
files, which is where I assume you are storing your Vue.js 2 template, so webpack is not actually processing the .vue
files. You need to use something like the vue-loader webpack plugin to allow webpack to process your single-file components.
Take a look at the documentation for vue-loader, or use something like the webpack-simple boilerplate as a starting point to understand what config you need to include.
You could run the following to quickly get an example working which includes hot-reload:
npm install -g @vue/cli
vue create hello
cd hello
npm run serve
This is the corresponding config that I use with Webpack 2 (it looks like you're using Webpack 1 for some reason) is:
module: {
rules: [
...
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: utils.cssLoaders({
sourceMap: isProduction
? config.build.productionSourceMap
: config.dev.cssSourceMap,
extract: isProduction
})
}
},
...
]
}
If you still have problems or can't figure it out, try using Chrome Dev Tools to debug the app running in the Android emulator to explore what ends up running in the emulator. That will give you (me, and others) more clues as to what could be going wrong!
这篇关于npm run build = 无图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!