先说需求:搜了一些解决方案,发现很多人只贴一点代码,就说解决了。我照葫芦画瓢,却依然无法实现,这就导致我“既不知其然也不知其所以然”。于是我研究了config/index.js的配置,摸索出找到静态文件的方法,分享如下:
a.我希望打包出来的结构是:
(别问为什么这么麻烦,都是项目需要/0.0\)
dist
- static
---- vuetest
-------- js
-------- css
- templates
---- vuetest
-------- index.html
b.当然就是不要报错啦。
解决:清楚谁是谁,并根据项目实际需要配置
// 原始config/index.js。这里就是和 npm run build 息息相关的配置代码build: {// Template for index.htmlindex: path.resolve(__dirname, '../dist/index.html'),// PathsassetsRoot: path.resolve(__dirname, '../dist'),assetsSubDirectory: 'static',assetsPublicPath: '/',productionSourceMap: true,devtool: '#source-map',productionGzip: false,productionGzipExtensions: ['js', 'css'],bundleAnalyzerReport: process.env.npm_config_report}
调整过后:
可能有点啰嗦,但这里的路径是相对于config/index.js文件本身而言
build: {// Template for index.htmlindex: path.resolve(__dirname, '../dist/templates/vuetest/index.html'),// Paths// 将静态资源打包到哪个目录,会出现js、css文件夹assetsRoot: path.resolve(__dirname, '../dist/static'),// 引用静态资源时可以理解为路径将下面两个相加assetsSubDirectory: 'vuetest',assetsPublicPath: '../../static/',//tip:下面这个改成false,能减少打包出来的体积,true835k,false149kproductionSourceMap: false,devtool: '#source-map',productionGzip: false,productionGzipExtensions: ['js', 'css'],bundleAnalyzerReport: process.env.npm_config_report}
打包时,会根据assetsRoot属性,把静态资源打包到dist/static文件夹。
涉及到静态文件引用时,会将assetsPublicPath +assetsSubDirectory 形成../../static/vuetest的形式引用。
至于是js还是css文件夹,是哪个css文件,这个就不用我们分心了,我们只需要把文件路径配置清楚就好了。