Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why not possible to use ES imports in vue.config.js file with VueJS?

Why aren't ES imports working in vue.config.js file?

In example:

import * as path from 'path';
import * as pjson from './package.json';

module.exports = {
  configureWebpack: {
    resolve: {
      alias: {
        '@': path.join(__dirname, '/src'), // Alias @ to /src folder for ES/TS imports
      },
    },
  },
  pwa: {
    name: pjson.title,
    assetsVersion: pjson.version,
  },
};

Getting error after running npm run lint command (which uses vue-cli-service):

\vue.config.js:1
import * as path from 'path';

SyntaxError: Unexpected token *
    at Module._compile (internal/modules/cjs/loader.js:720:23)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
    at Module.load (internal/modules/cjs/loader.js:643:32)
    at Function.Module._load (internal/modules/cjs/loader.js:556:12)
    at Module.require (internal/modules/cjs/loader.js:6

Also import 'path'; is not working either (tried also other syntax variants):

import 'path';
       ^^^^^^

SyntaxError: Unexpected string

The reason I'm trying to refactor from const path = require('path'); syntax is to avoid this new linter error after ESLint plugins upgrade:

Require statement not part of import statement. eslint(@typescript-eslint/no-var-requires)

But it seems I still need to append this on top of the file: /* eslint-disable @typescript-eslint/no-var-requires */

like image 937
ux.engineer Avatar asked Dec 18 '19 11:12

ux.engineer


People also ask

How do I import files into Vue js?

Here, you can import the JavaScript library by using the 'import' keyword inside the script tag of your Vue file. import * as mykey from '../assets/js/mykey. js'; The second way is to include your external JavaScript file into the mounted hook of your Vue component.

What is Vue config js file?

vue. config. js is an optional config file that will be automatically loaded by @vue/cli-service if it's present in your project root (next to package. json ). You can also use the vue field in package.


1 Answers

The file vue.config.js is loaded by @vue/cli-shared-utils/lib/module.js via CommonJS require. Because of that, it expects vue.config.js to be CommonJS, too.

There are a few schemes you could employ to overcome this built-in limitation such as using vue.config.js to

require('@babel/register'); 

then require another file like vue.config.mjs where your ESM-based code resides.

But given this is only a config file that usually doesn't have a lot of code, it may be better not to fight city hall and instead use CommonJS.

like image 106
nstuyvesant Avatar answered Oct 08 '22 19:10

nstuyvesant