gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 17:19:20 74 4
gpt4 key购买 nike

为什么不是 ES importsvue.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,
},
};

运行后出现错误 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

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

SyntaxError: Unexpected string

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

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



但似乎我仍然需要在文件顶部附加这个: /* eslint-disable @typescript-eslint/no-var-requires */

最佳答案

文件 vue.config.js 由 @vue/cli-shared-utils/lib/module.js 通过 CommonJS require 加载。因此,它也期望 vue.config.js 是 CommonJS。
您可以采用一些方案来克服这个内置限制,例如使用 vue.config.js

require('@babel/register'); 
然后需要另一个文件,例如基于 ESM 的代码所在的 vue.config.mjs。
但鉴于这只是一个配置文件,通常没有很多代码,最好不要与市政厅争吵,而是使用 CommonJS。

关于javascript - 为什么不能使用 VueJS 在 vue.config.js 文件中使用 ES 导入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59391324/

74 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com