为什么不能在带有 VueJS 的 vue.config.js 文件中使用 ES 导入?

ux.*_*eer 7 javascript typescript webpack vue.js vue-cli

为什么ES 导入vue.config.js文件中不起作用?

例如:

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,
  },
};
Run Code Online (Sandbox Code Playgroud)

运行npm run lint命令后出错(使用 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
Run Code Online (Sandbox Code Playgroud)

import 'path';不起作用(也尝试了其他语法变体):

import 'path';
       ^^^^^^

SyntaxError: Unexpected string
Run Code Online (Sandbox Code Playgroud)

我尝试从const path = require('path');语法重构的原因是为了避免在 ESLint 插件升级后出现这个新的 linter 错误:

Require 语句不是 import 语句的一部分。eslint(@typescript-eslint/no-var-requires)

但似乎我仍然需要将其附加到文件的顶部: /* eslint-disable @typescript-eslint/no-var-requires */

nst*_*ant 5

文件 vue.config.js 由 @vue/cli-shared-utils/lib/module.js 通过 CommonJS require 加载。因此,它期望 vue.config.js 也是 CommonJS。

您可以采用一些方案来克服这种内置限制,例如使用 vue.config.js

require('@babel/register'); 
Run Code Online (Sandbox Code Playgroud)

然后需要另一个文件,例如 vue.config.mjs,其中包含基于 ESM 的代码。

但考虑到这只是一个配置文件,通常没有很多代码,最好不要与市政厅对抗,而是使用 CommonJS。