I was trying using SystemJS to load React but it didn't loaded instead throwing an error message in Console > 'React is not defined'
I've read their documentation also searching through similar questions but doesn't satisfy my need, did i miss something?
Here's is what I was tried
<!DOCTYPE html> <html lang="en"> <head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>React 18 with SystemJS</title>
<script src="dependencies/systemjs-6.12.1.min.js"></script>
<script type="systemjs-importmap"> {
"imports": {
"react" : "/react.production-18.min.js"
, "reactDOM" : "/react-dom.production-18.min.js"
} }
</script>
</head><body>
<div id="root">
<script type="systemjs-module">
System.import('react');
System.import('reactDOM');
class Hello extends React.Component {
render() {
return React.createElement('div', null, `Hello ${this.props.toWhat}`);
} }
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(React.createElement(Hello, {toWhat: 'World'}, null));
</script>
</div></body></html>
Edit1: I'm using SystemJS version 6.12.1
You need a bit more configuration to get it going. It is also recommended to keep react code in separate files.
Full working example here.
SystemJS configuration for react:
System.config({
baseURL: '//npm.jspm.io/',
// CDN resolves
paths: {
'npm:*': '//npm.jspm.io/*',
'unpkg:*': '//unpkg.com/*',
'jsdelivr:*': '//cdn.jsdelivr.net/g/*',
'jsdelivr-npm:*': '//cdn.jsdelivr.net/npm/*'
},
meta: {
'*.scss': { loader: "sass" }
},
map: {
// The Application path
'index': INDEX + '?' + Date.now(),
// SystemJS plugins
'plugin-babel': 'unpkg:systemjs-plugin-babel#0/plugin-babel.js',
'systemjs-babel-build': 'unpkg:systemjs-plugin-babel#0/systemjs-babel-browser.js',
// 'scss': 'npm:scss',
// Application modules
'react': 'jsdelivr:react#15/react.js',
'react-dom': 'jsdelivr:react#15/react-dom.js'
},
packages: {
'https://npm.jspm.io/' : { defaultExtension: 'js' },
'https://cdn.rawgit.com/*' : { defaultExtension: false },
'https://unpkg.com/' : { defaultExtension: false },
'./index.scss' : { defaultExtension: false },
},
transpiler: 'plugin-babel',
babelOptions: {
sourceMaps: false,
stage0: true,
react: true
}
});
Related
I'm using Snowpack + Svelte. After upgrading to Snowpack 3 is not working anymore and I can't configure mount in snowpack.config.js properly.
Don't understand exactly why it cannot find App.js also it's trying to find .jsx, .ts...
[404] /_dist_/screens/App.js
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="global.css">
<script type="module" defer src="_dist_/main.js"></script>
</head>
<body>
</body>
</html>
And then in my snowpack.config.js
/** #type {import("snowpack").SnowpackUserConfig } */
module.exports = {
mount: {
public: '/',
src: '/_dist_',
},
plugins: [
'#snowpack/plugin-svelte',
'#snowpack/plugin-dotenv',
],
routes: [
/* Enable an SPA Fallback in development: */
// {"match": "routes", "src": ".*", "dest": "/index.html"},
],
optimize: {
/* Example: Bundle your final build: */
// "bundle": true,
},
packageOptions: {
/* ... */
},
devOptions: {
/* ... */
},
buildOptions: {
/* ... */
},
alias: {
components: './src/components',
screens: './src/screens',
lib: './src/lib'
},
};
I also tried:
mount: {
// Same behavior as the "src" example above:
"src": {url: "/dist"},
// Mount "public" to the root URL path ("/*") and serve files with zero transformations:
"public": {url: "/", static: true, resolve: false}
},
So now it's complaining less but still not working
[snowpack] [404] /_dist_/main.js
Files structure
root
--node-modules
--public
----global.css
----index.html
--src
----components
----lib
----screens
----main.js
--snowpack.config.js
...
package.json
"devDependencies": {
"#snowpack/plugin-dotenv": "^2.0.5",
"#snowpack/plugin-svelte": "^3.5.0",
"#snowpack/web-test-runner-plugin": "^0.2.1",
"#testing-library/svelte": "^3.0.3",
"#web/test-runner": "^0.12.2",
"chai": "^4.2.0",
"smart-webcomponents": "^9.0.0",
"snowpack": "^3.0.10",
"svelte": "^3.31.2",
"svelte-i18n": "^3.3.0"
}
Any help or idea will be really appreciated.
Just add .svelte when you import your components.
import App from 'screens/App.svelte'
Please, check this https://github.com/snowpackjs/snowpack/pull/2014#issuecomment-756624333 if you wanna dive deeper.
while using the ES6 module language in nodejs it gives me an error of
" IMPORTS CANNOT BE USED OUTSIDE THE MODULE" ERROR IN CHROME BROWSER.
I am trying to build my project using Node js express mongoose morgan express-handlebars and ES6
but while I run the project it gives me an error for the same
I tried using .babelrc and webpack.config.js but not able to resolve it.
can anyone help me to achieve it?
I am putting images of my project for your reference.
Thank You
enter image description here
enter image description here
Babelrc:
{
"presets": [
["#babel/env", {
"useBuiltIns": "usage",
"corejs": "3",
"targets": {
"browsers": [
"last 5 versions",
"ie >= 8"
]
}
}]
]
}
webpack.config.js:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: ['./index.js'],
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'js/bundle.js'
},
devServer: {
contentBase: './dist'
},
plugins: [
new HtmlWebpackPlugin({
title: 'Custom template using Handlebars',
filename: 'index.html',
template: 'main.hbs'
})
],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
}
],
loaders: [
{ test: /\.hbs$/, loader: "handlebars-loader" }
]
}
};
main.js:
enter code here
import Search from './models/search';
import Movie from './models/Movie'
import User from './models/user'
import * as searchView from './views/searchView'
import * as movieView from './views/movieView'
import { elements , renderLoader, clearLoader } from './views/base'
const state = {};
const controlSearch = async () => {
// const query = searchView.getInput();
const query = 'avengers';
if (query) {
searchView.clearInput();
searchView.clearResult();
state.search = new Search(query);
state.user = new User();
searchView.clearInput();
searchView.clearResult();
renderLoader(elements.searchRes);
await state.search.getResult();
await state.user.userSignUp();
clearLoader();
console.log(state.search.result);
searchView.renderResults(state.search.result);
}
};
elements.searchForm.addEventListener('submit', e => {
e.preventDefault();
controlSearch();
});
main.hbs
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Movie Recherer</title>
<link rel="stylesheet" href="/css/bootstrap.min.css"/>
<link rel="stylesheet" href="/css/all.min.css"/>
<link rel="stylesheet" href="/css/main.css" />
<link rel="stylesheet" href="/css/home.css" />
</head>
<body>
<div class="container">
<div class="row">
{{{body}}}
</div>
</div>
<script src="/jquery.min.js"></script>
<script src="/js/bootstrap.min.js"></script>
<script language="javascript" src="/js/main.js"></script>
<script language="javascript" src="/js/models/Movie.js"></script>
<script language="javascript" src="/js/models/search.js"></script>
<script language="javascript" src="/js/views/base.js"></script>
<script language="javascript" src="/js/views/movieView.js"></script>
<script language="javascript" src="/js/views/searchView.js"></script>
</body>
</html>
You need to include you import inside a module:
Try this:
<script type="module"> import btn from './helper' </script>
Add type="module" in every script tag of your main.hbs file
I would like to display a favicon using the lib react-static-plugin-favicons.
I added it to my static.config.js :
export default {
entry: path.join(__dirname, 'src', 'index.tsx'),
getRoutes: async () => {
return [
{
path: '/',
template: 'src/containers/individuals.tsx'
}
]
},
plugins: [
require.resolve("react-static-plugin-sass"),
['react-static-plugin-typescript', { typeCheck: true }],
[
require.resolve('react-static-plugin-source-filesystem'),
{
location: path.resolve('./src/page'),
},
],
require.resolve('react-static-plugin-reach-router'),
require.resolve('react-static-plugin-sitemap'),
[
'react-static-plugin-favicons',
{ inputFile: path.resolve('./src/assets', 'favicon-32px.png') },
]
],
basePath: basepath,
Document: ({
Html,
Head,
Body,
children,
state: { siteData, renderMeta },
}) => (
<Html lang="en-US">
<Head>
<meta charSet="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</Head>
<Body>{children}</Body>
</Html>
),
}
And this is my file structure :
Can you spot what did I do wrong because it doesn't work ?
Thanks
I tried this plugin as well and could not get it to work - however adding the file as favicon.ico to the public folder worked for me as suggested at https://github.com/react-static/react-static/issues/1483.
I intend to develop an angularJS client where I will use angular components. This will lead to multiple .js/.css files.
In order to avoid manually referencing each newly added js/css file I intend to use a grunt-include-source task.
The problem is that, after configuring the Gruntfile.js, the „grunt includeSource” task runs, returning „Done, without errors.” status but no update is made in the index.html file.
My project structure is the one presented in the attached picture (I use WebStorm as IDE).
My index.html file is the following:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>RavenApp</title>
<!-- include: "type": "css", "files": "*.css" -->
</head>
<body>
<!-- bower:js -->
<script src="../bower_components/angular/angular.js"></script>
<script src="../bower_components/angular-route/angular-route.js"></script>
<script src="../bower_components/angular-sanitize/angular-sanitize.js"></script>
<script src="../bower_components/angular-mocks/angular-mocks.js"></script>
<script src="../bower_components/jquery/dist/jquery.js"></script>
<script src="../bower_components/underscore/underscore.js"></script>
<!-- endbower -->
<!-- include: "type": "js", "files": "*.js" -->
</body>
</html>
My Gruntfile.js is the following:
module.exports = function (grunt) {
grunt.loadNpmTasks('grunt-wiredep');
grunt.loadNpmTasks('grunt-include-source');
grunt.initConfig({
wiredep: {
target: {
src: 'app/index.html'
}
},
includeSource: {
options: {
basePath: 'app',
templates: {
html: {
js: '<script src="{filePath}"></script>',
css: '<link rel="stylesheet" type="text/css" href="{filePath}" />'
}
},
app: {
files: {
'app/index.html': 'app/index.html'
}
}
}
}
});
};
Could anyone indicate me what I have done wrong?
Thank you.
We don't need to write templates key under includeSource key:
module.exports = function (grunt) {
grunt.loadNpmTasks('grunt-wiredep');
grunt.loadNpmTasks('grunt-include-source');
grunt.initConfig({
wiredep: {
target: {
src: 'app/index.html'
}
},
includeSource: {
options: {
basePath: 'app',
app: {
files: {
'app/index.html': 'app/index.html'
}
}
}
}
});
};
HTML code is enough for including js and css:
<!-- include: "type": "css", "files": "*.css" -->
<!-- include: "type": "js", "files": "*.js" -->
On my book of Eric Elliot I find these three code but I can not understand like to use them:
(1)
define(['ch04/amd1', 'ch04/amd2'],
function myModule(amd1, amd2) {
var testResults = {
test1: amd1.test(),
test2: amd2.test()
},
// Define a public API for your module:
api = {
testResults: function () {
return testResults;
}
};
return api;
});
(2)
require(['ch04-amd'], function (amd) {
var results = amd.testResults();
test('AMD with Require.js', function () {
equal(results.test1, true,
'First dependency loaded correctly.');
equal(results.test2, true,
'Second dependency loaded correctly.');
});
});
(3)
if (typeof define === 'function') {
define([], function () {
return api;
});
}
I tried to use require.js and I write these codes but it doesn't work:
javascript\librerie\jquery.js
javascript\librerie\qunit.js
javascript\librerie\require.js
script_libro_eric_elliott.php
<!DOCTYPE html>
<html>
<head>
<title>Utilizzo della libreria Require.js</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script data-main="javascript/moduli" src="javascript/librerie/require.js">
</script>
</head>
<body>
<div>Utilizzo della libreria Require.js</div>
</body>
</html>
javascript\moduli\script_libro.js
define(['ch04/amd1', 'ch04/amd2'],
function myModule(amd1, amd2) {
var testResults = {
test1: amd1.test(),
test2: amd2.test()
},
// Define a public API for your module:
api = {
testResults: function () {
return testResults;
}
};
return api;
});
javascript\moduli\main.js
require(['ch04-amd'], function (amd) {
var results = amd.testResults();
test('AMD with Require.js', function () {
equal(results.test1, console.log(true),
'First dependency loaded correctly.');
equal(results.test2, console.log(true),
'Second dependency loaded correctly.');
});
});
javascript\configurazione.js
/* global requirejs */
requirejs.config({
"baseUrl": "javascript/librerie",
"paths": {
"moduli": "../moduli"
},
"shim": {
"script_libro": {
deps: ["jquery", "qunit"]
}
}
});
requirejs(["moduli/main"]);
I would like to write output strings on console so I edit Eric Elliot's script too. On my console I can only read:
Error: Script error for: moduli
http://requirejs.org/docs/errors.html#scripterror
Could you help me, please?
NEW UPDATE
I believe that the problem is in script_libro.js in fact the console find an error only in this file. I send you my new code:
script_libro_eric_elliott.php
<!DOCTYPE html>
<html>
<head>
<title>Utilizzo della libreria Require.js</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<script data-main="javascript/configurazione.js"
src="javascript/librerie/require.js">
</script>
</head>
<body>
<div>Utilizzo della libreria Require.js</div>
<div id="contenitore"></div>
</body>
</html>
javascript\moduli\script_libro.js
define(['jquery', 'qunit'], function myModule(amd1, amd2) {
var testResults = {
test1: amd1.test(),
test2: amd2.test()
},
api = {
testResults: function () {
return testResults;
}
};
return api;
});
javascript\moduli\main.js
require(['javascript/moduli/script_libro.js'], function (amd) {
var results = amd.testResults;
test('AMD with Require.js', function () {
equal(results.test1, true,
console.log('First dependency loaded correctly.'));
equal(results.test2, true,
console.log('Second dependency loaded correctly.'));
});
});
javascript\configurazione.js
require.config({
baseUrl: 'javascript/librerie',
urlArgs: "bust=" + (new Date()).getTime(),
paths: {
CartellaModuli: '../moduli',
},
shim: {
script_libro: {
deps: ['qunit', 'jquery']
}
}
});
require(['CartellaModuli/main']);
Your data-main should point to a module instead of a directory. Try changing it to data-main="javascript/moduli/main".
That probably won't solve everything since you don't include your configuration in configurazione.js anywhere.