3
votes

I would like organize my typescript code with es6 module and load them via the script type="module" directly in the browser. I have checked the support (https://caniuse.com/#feat=es6-module) and it would work. I use chrome version 66.

I have tried without success (see code below) and moreover I m confused about the correct strategy to use.

Solution 1 : In app.ts file, should I import the external module but then how to load the correct js file ?

Solution 2 : In app.ts file, should I import directly the .js code but how to reference the .d.ts file to have the type checkin ?

Any help will be greatly appreciated.

=======================================================================

This is the code i have tried

My index.html file

<!-- 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>

My app.ts file

//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 :)!'
    }
});

My tsconfig.json file

// tsconfig.json
{
  "compilerOptions": {
    "strict": true,
    "target": "es6",
    "module": "es6",
    "moduleResolution": "node",
    "allowJs": true
  }
}

My package.json file

{
  "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"
  }
}
1
If you want strict type checking on VueJS, have a look at vue-property-decorator :)Terry

1 Answers

3
votes

After days of research, I have found an answer. For the moment, it s not possible to do with typescript without using a module loader. There is a lot of discussion about a native loader in the browser in typescript.

More information are available here =>

https://github.com/Microsoft/TypeScript/issues/16577 https://github.com/Microsoft/TypeScript/issues/13422

An interesting proposition draft has started and is available here =>

https://github.com/domenic/package-name-maps