利用vue-cli3生成的项目,想用url-loader来加载json文件,require('a.json')的时候可以返回一个绝对路径。
vue.config.js配置如下:
'use strict'
const path = require('path')
// const PrerenderSpaPlugin = require('prerender-spa-plugin')
// const Renderer = PrerenderSpaPlugin.PuppeteerRenderer;
function resolve(dir) {
return path.join(__dirname, dir)
}
const name = 'vue Admin Template' // page title
const port = 9528 // dev port
const isProd = process.env.NODE_ENV === 'production';
// All configuration item explanations can be find in https://cli.vuejs.org/config/
module.exports = {
/**
* You will need to set publicPath if you plan to deploy your site under a sub path,
* for example GitHub Pages. If you plan to deploy your site to https://foo.github.io/bar/,
* then publicPath should be set to "/bar/".
* In most cases please use '/' !!!
* Detail: https://cli.vuejs.org/config/#publicpath
*/
publicPath: '/',
assetsDir: 'static' ,
// lintOnSave: process.env.NODE_ENV === 'development',
lintOnSave: false,
productionSourceMap: false,
devServer: {
port: port,
open: true,
overlay: {
warnings: false,
errors: true
},
disableHostCheck : true
},
configureWebpack: {
// provide the app's title in webpack's name field, so that
// it can be accessed in index.html to inject the correct title.
name: name,
resolve: {
alias: {
'@': resolve('src')
}
},
module: {
rules: [
{
test: /\.json$/,
loader: 'url-loader',
options: {
limit: 10000,
name: '/static/json/[name].[hash:7].[ext]'
// name: utils.assetsPath('json/[name].[hash:7].[ext]')
}
}
]
}
},
chainWebpack(config) {
// set preserveWhitespace
config.module
.rule('vue')
.use('vue-loader')
.loader('vue-loader')
.tap(options => {
options.compilerOptions.preserveWhitespace = true
return options
})
.end()
config.module
.rule('json')
.test(/\.json$/)
.include.add(resolve('src/assets')) //处理svg目录
.end()
.use('url-loader')
.loader('url-loader')
.options({
limit:10000,
name:`static/json/[name].[hash:7].[ext]`
})
.end()
}
}
引用代码和报错如下:
有尝鲜的大佬能帮忙看一下问题么
增加json-loader之后代码如下,loader已经正确,但是引入时候依然报错
这是对应的json文件
webpack本质是将多个js合并。所有的loader都是将特定文件转化成js。你直接加载json,因为没有module.exports,是无法被识别的。你需要json-loader或者raw-loader