简体   繁体   中英

Webpack alias in Laravel Mix to node_modules

I would like to use an alias in VUE.JS in a Laravel 5.8 project to import css and js I have in my module.

webpack.mix.js

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

In my VUE App.js I would like import the css folder and I wrote:

resources/js/app.js

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

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

But I'm wrong something becouse the alias is not resolved:

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

Can you help me to fix the issue?

After so many attempts I got the issue. The code was good but I was missing to load the webpack.mix.js properly:

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.

But if you are using npm run watch it is not (re)loaded before to compile new changed assets. This means:

if you are in watch mode ( npm run watch ) exit and restart it to load new updated webpack.config.js if you changed it.

Finally it worked! And it resolve new alias properly!

Here the final config I used in webpack.config.js :

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

Another alternative is:

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

Then in my Vue component (or in vue app.js, just in case)

 <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
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM