// webpack.mix.js
const mix = require('laravel-mix')
const path = require('path')
// ...
mix.webpackConfig({
resolve: {
alias: {
'@models$': path.resolve(__dirname, 'resources/js/models'),
'@plugins$': path.resolve(__dirname, 'resources/js/plugins'),
'@services$': path.resolve(__dirname, 'resources/js/services'),
'@stores$': path.resolve(__dirname, 'resources/js/stores'),
'@utils$': path.resolve(__dirname, 'resources/js/utils'),
}
}
})
// Alternatively, there is an extension for webpack alias that makes this a bit cleaner.
// @see https://laravel-mix.com/extensions/alias
Note the dollar sign ($) at the end of the alias names. This makes the alias is final. For example:
- with
@utils
we can import@utils/dates/myDateFunction.js
. - with
@utils$
we cannot. Instead we have to expose that function in theindex.js
file.
Create an index.js
file at the root of each folder that has an alias to control what can be imported.
Say inside that folder you have many files that export named variables like this.
// utils/strings.js
export const slugify = value => value.toLowerCase().replace(/[\s\W-]+/g, '-')
export const capitalize = value => value.charAt(0).toUpperCase() + value.slice(1).toLowerCase()
export const titleCase = value => value.replace(/\w[^\s-\_]*/g, capitalize)
Then, you can use the syntax export * from './file'
in your index.js
file since they are already named. Be careful with naming conflicts though.
// utils/index.js
export * from './dates'
export * from './strings'
export * from './common'
export * from './locale'
However, if you use export default
within each of these files you will have to give them a name in your index.js
file.
For example, let's say you have a services
folder where each service has its own file and that each file export the service using export default
.
// services/Http.js
export default {
get (url) { ... },
post (url, data = {}) { ... },
put (url, data = {}) { ... },
patch (url, data = {}) { ... },
delete (url) { ... },
sendRequest (url, data = {}) { ... },
}
Then you need to export them in your index.js
using export { default as MyService } from './my/service'
.
// services/index.js
export { default as Echo } from './Echo'
export { default as Form } from './Form'
export { default as Http } from './Http'