Bra*_*sen 5 node.js node-modules typescript es6-modules vite
我正在尝试从本地 Nodejs 包导入导出的成员。在使用 Vite(标准 CRA webpack 设置)之前,这些工作正常,但自从切换到 Vite 后,我收到以下错误:
Uncaught SyntaxError:
The requested module '/@fs/Users/...{long_path}.../lib/shared/countries/build/index.js'
does not provide an export named 'countryListAllIsoData'
Run Code Online (Sandbox Code Playgroud)
Vite 项目是使用npm create vite@latest
typescript 、 react、swc 预设进行设置的。
这些失败的导入仅发生在本地软件包上(没有从 npm 注册表安装的软件包),所以我确信问题出在我这边,但我无法找出导致它的原因。
由于他们确实使用 Webpack 工作,我不太确定为什么他们不能使用 Vite 工作?Vite 要求我的项目将项目设置为模块(在package.json
-中"type": "module"
)。模块中导入的工作方式是否会破坏我当前的代码?
我正在使用 VS Code,它似乎对模块的导入方式非常满意。没有显示错误,我可以毫无问题地转到导入的定义(让我相信所有内容都已正确导出)。
我导入如下:
import { countryListAllIsoData } from "countries";
Run Code Online (Sandbox Code Playgroud)
该tsconfig.json
文件未受影响(与创建时完全相同npm create vite@latest
)。这同样适用于该package.json
文件,除了安装了一些模块(例如导致此问题的模块)。
导致此问题的本地包已命名,countries
并且相当小且简单。它有以下package.json
文件:
/// package.json
{
"name": "countries",
"version": "1.0.0",
"description": "",
"main": "./build/index.js",
"exports": {
".": "./build/index.js"
},
"scripts": {
"build": "tsc",
"prepare": "npm run build"
},
"keywords": [],
"author": "Bram Vanbilsen",
"license": "UNLICENSED",
"devDependencies": {
"typescript": "^4.8.4"
}
}
Run Code Online (Sandbox Code Playgroud)
文件tsconfig.json
:
{
"compilerOptions": {
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
"module": "commonjs", /* Specify what module code is generated. */
"moduleResolution": "nodenext", /* Specify how TypeScript looks up a file from a given module specifier. */
"declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
"declarationMap": true, /* Create sourcemaps for d.ts files. */
"outDir": "./build", /* Specify an output folder for all emitted files. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
"strict": true, /* Enable all strict type-checking options. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}
Run Code Online (Sandbox Code Playgroud)
文件index.ts
:
export const countryListAllIsoData = [...] as const;
Run Code Online (Sandbox Code Playgroud)
我遇到了这个问题,并使用 Vite 别名修复了它。
在 Vite 配置中,为包名称添加别名,并包含本地文件夹的绝对路径:
resolve: {
alias: {"countries":"/Users/...{long_path}.../lib/shared/countries"}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2728 次 |
最近记录: |