javascript - 请求的模块不提供名为
问题描述
我正在将这个 javascript 项目 ( https://github.com/Legorin/satisfactory-calculator ) 翻译成打字稿。
当我在 html 脚本标签中导入转译的打字稿文件时出现错误。
<script>
var handlers = {}
</script>
<script type="module">
import { Initilatizion } from "./init.js";
handlers.init = Initilatizion.init;
</script>
错误是:Uncaught SyntaxError: The requested module './init.js' does not provide an export named 'Initilatizion'
这是我的 init.ts 文件
import { Belt } from "./belt";
import { Building } from "./building";
import { FactorySpecification } from "./factorySpecification";
import { Fragment } from "./fragment";
import { Item } from "./item";
import { Recipe } from "./recipe";
import { Settings } from "./settings";
// tslint:disable-next-line: no-var-requires
const d3 = require("../third_party/d3.min.js");
export class Initilatizion {
public static loadData(settings) {
const spec: FactorySpecification = FactorySpecification.getInstance();
d3.json("data/data.json").then((data) => {
const items = Item.getItems(data);
const recipes = Recipe.getRecipes(data, items);
const buildings = Building.getBuildings(data);
const belts = Belt.getBelts(data);
spec.setData(items, recipes, buildings, belts);
Settings.renderSettings(settings);
spec.updateSolution();
});
}
public static init() {
const settings = Fragment.loadSettings(window.location.hash);
this.loadData(settings);
}
}
这是我的 tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"esModuleInterop": true,
"target": "es6",
"moduleResolution": "node",
"sourceMap": true,
"allowJs": true,
"outDir": "dist",
"sourceRoot": "src",
},
}
我的错误在哪里?
解决方案
您module
在tsconfig.json
!
通过设置module
告诉typescript"commonjs"
生成一个 JavaScript 文件,该文件使用 nodejs 和其他人使用的commonjs导入/导出语法。但是,您在 HTML 中使用“新”ES6 模块导入/导出语法,因此必须设置module
为"esnext"
or "es6"
!
注意:您共享了一个无效的 tsconfig.json 文件,我在下面修复了它
示例tsconfig.json
:
{
"compilerOptions": {
"module": "es6",
"esModuleInterop": true,
"target": "es6",
"moduleResolution": "node",
"sourceMap": true,
"allowJs": true,
"outDir": "dist",
"sourceRoot": "src"
},
}