How to get Javascript's IMPORT EXPORT working. Do I need transpiler?

房东的猫 提交于 2021-01-27 21:50:42

问题


I am so confused about this. All I want to do is simply break up my javascript into modules, and include them in certain pages. Some pages may need my user-module.js , some pages may not.

I have Googled, read the tutorials, and it's still not working for me.

Here is a simple test case:

1. Include my script from my html

<script src="../js/login-view-model.js"></script>

Now, inside there...

2. TRY to include another module/js file


// LoginViewModel


// I NEED MY IMPORT HERE
import { userService } from '../js/viewModels/user-service.js'

var LoginViewModel = function () {

    self = this;

    userService.user.sayHello();

}; // End View Model

ko.applyBindings(new LoginViewModel());

Now, inside my user-service.js

user-service.js

let user = {
     sayHello: function() { alert("hello") };
}

export {user};

I don't see what I am missing.

Do I need to use another JS library to get this simple example working? I am so lost...lol , please help!

Oh, as you can see I am using KnockoutJS. Not sure if that is the problem.

Thank you.

John


回答1:


(There isn't really a good way to show how to do this in something like jsfiddle, so I appologize for the inline code)

Here is a very basic example of what you're trying to do (minus the knockout part)

One key here is that you need to tell the browser that your script is a module (type="module") (see ES6 in the browser: Uncaught SyntaxError: Unexpected token import for some other issues you can run into when not defining type as module)

The other key fix to your problem is that you're trying to invoke .sayHello() in the wrong way.

userService.user.sayHello(); // wrong
userService.sayHello(); // right

You exported user so you don't need to do .user, there is no property of user on your exported object. userService is already user

Working Example:

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <script src="loginviewmodel.js" type="module"></script>
</body>
</html>

View Model

import { user } from "./userservice.js";

user.sayHello();

User Service

let user = {
    sayHello: function() { alert("hello"); }
};

export {user};



回答2:


you need a module bundler like webpack for example to take care of that

take your main file as an entry and generate a single JavaScript file based on your imports.

Example of a simple webpack configuration.

var path = require('path');

module.exports = {
  entry: './main.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'output.bundle.js'
  }
};


来源:https://stackoverflow.com/questions/56959001/how-to-get-javascripts-import-export-working-do-i-need-transpiler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!