Reputation: 5734
I have a components.js file that looks like this:
import { lookCoordinate } from './tools.js'; // I get: SyntaxError: Unexpected token {
Vue.component('coordform', {
template: `<form id="popup-box" @submit.prevent="process" v-if="visible"><input type="text" autofocus refs="coordinput" v-model="coords"></input></form>`,
data() {
{
return { coords: '', visible: false }
}
},
created() {
window.addEventListener('keydown', this.toggle)
},
destroyed() {
window.removeEventListener('keydown', this.toggle)
},
methods: {
toggle(e) {
if (e.key == 'g') {
if (this.visible) {
this.visible = false;
} else
this.visible = true;
}
},
process() {
lookCoordinate(this.coords) // Tried to import from tools.js
}
}
});
But I'm getting:
Uncaught SyntaxError: Unexpected token {
How do I import a function from another plain JS file and use it within a Vue component?
Thanks.
Upvotes: 1
Views: 667
Reputation: 29169
You will get this error if trying to load a Javascript file without ES6 support enabled. The parser does not understand the syntax of import
is as it begins parsing the file.
Check your webpack or vue-cli settings to make sure that you are transpiling the code.
For instance, a browser does not know what import
means, and neither does plain old node unless enabling experimental support.
You can also change it to:
const lookCoordinate = require('./tools.js').lookCoordinate;
and see if that gives you an error. That format does almost exactly the same thing.
If using import
from a browser, also enable module support, as suggested by Orkhan Alikhanov in the comments.
It is supported if you add script with type="module". e.g:
<script type="module" src="main.js"></script>
Upvotes: 2
Reputation: 10060
It is supported if you add script with type="module"
:
<script type="module" src="main.js"></script>
Upvotes: 1
Reputation: 155
Can you please try this without {}
.
import { lookCoordinate } from './tools.js'
{}
is used when you define multiple functions inside tools.js
like,
import { lookCoordinate, lookCoordinate2 } from './tools.js'
Upvotes: 0