How To Configure TypeScript and Require in Visual Studio 2017 - visual-studio

Even though this talks about VueJS. I suspect it will work with any other JavaScript language like Angular or React as well.
I have been learning Vue.js and loving it. Knowing I have a larger application on the way and the fact that I have wanted to start using TypeScript. Now seems like the time to do so. I have a firm grasp on Vue at this point but can not find any documentation (over 2 weeks of finding the exact, MINIMUM requirements) on how to setup TS and actually get it to run.
Here is an example of some HTML and Vue code that works with using just script tags and normal JavaScript.
HTML
<div id="app">
<h4>{{ Value }}</h4>
</div>
#section Scripts {
<script src="~/lib/vue/vue.js"></script>
<script src="~/js/test.js"></script>
}
JavaScript - test.js
var app = new Vue({
el: "#app",
data: {
Value: "Hello there"
}
});
This works and produces Hello there on the page.
Configuring TypeScript
This seems straight forward, I have a TypeScripts folder below my js folder where the "source" .ts files will be. The output files will be in the js folder as .js files. Here is my tsconfig.json located in the TypeScripts folder:
{
"compileOnSave": true,
"compilerOptions": {
"noEmitOnError": true,
"noImplicitAny": false,
"outDir": "../",
"removeComments": false,
"sourceMap": true,
"target": "es5",
"module": "amd" // <-- Should this be used?
},
"exclude": [
"node_modules",
"wwwroot"
]
}
This works and I do get .js files each time a save the .ts files.
However, now I want to incorporate Vue into the .ts using it in ways I have seen in videos as well as code online. The following code compiles without errors:
JavaScript - ES6 - test2.ts
const Vue = require("vue")
const app = new Vue({
el: "#app",
data: {
Value: "Hello there"
}
})
Now I update the HTML to the following:
HTML
<div id="app">
<h4>{{ Value }}</h4>
</div>
#section Scripts {
<script src="~/js/test2.js"></script>
}
I reload the page and all I get is the {{ Value }} markup. Plus the JavaScript error: Uncaught ReferenceError: require is not defined.
That seems simple enough, I figure I just add the following line to the Scripts section and remove the single reference to the test2.js file:
#section Scripts {
<script src="~/lib/require.min.js" data-main="/js/test2.js"></script>
}
Reload and now I get: Uncaught Error: Module name "vue" has not been loaded yet for context: _. Use require([]) which references this but that code now seems to diverge from what the .ts file should look like.
The ES6 Test2.ts file seems to be the way people code. The way it wants me to write the require statement in the link above seems far more verbose and does not show up in any code samples I have seen. So I must be missing something. If it helps, the Vue and Require downloads have come from my package.json (npm) file which looks like this:
"devDependencies": {
"#types/node": "^9.4.7",
"requirejs": "^2.3.5",
"vue": "^2.5.16"
...
}
And my bundleconfig.json which puts them in the wwwroot/lib folders where they should go.
{
"outputFileName": "wwwroot/lib/require.min.js",
"inputFiles": ["node_modules/requirejs/require.js"]
},
{
"outputFileName": "wwwroot/lib/vue/vue.js",
"inputFiles": [ "node_modules/vue/dist/vue.js" ]
}
I have to believe I am so close to getting it. Being able to write code in the more modern ES versions is great. I have just not been able to find the right piece of the puzzle to fit it all together.

The main problem above is because in the first "plain JavaScript" example, you are not using modules at all. You are loading the Vue library directly in your page, which creates the global Vue object, and then your script is global (i.e. not a module) and references the Vue object directly.
For the test2.ts file, you mention this is ES6, but you then 'require' in the Vue library. This means the code is now attempting to use modules, but CommonJS modules, not ES6 modules. (Where you would write something like import Vue from "vue"). This means it would require a loader at runtime (e.g. the require.js library you are trying to use), which could work if configured correctly, but generally you'd want something like WebPack to package up Vue.js and your code into a standalone bundle the page loads at runtime.
Note: Edited paragraph below
I've created a sample ASP.NET Core project showing how to configure TypeScript and WebPack to generate a bundle per page using the global Vue.js object via a script tag. I've put an extensive readme on it to explain all the workings. You can see it at https://github.com/billti/SimpleVueApp . If you have further feedback, I'll continue to update it to make it better/clearer.
That said, as you get deep in Vue there is one Visual Studio limitation to be aware of. Currently there is no rich support for .vue files (known in the docs as "single file components"). What I mean by "rich support", is that these files have a certain context that we don't infer right now to provide good IntelliSense (i.e. completion lists, errors, tooltips, etc.). Also, HTML files in Visual Studio (which is what you would open a .vue files as) also only support plain CSS in <style> tags, and plain JavaScript in <script> tags currently, whereas with the right Vue and WebPack setup you can do things like write LESS code directly in your style tags, and write TypeScript directly in your script tags. My team is looking at this currently and hoping to improve this in the near future.
Let me know if any of that isn't clear. Happy to help further.

Related

Adding SASS modules to Netlify CMS custom preview breaks Gatsby

Summary
The project works without issues with SASS modules.
Trying to use SASS inside src/cms/cms.js for the purposes of customizing the CMS admin preview panel breaks the project.
Using regular CSS or CSS modules works without any problem for the admin preview panel.
I've checked for this issue on GitHub, the Netlify CMS forums and documentation, Stack Overflow, and everywhere that Google has led me.
Describe the bug
My project uses Netlify CMS and Gatsby. I have no issues with SASS when working on the project. The issue only comes up when I try to use SASS inside components that I want to use as custom preview with CMS.registerPreviewTemplate() for the CMS Admin panel at http://localhost:8000/admin/.
I've setup up everything without any issues and there are no problems when I use CSS modules.
The problem is that my project uses SASS and when I just rename import * as styles from PreviewTesting.module.css to import * as styles from './PreviewTesting.module.scss' inside PreviewTesting.jsx I get this error:
ERROR Failed to compile with 1 error 6:03:26 PM
⠀
error in ./src/templates/previewTesting/PreviewTesting.module.scss
⠀
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See
https://webpack.js.org/concepts#loaders
> .previewTestingDescription {
| background-color: lightgoldenrodyellow;
| font-family: 'Montserrat-Regular', sans-serif;
Also, just adding import '../styles/global.scss' inside the src/cms/cms.js file causes the same error that prevents the build from happening.
I've tried updating and downgrading any package I could think of and this did not help. I've also tried to register the files as preview styles with CMS.registerPreviewStyle(file); and I've tried Raw CSS with https://www.netlifycms.org/docs/beta-features/#raw-css-in-registerpreviewstyle. None of these solved the issue.
To Reproduce
Steps to reproduce the behavior. For example:
Create a React component.
Import a SASS module component into the React component.
Register that component as a preview component with CMS.registerPreviewTemplate('name', PreviewTesting) inside src/cms/cms.js
An alternative way to reproduce:
Add import '../styles/global.scss' inside the src/cms/cms.js. global.scss hold regular SASS things like imports for fonts, variable and other such things.
Expected behavior
The project should run and apply the CSS styling to the preview panel at http://localhost:8000/admin/
Screenshots
Applicable Versions:
"gatsby": "^4.9.0"
"gatsby-plugin-netlify-cms": "6.25.0"
"gatsby-plugin-sass": "5.25.0"
"netlify-cms-app": "^2.15.72"
"sass": "1.49.9"
"gatsby": "^4.9.0" (updated to the latest version "4.25.1")
Node.JS version:
Did not work on v16, updated to v18.12.1, still does not work.
CMS configuration
collections:
- name: "name"
label: "names"
label_singular: "name"
description: >
Test
create: true
slug: "{{category}}-{{slug}}"
fields:
- { name: title, label: Title }
- { name: subtitle, label: Subtitle, required: false }
Additional context
Any help would be very appreciated.
A friend of mine provided me with a solution:
The plugin order in gatsby-config.js actually matters in this case. gatsby-plugin-sass must come before gatsby-plugin-netlify-cms
The plugin segment in gatsby-config.js should look like this:
{
resolve: 'gatsby-plugin-sass',
options: {
additionalData: '#use "/src/styles/global" as *;',
sassOptions: {
includePaths: ['src/styles'],
},
},
},
{
resolve: 'gatsby-plugin-netlify-cms',
options: {
modulePath: `${__dirname}/src/cms/cms.js`,
},
},

Laravel, Datatable, Composer and Webpack : Good practices to allow developpers to customize my library in their projects

To set the context I am creating a CRUD application for Laravel. It is installed via composer and the sources are therefore in the vendor/organization/package directory.
In my project, I use Datatable. So I use Laravel Mix to compile my sources and a command line allows to copy JS and CSS compiled files into the public directory of the Laravel Host application.
I would like however that the developers who will use my library can customize the display of some Datatable cells. To do this you must use Datatable's createdCell configuration.
$('#example').dataTable( {
"columnDefs": [ {
"targets": 3,
"createdCell": function (td, cellData, rowData, row, col) {
if ( cellData < 1 ) {
$(td).css('color', 'red')
}
}
} ]
});
The problem is that the JS sources of my project are already compiled...
For the moment I found a temporary solution that consists in leaving the JS sources in vendor/organization/package but copying the webpack.mix.js configuration into the Host application and asking the developers to compile themselves. The problem is that all JS dependencies must also be installed and it doesn't take very seriously to force the developers to compile sources before being able to use my library.
What are good practices to achieve this objective?
The following source may help, but I confess I don't know how to apply it to Laravel:
How to bundle vendor scripts separately and require them as needed with Webpack?
Thank you for your help.

Vuejs 2 + laravel elixir + lodash Uncaught ReferenceError: _ is not defined

I'm using the tools specified in the title. I import lodash in my bootstrap.js
window._ = require('lodash');
However, when I try to use something like this (similar example to here), I get the error discribed in the title
created() {
this.test();
},
methods: {
test: _.debounce(function () {
console.log('calculating', true);
setTimeout(function () {
console.log('calculating', false);
}.bind(this), 1000)
}, 500),
}
However, if I remove the window._ = require('lodash'); and insert lodash manually in the page it works fine, like
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.js"></script>
What I'm missing?
Also, What is the advantage of importing the libraries by require instead of using Gulp to merge and uglyfy everything?
I am not sure why you are getting that error related to _.
On your other question, I can think following advantage of using require over gulp or any other build tool:
All build tools comes with their own set of dependencies and other accessories, which bloats your overall code size.
You may start to rely on their plugins and time can come, when you need to use grunt for one task, while for other tasks you are using grunt, quting from gulp-grunt
What if your favorite grunt plugin isn't available for gulp yet? Don't fret, there is nothing to worry about! Why don't you just hook in your grunt configuration?
You will have to manage updating of different plugins of gulp and make sure all are working with new updated versions.
These are some of the things I have experienced or read about, but these tools do remove the pain of building, hot-reloading, compressing or obfuscating your code, but definetely there can be other raw way to do these, as what these are doing is providing you an abstraction.

js in html is not executing in Phoenix framework sample app

I'm playing around with the phoenix framework. I copied the chat example entirely but I'm not getting any results.
In fact when I write console.log("testing") in my app.js I notice that my console does not log anything...
I am getting the error referenced in this link:
phoenix framework - invalid argument at new Socket - windows
However that error seems to be related to Brunch not working in windows. When I brunch build, I can confirm that app.js has the console.log("testing") that I included.
Nevertheless, I don't see that console log when I visit my localhost:4000.
Why is JS not executing?
Turns out the guide is missing a key line that made it not work.
The guide has the following:
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="<%= static_path(#conn, "/js/app.js") %>"></script>
</body>
But that is missing the below line which you can put above the body tag.
<script>require("web/static/js/app")</script>
Even as Chowza already solved this question I would like to propose another, possible cleaner solution, using the autoRequire feature of Brunch.io.
The problem occurs because Brunch.io does not autoRequire the app.js under Windows correctly. Chowza worked around this issue by requiring the file manually in the html. You can omit the manual require if you alter the /brunch-config.js as follows: Change from
modules: {
autoRequire: {
"js/app.js": ["web/static/js/app"]
}
}
To
modules: {
autoRequire: {
"js/app.js": ["web/static/js/app"],
"js\\app.js": ["web/static/js/app"]
}
}
This way the app.js is autoRequired, even if you work on a Windows based system.
I would like to mention, that this solution is based on the link Chowza himself posted, so all credit goes to him for pointing to the link.

Simple ajax/prototype problem

im beginning with Ajax, i have problem with including Ajax files.
Ajax code written in original page (like index.php) and placed in (head) section works fine, but when i try to place code in external file (in js folder, where is placed prototype.js file), i don't get any response, not even in Firefox Error Console.
I haven't changed Ajax code except url for calling PHP function.
edit:
calling ajax files:
<script type="text/javascript" src="js/prototype.js"></script>
<script type="text/javascript" src="js/myValidation.js"></script>
</head><body>
....
Username: <input type="text" name="uname" id='uname' />
Available?
<span id="result"></span>
Email address: <input type="text" name="email" />
...
I embaded this function call in html. Validate function is from book "PHP and Script.aculo.us Web 2.0 app interfaces"
myValidation.js
function Validate(){
var user=$('uname');
var name="uname="+user.value;
var pars=name;
new Ajax.Request(
'myValidation.php',
{
method:'post', parameters:pars, asynchronous:true, onComplete: showAvailable
}
);
}
function showAvailable(originalRequest){
var newData=originalRequest.responseText;
$('result').innerHTML=newData;
}
This example is from mentioned book
You haven't shown us your myValidation.js file, but here are the typical reasons I see when people move from inline script blocks to external files and things stop working:
They put script blocks in the external JavaScript files. You probably didn't do that, but I've seen it often enough to mention it. Your external script is pure JavaScript, so for instance it should be:
function Validate() {
// ...
}
not:
<script type='text/javascript'>
function Validate() {
// ...
}
</script>
I've seen the latter a fair bit.
They put the JavaScript file in a location that doesn't match their script tag src.
They left an opening <!-- or closing --> in the script. Important not to do that, in external JavaScript files those are syntax errors.
They're using a web server that's case sensitive and the src attribute and the file's actual name don't match.
They're using a web server sensitive to permissions and the file doesn't have the right permissions.
In the case of the last two above, it's easy to check: Just open a new tab and actually enter the URL of the JavaScript file. If you see the JavaScript, great; if not, you probably have more information.
For issues like this (and hundreds of others), there's nothing like having a decent toolset. For debugging JavaScript on browsers, there are quite a few. There's Firebug (a Firefox add-in), Chrome's and Safari's Development Tools (built into the browsers), Microsoft Visual Studio or Script Debugger for debugging with IE, etc. Firebug and Dev Tools would both tell you about broken src links, as well as any exceptions, etc.
Have you checked that those files are accessible from the HTML code? And more - have you placed you scripts in the bottom of the page - because AJAX will bind it's handlers only to existing elements?
Problem solved.
In /js/ folder i had one php file, that i put there just because of simplicity. After moving it to other location all worked. Don't know if that is rule, nut no php files in /js/ folder. Thanks T.J and Tomasz

Resources