I have an xState State Machine defined in a MYSM.js. I would like to try importing this javascript file in my app.js file. I have tried every solution and I can't get it to work.
MYSM.js
const { createMachine, actions, interpret, assign, interface } = XState;
export interface MYSMContext {
returnCode: undefined, errorMessage: undefined
}
export const mySM = createMachine({/* code here */});
app.js
import {mySM} from './MYSM.js'
const newContext = {returnCode: 0; errorMessage: ''};
const dynamicSM = mySM.withContext(newContext);
const myService = interpret(dynamicSM).start();
index.html
<!-- xState State Machine-->
<script type="module" src="https://unpkg.com/xstate#4/dist/xstate.js"></script>
<script type="module" src="https://unpkg.com/xstate#4/dist/xstate.web.js"></script>
<script type="module" src="~/js/MYSM.js"></script>
<script type="text/javascript" src="~/js/app.js"></script>
In my browser, I'm getting the 'SyntaxError: Cannot use import statement outside a module'
How do I import MYSM.js into app.js?
The error should be taken quite literally:
SyntaxError: Cannot use import statement outside a module
You are using import statement import {mySM} from './MYSM.js' inside app.js, which is not a module. But the rule is clear: you cannot use import statement, if it is not inside a module. Change app.js to module by changing type attribute:
<script type="module" src="~/js/app.js"></script>
Additional notes:
You can also remove this line of code
<script type="module" src="~/js/MYSM.js"></script>
since you are already importing mySM inside app.js.
Related
my situation is as follows:
I want to try out some components from the Azure Communication Services UI Library: (https://azure.github.io/communication-ui-library/?path=/docs/quickstarts-composites--page).
The thing is: I want to use them in codebase that is kind of legacy (let's say an older version of ASP.NET), so there is no way I can import the modules in a React/Angular-way. I would probably need to import them in plain HTML.
My idea was: I can create a separate 'site.js' file, import the module in there and load this in the main _Layout.cshtml.
I wrote this script:
// TODO: How can we import this module?
import { Chat } from "#azure/communication-chat";
const chat = new Chat({
auth: {
token: "Your token here"
},
conversationId: "Your conversation Id here",
});
const chatContainer = document.getElementById("chat-container");
chat.render(chatContainer);
And then imported the script like this:
<script src="~/js/site.js" asp-append-version="true"></script>
But that gives me the error: "Uncaught SyntaxError: Cannot use import statement outside a module".
Apparently it is not possible this way.
So my question is: Is it possible at all? What other ways are there to try?
You need to source your JS as a module, which requires adding type="module" to the script node:
<script src="~/js/site.js" type="module" asp-append-version="true"></script>
Taken from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules#applying_the_module_to_your_html. The whole page is probably worth reading.
You can only use import and export statements inside modules, not regular scripts
I want to import react in ejs it shows cannot use import statement outside module.
import React from react
When I execute this ^^^ I get error cannot use import statement outside module.
const {React} = require("react")
When I run this ^^^ it gives me error require is not defined...
You need to set your script type as module to be able to use import statement / ES Module :
If you are using node.js, you have to edit your package.json and set :
{
"type": "module",
}
Else, if you import your js script from an html balise you have to set (almost the same thing) :
<script src="app.js" type="module" ></script>
This will enable the use of import inside app.js
I have Javascript codes as below. When the importation is inside <script src="..."></script>, it works. However, if I moved the importation to import ...;, it doesn't work. The error message is: "Uncaught ReferenceError: Stats is not defined".
Why is that? Since I am working on a Jekyll site, I prefer to do the import ...; way to make sure other elements of the site work. Any idea how to do the import ...; way without error?
It works
<div id="stats"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/stats.js/r16/Stats.min.js"></script>
<script type="module">
const stats = new Stats()
stats.setMode(0)
document.getElementById('stats').appendChild(stats.domElement)
</script>
It doesn't work
<div id="stats"></div>
<script type="module">
import 'https://cdnjs.cloudflare.com/ajax/libs/stats.js/r16/Stats.min.js';
const stats = new Stats()
stats.setMode(0)
document.getElementById('stats').appendChild(stats.domElement)
</script>
import allows you to import JavaScript modules which conform to the ES6 module format.
Stats.min.js does not. The code is obfuscated but appears to create a global and support the old CommonJS module format.
This is a simple problem. I'm attempting to import modules from one javascript file to another, and then run it on Chrome. I'm using 2 javascript files and an html file, all in the same folder:
first js file (testfile1.js):
import {test} from 'testfile2.js';
test.func();
second js file (testfile2.js):
let f = function() {
console.log("TEST");
}
let test = {
func: f
};
export test;
The html file is plain, empty html file with a link to testfile1.js script in the header:
<script type="text/javascript" src="testfile1.js"></script>
Whenever I open the html file in chrome, I get the error:
testfile1.js:1 Uncaught SyntaxError: Unexpected token {
When I removed the brackets in the import statement, I get an unexpected identifier statement. Isn't this the proper way to import modules in the browser? Why is it not working at all?
Modules require type="module" not "text/javascript"
As per Jaromanda X's comment, you need to change the value of the type attribute of the <script> tag to "module" as import { test } from 'testfile2.js' is module code.
<script type="module" src="testfile1.js" />
What about dynamic import()
If you really don't feel like using type="module", any javascript file is allowed to use the dynamic import() syntax, even without type="module".
However, the dynamic import has a caveat, the function import() returns a promise, therefore, you are unable to use it synchronously. You must either await or .then a dynamic import to use the value it resolves to.
import('testfile2.js').then(({ test }) => {
// your code
});
I am able to define a module in my html file me.html:
<script type="module" id="DEFAULT_MODULE">
import Atom from './atom.js';
console.log("definition of getAtom")
export default function getAtom(){
return new Atom('atom');
}
console.log("exported getAtom")
</script>
Also see
https://blog.whatwg.org/js-modules
https://github.com/whatwg/html/pull/443#issuecomment-167639239
=> Is it possible to import that "anonymous" module to another module script in the same html file? Or to some "code behind"- JavaScript file that also has been loaded by the me.html file? The export seems to work; at least it does not throw any error.
For the import of the getAtom method I tried for example:
<script type="module">
import getAtom from '.'; //this line does not work
console.log("usage of getAtom")
var atom = getAtom();
</script>
I would expect some syntax like
import getAtom;
import getAtom from '.';
import getAtom from window;
import getAtom from './me.html';
import getAtom from '.DEFAULT_MODULE';
However, none of these lines worked.
=>What is the correct syntax to reference the "anonymous" module if it is possible at all?
I use Chrome version 63.0.3239.108.
Related question:
How to dynamically execute/eval JavaScript code that contains an ES6 module / requires some dependencies?
As I understand, there is no way to import "anonymous" module, because "anonymous" module have no module specifier or individual url (its import.meta.url is just the html url as current spec). In theory it can be extended in the future, but I can not find the good use cases for such feature.