refactor: simplify config loading by skip fs.existsSync check (#5305)

Use error code thrown by `require` directly.
This also simplifies module mocking in unit test.
This commit is contained in:
Haoqun Jiang
2020-03-24 15:24:52 +08:00
committed by GitHub
parent 5b1709abf0
commit f1bdf7319a
2 changed files with 15 additions and 24 deletions

View File

@@ -1,5 +1,4 @@
jest.mock('fs')
jest.mock('/vue.config.js', () => ({ lintOnSave: false }), { virtual: true })
jest.mock('vue-cli-plugin-foo', () => () => {}, { virtual: true })
const fs = require('fs')
@@ -125,23 +124,18 @@ test('keep publicPath when empty', () => {
})
test('load project options from vue.config.js', () => {
process.env.VUE_CLI_SERVICE_CONFIG_PATH = `/vue.config.js`
fs.writeFileSync('/vue.config.js', `module.exports = { lintOnSave: false }`)
jest.mock(path.resolve('/', 'vue.config.js'), () => ({ lintOnSave: false }), { virtual: true })
mockPkg({
vue: {
lintOnSave: 'default'
}
})
const service = createMockService()
fs.unlinkSync('/vue.config.js')
delete process.env.VUE_CLI_SERVICE_CONFIG_PATH
// vue.config.js has higher priority
expect(service.projectOptions.lintOnSave).toBe(false)
})
test('load project options from vue.config.js', () => {
process.env.VUE_CLI_SERVICE_CONFIG_PATH = `/vue.config.js`
fs.writeFileSync('/vue.config.js', '') // only to ensure fs.existsSync returns true
test('load project options from vue.config.js as a function', () => {
jest.mock('/vue.config.js', () => function () { return { lintOnSave: false } }, { virtual: true })
mockPkg({
vue: {
@@ -149,8 +143,6 @@ test('load project options from vue.config.js', () => {
}
})
const service = createMockService()
fs.unlinkSync('/vue.config.js')
delete process.env.VUE_CLI_SERVICE_CONFIG_PATH
// vue.config.js has higher priority
expect(service.projectOptions.lintOnSave).toBe(false)
})

View File

@@ -1,4 +1,3 @@
const fs = require('fs')
const path = require('path')
const debug = require('debug')
const merge = require('webpack-merge')
@@ -305,21 +304,21 @@ module.exports = class Service {
process.env.VUE_CLI_SERVICE_CONFIG_PATH ||
path.resolve(this.context, 'vue.config.js')
)
if (fs.existsSync(configPath)) {
try {
fileConfig = require(configPath)
try {
fileConfig = require(configPath)
if (typeof fileConfig === 'function') {
fileConfig = fileConfig()
}
if (typeof fileConfig === 'function') {
fileConfig = fileConfig()
}
if (!fileConfig || typeof fileConfig !== 'object') {
error(
`Error loading ${chalk.bold('vue.config.js')}: should export an object or a function that returns object.`
)
fileConfig = null
}
} catch (e) {
if (!fileConfig || typeof fileConfig !== 'object') {
error(
`Error loading ${chalk.bold('vue.config.js')}: should export an object or a function that returns object.`
)
fileConfig = null
}
} catch (e) {
if (e.code !== 'MODULE_NOT_FOUND') {
error(`Error loading ${chalk.bold('vue.config.js')}:`)
throw e
}