reactjs project load javascript libraries and attach to window object - javascript

I would like to add some javascript libraries to my reactJS project.
I do this by adding script tags to the section of index.html
<script src="../src/components/reports/scripts/stimulsoft.reports.js"></script>
<script src="../src/components/reports/scripts/stimulsoft.viewer.js"></script>
and usage of library is like:
class Viewer extends React.Component {
render() {
return <div id="viewerContent"></div>;
}
componentWillMount() {
var report = Stimulsoft.Report.StiReport.createNewReport();
report.loadFile("reports/Report.mrt");
var options = new Stimulsoft.Viewer.StiViewerOptions();
this.viewer = new Stimulsoft.Viewer.StiViewer(options, "StiViewer", false);
this.viewer.report = report;
}
componentDidMount() {
this.viewer.renderHtml("viewerContent");
}
}
but I have this error:
these are original sample Stimulsoft Reports.JS and GitHub

Based on comments under the question, and the guides presented in index.html file of react project as follows:
//Notice the use of %PUBLIC_URL% in the tags above.
//It will be replaced with the URL of the `public` folder during the build.
//Only files inside the `public` folder can be referenced from the HTML.
I placed scripts folder into the public folder of react project and edit src attribute to new source address, and my problem was solved
and this code work for me:
<script src="%PUBLIC_URL%/StimulSoft/scripts/stimulsoft.reports.js"></script>
<script src="%PUBLIC_URL%/StimulSoft/scripts/stimulsoft.viewer.js"></script>

Related

Stencil custom page javascript not firing

I'm trying to create a custom web page in stencil website and trying to add custom javascript module.
This is the html file named '/templates/pages/custom/page/customz.html'
{{~inject 'template' template}}
<h2>Hello World!</h2>
<body>
Some custom content!
<body>
<script>window.__webpack_public_path__ = "{{cdn 'assets/dist/'}}";</script>
<script src="{{cdn 'assets/dist/theme-bundle.main.js'}}"></script>
<script>window.stencilBootstrap("{{page_type}}", {{jsContext}}).load();</script>
This is the javascript file named '/asset/js/theme/customz.js'
import PageManager from './page-manager';
export default class Customz extends PageManager {
onReady() {
console.log('onReady');
}
constructor(context) {
super(context);
console.log(context);
}
}
then i added this in app.js file
const customClasses = {
'pages/custom/page/customz': () => import('./theme/customz')
};
and also added it .stencil file to test it locally
I also created the web page in bigcommerce dashboard.
The problem i have is that the HTML is loaded but the Javascript file is not injected (i cannot see the console log strings in console or other js logic i insert).
Where can be the problem?
The place I usually start when troubleshooting a custom template is the related section on the BigCommerce Dev Center here: https://developer.bigcommerce.com/stencil-docs/storefront-customization/custom-templates#troubleshooting-template-authoring
If you've verified the version of the Stencil CLI and URL you're using, try using this same code with the base Cornerstone theme on the latest version.
you need add link for Windows too:
Look like:
const customClasses = {
'pages/custom/page/customz': () => import('./theme/customz'),
'pages\\custom\\page\\customz': () => import('./theme/customz')
};
And your custom page must contains:
`{{~inject 'template' template}}
<script>window.__webpack_public_path__ = "{{cdn 'assets/dist/'}}";</script>
<script src="{{cdn 'assets/dist/theme-bundle.main.js'}}"></script>
<script>window.stencilBootstrap("{{page_type}}", {{jsContext}}).load();</script>`
If don`t connection on base file from layout.

Is it possible to serve Static files with create-react-app from public folder?

Basically I made a (relatively) simple app for a client. The app works and all but they keep asking for changes to the data.
Given the originally anticipated simplicity of the app and the fact it held static data, i did not link it to any back end.ll the data lives in a local static file with an object holding the data.
The problem is that fle gets bundled into the buld, so if i want to just change some static data without having to rbuild, i can't!
I have assets that my data file can access inside the public folder, and those are working fine. I was trying to achieve the same idea with a js file.
I canot import from outside the /src folder.
Is there a way i can access static data from the static folder that gets added on build somehow?
Yes, you can place assets in the static folder.
Docs: Using the Public Folder
You can reference the path in index.html with %PUBLIC_URL%/path/resource.
You can use process.env.PUBLIC_URL + '/path/resource' in javascript code.
Both of these approaches are replaced at build time for your final build.
If these are javascript assets, the build will not be aware of them. You need to structure it as an external javascript library and store them in a global variable that you can reference within your code. Then you can load that javascript library in your index.html
Say you wanna read json file containing data, you could do it in the following way:
class App extends Component {
async getData() {
const res = await fetch("/json/sample.json");
const data = await res.text();
console.log(data);
return this.setState({ data });
}
componentDidMount() {
this.getData();
}
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<div>{this.state.data}</div>
</header>
</div>
);
}
}
Where the json folder is created inside public folder. Anything that you put within public folder is served automatically when using create-react-app. Hope this helps.

Reference relative path inside JS config file in MVC

I'm trying to incorporate this scanning software into an application.
The folder which contains all the necessary .js, .css and binary files is called Resources.
In my MVC app - I have placed the Resources file inside my Scripts folder.
In my .cshtml, I have the following:
#section scripts {
<script src="~/Scripts/Resources/dynamsoft.webtwain.config.js"></script>
<script src="~/Scripts/Resources/dynamsoft.webtwain.initiate.js"></script>
}
Which loads the scripts successfully.
The issue I'm facing is the scripts themselves reference relative paths within the Resources folder.
In dynamsoft.webtwain.config.js - you can set the path to the resources folder - I have mine set to the following:
Dynamsoft.WebTwainEnv.ResourcesPath = '~/Scripts/Resources';
However when the page loads - I'm receiving 404 errors for some of the files because it's trying to literally interpret the path:
I have also tried the following but with no luck:
Dynamsoft.WebTwainEnv.ResourcesPath = '#Url.Content("~/Scripts/Resources")';
As far as I know you can't use relative paths starting with tilde (~) in separate JS files because #Url.Content() helper and ASP.NET relative paths only work inside Razor view page, but you can pass the relative path by creating root path in JS global scope (i.e. Razor view page's <script> tag) like this:
<script>
var baseUrl = '#Url.Content("~")';
</script>
Then you can include the path inside JS files using that variable:
// custom JS file
if (typeof baseUrl !== 'undefined') {
Dynamsoft.WebTwainEnv.ResourcesPath = baseUrl + '/Scripts/Resources';
}
Or simply mentioning full path & pass it:
#* Razor page *#
<script>
var resourcesPath = '#Url.Content("~/Scripts/Resources")';
</script>
// custom JS file
if (typeof resourcesPath !== 'undefined') {
Dynamsoft.WebTwainEnv.ResourcesPath = resourcesPath;
}
Another alternative is using custom JS view engine together with file handler for JS scripts like example below:
// custom JS engine
public class CustomJSEngine : BuildManagerViewEngine
{
public CustomJSEngine()
{
ViewLocationFormats = new[]
{
"~/Scripts/{0}.js",
"~/Scripts/Resources/{0}.js"
};
FileExtensions = new[]
{
"js"
};
}
protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
{
var view = new RazorView(controllerContext, viewPath,
layoutPath: masterPath, runViewStartPages: true, viewStartFileExtensions: FileExtensions,
viewPageActivator: ViewPageActivator);
return view;
}
}
// put these lines below inside Application_Start()
RazorCodeLanguage.Languages.Add("js", new CSharpRazorCodeLanguage());
ViewEngines.Engines.Add(new CustomJSEngine());
// add this line if necessary
WebPageHttpHandler.RegisterExtension(".js");
References:
#Url.Content in separate javascript file using ASPNET MVC 3 and Razor
Returning razor-parsed Javascript as a ViewResult from a controller

Importing tracking.js into an angular project

I have downloaded tracking.js and added it to my /src/assets folder
In my angular-cli.json file I have added to my scripts:
"scripts": [
"../src/assets/tracking/build/tracking-min.js"
],
issue here - In my angular component, I import tracking as follows:
import tracking from 'tracking';
and in the chrome inspection window I can hover over 'tracking' and see all of the properties as shown:
I can even call the ColorImage constructor in the console window! :
However when it tries to execute the constructor in my code I get the error about tracking being undefined:
I had assumed it was because I wasn't passing in the tracking object through the constructor in the traditional DI fashion, but when doing so I got the error that the namespace couldn't be used as a type:
The only other thing I could think of was to try and add the external reference in the main index.html file, but I got an error about strict MIME checking.
To clarify: this is all happening in my angular component constructor (when the tracking methods get exercised)
Any ideas?
go to your node_modules folder and find this file : "node_modules/tracking/build/tracking.js" . open the file and add this line of code to end of the file :
module.exports = window.tracking
save file and in use this code to import it :
import * as tracking from 'tracking';
I don't think you can use DI with that external library. However, you should be able to create a new instance in the constructor:
import tracking from 'tracking';
constructor(...) {
this.colors = new tracking.ColorTracker(...);
}
myFunction() {
this.colors.doWhateverIWant();
}
If you only want a single tracking instance throughout your app, then you'll have to create your own trackingService and inject that.
another solution is to reference the tracking.js via script tag :
<html>
<head></head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tracking.js/1.1.3/tracking-
min.js"></script>
</body>
</html>
and in your component.ts write :
(window as any).tracking.ColorTracker(["magenta"]);

How to dynamically load and initialize a module with webpack

Here is the setup of a website I'm working on:
I have multiple types of pages. Each page have a (known) number of js views(components), encapsulated in modules. For each page type I create its own entry point. Previously I used RequireJS and rjs for bundling, so I had a special module (called 'loader'), which could load and initialize each view.
So basically, I have such a structure
-news.js
-homepage.js
-components
|
-header.js
-menu.js
-search.js
-article.js
-loader.js
and my news.js is
require('components/header');
require('components/search');
require('components/article');
var loader = require('components/loader');
loader.initAll();
and my homepage.js is
require('components/header');
require('components/search');
require('components/menu');
var loader = require('components/loader');
loader.initAll();
Each component looks like
<div class="js-component" data-component="components/article"></div>
And inside loader.js I would like to see something like
module.exports = {
initAll: function () {
// get all components on the page
var components = document.querySelectorAll('.js-component');
components.forEach(function(component) {
component.name = component.getAttribute('data-component');
// next is obviously not working with webpack, but is what I need
require(component.name).init();
})
}
}
How should I organize this with webpack?

Categories