【发布时间】:2018-10-24 07:47:37
【问题描述】:
我想用 es6 模块组织我的打字稿代码,并通过脚本 type="module" 直接在浏览器中加载它们。我已经检查了支持 (https://caniuse.com/#feat=es6-module),它会起作用。我使用的是 chrome 版本 66。
我尝试过但没有成功(参见下面的代码),而且我对使用正确的策略感到困惑。
解决方案1:在app.ts文件中,我应该导入外部模块,然后如何加载正确的js文件?
解决方案2:在app.ts文件中,我应该直接导入.js代码,但是如何引用.d.ts文件进行类型检查?
任何帮助将不胜感激。
================================================ =========================
这是我尝试过的代码
我的 index.html 文件
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<div id="app">
<img src="https://vuejs.org/images/logo.png" alt="Vue logo">
<h1>{{ msg }}</h1>
</div>
<script type="module" src="app.js"></script>
</body>
</html>
我的 app.ts 文件
//Solution 1
// import Vue from "vue"; // Uncaught TypeError: Failed to resolve module specifier "vue". Relative references must start with either "/", "./", or "../".
//Solution 2
import Vue from "./Vendors/vue.esm.browser.js"; // It works in the browser but i have lost the definition inside Typescript file
var app = new Vue({
el: '#app',
data: {
msg: 'hello :)!'
}
});
我的 tsconfig.json 文件
// tsconfig.json
{
"compilerOptions": {
"strict": true,
"target": "es6",
"module": "es6",
"moduleResolution": "node",
"allowJs": true
}
}
我的 package.json 文件
{
"name": "vuejsbrowseresmodule",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"vue": "^2.5.16"
}
}
【问题讨论】:
-
如果你想对 VueJS 进行严格的类型检查,看看 vue-property-decorator :)
标签: typescript vuejs2 es6-modules