javascript - Laravel Mix 中的 Webpack 别名为 node_modules

标签 javascript laravel vue.js webpack laravel-mix

我想在 Laravel 5.8 项目中的 VUE.JS 中使用别名来导入模块中的 css 和 js。

webpack.mix.js

mix.webpackConfig({
resolve: {
    alias: {
        'alias':  path.resolve(
            __dirname,
            '~myModule/src'
        )
     }
   }
});

在我的 VUE App.js 中,我想导入 css 文件夹,我写道:

resources/js/app.js

// css files
import 'alias/lib/css'

// js files
import 'alias/lib/script'

但是我错了,因为别名未解析:

ERROR in ./resources/js/app.js Module not found: Error: Can't resolve 'alias/lib/css' in...

你能帮我解决这个问题吗?

最佳答案

经过多次尝试,我发现了这个问题。代码很好,但我缺少正确加载 webpack.mix.js:

From Laravel Mix documentation:

The webpack.mix.js file is your entry point for all asset compilation. Think of it as a light configuration wrapper around Webpack. Mix tasks can be chained together to define exactly how your assets should be compiled.

但是,如果您使用npm run watch,则在编译新的更改 Assets 之前不会(重新)加载。这意味着:

如果您处于监视模式(npm run watch),请退出并重新启动以加载新更新的webpack.config.js(如果您更改了它)。

终于成功了!并且它正确解析新别名!

这是我在 webpack.config.js 中使用的最终配置:

mix.webpackConfig({
resolve: {
    alias: {
        'aliasName':  path.resolve(
            __dirname,
            'node_modules/MyModule/src/'
        )
     }
   }
});

另一种选择是:

mix.webpackConfig({
    resolve: {
        modules: [
            'node_modules'
        ],
        alias: {
            'aliasName' : 'MyModule/src/'
        }
    }
});

然后在我的 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
        }

关于javascript - Laravel Mix 中的 Webpack 别名为 node_modules,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55849379/

相关文章:

javascript - CSS 基于 % 宽度的 jQuery 设置高度

php - 单击 href Laravel 时显示 Bootstrap 模式

php - Laravel 网站上的虚假帐户创建预防

html - 如何在laravel项目中设置X-Frame-Options?

javascript - 无法获取正确的用户 ID 来删除 vue.js 中的列表元素

Vue.js:从父组件触发子组件上的@click

vue.js - nuxt js,如何在服务器端渲染时获取网页的主机名

javascript - 使用 babelify 转译异步函数,不超过 npm

javascript - init 上的 api 调用和参数更改

javascript - jQuery 联系表单标题移动效果