Unc*_*oke 1 javascript laravel webpack vue.js laravel-mix
我想在 Laravel 5.8 项目中的 VUE.JS 中使用别名来导入模块中的 css 和 js。
webpack.mix.js
mix.webpackConfig({
resolve: {
alias: {
'alias': path.resolve(
__dirname,
'~myModule/src'
)
}
}
});
Run Code Online (Sandbox Code Playgroud)
在我的 VUE App.js 中,我想导入 css 文件夹,我写道:
资源/js/app.js
// css files
import 'alias/lib/css'
// js files
import 'alias/lib/script'
Run Code Online (Sandbox Code Playgroud)
但我错了,因为别名没有解析:
./resources/js/app.js 中的错误未找到模块:错误:无法解析...中的“alias/lib/css”
你能帮我解决这个问题吗?
经过多次尝试,我遇到了这个问题。代码很好,但我缺少正确加载 webpack.mix.js:
webpack.mix.js 文件是所有资源编译的入口点。将其视为 Webpack 的轻量级配置包装器。混合任务可以链接在一起,以准确定义资产的编译方式。
但是,如果您使用npm run watch,则在编译新的更改资产之前不会(重新)加载它。这意味着:
如果您处于监视模式(npm run watch),则退出并重新启动以加载新更新的webpack.config.js(如果您更改了它)。
终于成功了!并且它正确解析新别名!
这是我在webpack.config.js中使用的最终配置:
mix.webpackConfig({
resolve: {
alias: {
'aliasName': path.resolve(
__dirname,
'node_modules/MyModule/src/'
)
}
}
});
Run Code Online (Sandbox Code Playgroud)
另一种选择是:
mix.webpackConfig({
resolve: {
modules: [
'node_modules'
],
alias: {
'aliasName' : 'MyModule/src/'
}
}
});
Run Code Online (Sandbox Code Playgroud)
然后在我的 Vue 组件中(或者在 vue app.js 中,以防万一)
<template>
<myModule-component></myModule-component>
</template>
require('aliasName/lib/css'); // to load full css directory
require('aliasName/lib/script'); // to load full js directory
import MyModuleComponent from 'aliasName/widgets/MyModuleComponent.vue'
...
export default {
...
components: {
'myModule-component': MyModuleComponent
}
Run Code Online (Sandbox Code Playgroud)