If you're working with the Vue CLI and trying to import global JS or CSS libraries, you're not alone. Some solutions will tell you to just add the package with a require statement or an @import statement. That works, but there is a time and a place to use @import in Vue — and importing a global CSS library isn't one of them. Instead, let's use an ES6 import statement.
…There is a time and a place to use the
@importstatement in Vue and importing a global CSS library isn't one of them.
What We'll Be Importing#
We'll be importing Bulma, the Flexbox-based CSS framework. I won't go into too much detail here, but it's built entirely on Flexbox, easy to pick up, and requires less markup than Bootstrap.
What We'll Be Doing#
We'll create a Webpack alias for the Bulma dependency. If you read my other post about creating aliases for package imports in React, this approach will look familiar.
I'm assuming you already have the Vue CLI installed. If not, it's straightforward — run npm install -g vue-cli, then vue init webpack my-project, and follow the prompts.
Creating the Webpack Alias#
First, add the Bulma dependency with NPM:
$ npm install bulma --save
Next, open build/webpack.dev.conf.js and paste the following code directly above the module object:
resolve: {
extensions: ['.css'],
alias: {
'bulma': resolve('node_modules/bulma/css/bulma.css'),
}
}
NOTE: If you want to use the SCSS file, there are additional steps you should take prior to following this article.
Now that the alias is set up, import it in src/main.js. Importing it here makes it available across the entire application:
import bulma from 'bulma';
That's it. Really.
Why This Approach Is Worth It#
You could add the relative path to Bulma directly, but the alias approach is cleaner, easier to read, and scales better as your project grows. It also keeps your global dependency imports consistent with the rest of your ES6 module imports — no mixing of require, @import, and import styles throughout your codebase.
Once you understand how Webpack aliases work in Vue CLI, you can apply the same pattern to any shared CSS or JavaScript dependency in your project.
