I have made a fresh blazor serverside app. And I have created a tsconfig.json and JS/src folder in my project folder. In Terminal, I have used npm init -y in my JS folder. Node modules can now be installed. I installed webpack and created a webpack.config.js file in my JS folder. Then I create a simple ts file with an alert function. After configuring my tsconfig.json in my project root, I added <script src="js/bundle.js"></script> to my _Layout.cshtml. And then in my index.cshtml page I added a button and some code to call the compiled bundle.js from webpack, located in wwwroot/js/.
I cannot see the function in my bundle.js file. What have I done wrong?
Folder structure:
tsconfig.json:
{
"compilerOptions": {
"noImplicitAny": false,
"noEmitOnError": true,
"removeComments": false,
"sourceMap": true,
"target": "ES2017",
"moduleResolution": "Node"
},
"exclude": [
"node_modules"
],
"include": [
"./JS/src/*.ts"
]
}
webpack.config.js:
const path = require('path');
module.exports = {
entry: './src/index.ts',
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude:/node_modules/,
},
],
},
resolve: {
extensions: ['.ts', '.js'],
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, '../wwwroot/js'),
},
};
index.ts:
function showAlert() {
alert("this is a test");
}
package.json:
{
"name": "js",
"version": "1.0.0",
"description": "",
"main": "webpack.config.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"ts-loader": "^9.2.6",
"typescript": "^4.5.5",
"webpack-cli": "^4.9.2"
}
}
Ok so after some struggling I figured out that I need to expose the function as a library.
In webpack.config.js:
const path = require('path');
module.exports = {
entry: './src/index.ts',
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude:/node_modules/,
},
],
},
resolve: {
extensions: ['', '.js', '.ts']
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, '../wwwroot/js'),
libraryTarget: 'umd',
library: 'EntryPoint'
},
};
Take note of the library and library target in the output section. I am not entirely sure whether var umd const or let is better for the library target, as I am not sure what UMD is. however it seems to work with either.
Here is my updated index.ts file:
import { Calculator } from "./calculator";
export function showAlert() {
console.log("Hello world");
alert("this is a test");
}
export let foo = new Calculator();
let bar = new Calculator();
Notice how foo and showAlert have export in front. This is required. Bar is not accessible.
Related
I have some issues with unbound breakpoints in VS Code. My project structure is as follows:
mittfast2 - Project root
|_webapp
|_.vscode
|_launch.json
|_src
|_java
|_resources
|_webapp - React components etc.
|_index.js
|_node_modules
|_package.json
My package.json has the following scripts:
"scripts": {
"start": "webpack serve --mode development",
"deploy": "NODE_ENV=production webpack -p --config webpack.production.config.js",
"build": "webpack --mode production",
"test": "jest",
"test:coverage": "jest --coverage",
"test:watch": "jest --watch --coverage"
}
I run with "npm start" and visit http://localhost:3000. Inspecting the sources gives me this:
I can successfully use the built in debugger in Chrome by adding and hitting breakpoints.
But when I add breakpoints in IntelliJ and run my debug launcher, they are all "Unbound breakpoint". This is my launch.json:
{
"version": "0.2.0",
"configurations": [
{
"name": "WSL Chrome",
"type": "pwa-chrome",
"request": "launch",
"url": "http://localhost:3000",
"webRoot": "${workspaceFolder}/src",
"sourceMapPathOverrides": {
"webpack:///./src/*": "${webRoot}/*",
"webpack:///src/*": "${webRoot}/*"
}
}
]
}
I believe something is wrong with my launch.json, specifically when I map my sources.
This is my webpack.config.js in case it is of interest:
const path = require('path')
/* Utilities */
const webpackHtml = require('html-webpack-plugin')
const webpackBundleAnalyzer = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
module.exports = {
entry: ['./src/main/webapp/index'],
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: [
'babel-loader',
'eslint-loader',
]
},
{
test: /\.html$/,
use: [
{
loader: 'html-loader'
}
]
},
{
test: /\.(s*)css$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'sass-loader'
]
},
{
test: /\.(ico|jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2)(\?.*)?$/,
loader: 'file-loader',
options: {
name: 'fonts/[name].[ext]?[hash:8]',
}
}
]
},
plugins: [
new webpackHtml({
hash: true,
template: './src/main/webapp/index.html',
filename: 'index.html'
}),
new webpackBundleAnalyzer({
openAnalyzer: false
}),
new MiniCssExtractPlugin({
filename: 'style.css'
})
],
devServer: {
port: 3000,
hot: true,
historyApiFallback: true,
proxy: {
'/resources/*': {
target: 'http://localhost:8080/fenix/',
secure: false,
onError: error => { console.log('::PROXY ERROR::', error) }
}
}
},
resolve: {
alias: {
'#actions': path.resolve(__dirname, 'src/main/webapp/actions'),
'#components': path.resolve(__dirname, 'src/main/webapp/components'),
'#gui': path.resolve(__dirname, 'src/main/webapp/gui'),
'#functions': path.resolve(__dirname, 'src/main/webapp/functions'),
'#middleware': path.resolve(__dirname, 'src/main/webapp/middleware'),
'#reducers': path.resolve(__dirname, 'src/main/webapp/reducers'),
'#styles': path.resolve(__dirname, 'src/main/webapp/styles'),
}
}
}
Given my project structure, can anyone see why my launch.json is incorrect and suggest improvements to successfully bind the breakpoints?
I hope this question contains all the information needed. Otherwise, please suggest improvements and I will happily edit the question.
Thanks!
There is only one line in my index.ts file.
export * from "./foo"
There is only one line in foo.ts file too.
export const foo = ()=> 'bar'
I'm only using default config from "npx webpack-cli init".
Only "mode" and "output" are edited.
const TerserPlugin = require('terser-webpack-plugin');
module.exports = {
mode: 'production',
entry: './src/index.ts',
output:{
filename:'index.js'
},
plugins: [new webpack.ProgressPlugin()],
module: {
rules: [{
test: /\.(ts|tsx)$/,
loader: 'ts-loader',
include: [path.resolve(__dirname, 'src')],
exclude: [/node_modules/],
options:{
transpileOnly: true
}
}]
},
resolve: {
extensions: ['.tsx', '.ts', '.js']
},
optimization: {
minimizer: [new TerserPlugin()],
splitChunks: {
cacheGroups: {
vendors: {
priority: -10,
test: /[\\/]node_modules[\\/]/
}
},
chunks: 'async',
minChunks: 1,
minSize: 30000,
name: false
}
},
target:"web"
}
And here is my tsconfig.js
{
"compilerOptions": {
"allowSyntheticDefaultImports": false,
"noImplicitAny": true,
"module": "es6",
"target": "es5",
"allowJs": false,
"sourceMap": true
}
}
Here is my package.json
{
"name": "npm",
"version": "1.0.0",
"description": "",
"main": "dist/index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack"
},
"author": "",
"license": "ISC",
"devDependencies": {
"#webpack-cli/init": "^1.0.3",
"babel-plugin-syntax-dynamic-import": "^6.18.0",
"terser-webpack-plugin": "^5.0.3",
"ts-loader": "^8.0.12",
"typescript": "^4.1.2",
"webpack": "^5.10.0",
"webpack-cli": "^4.2.0"
}
}
With these when I run build
"build": "webpack"
I got an empty index.js in "dist/index.js".
What am I missing?
I think the problem is here all about to remove unused export of webpack. Keep in mind that webpack is able to do this unless the input code passed to it must be esm style as same as you've done by configured module: "es6".
In case of exporting as library, you might have to tell webpack to build as library by specifying target or even could add a name:
webpack.config.js
{
output: {
library: "yourLibName",
libraryTarget: "umd",
filename: "index.js"
},
}
I cannot get ReactDOM.render(...) to accept any JSX tag, however if I use React.createElement(...) it works.
This is my index.jsx file:
import React from "react";
import ReactDOM from "react-dom";
// THIS WORKS!
//var elem = React.createElement('h1',{},"Hello");
//ReactDOM.render(elem, document.getElementById("content"));
// THIS DOESN'T WORK!
ReactDOM.render(<h1>Hello World!</h1>, document.getElementById("content"));
In the index.html file there is a div with id="content" somewhere.
This is my package.json file:
{
"name": "static",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack -p --progress --config webpack.config.js",
"dev-build": "webpack --progress -d --config webpack.config.js",
"watch": "webpack --progress -d --config webpack.config.js --watch"
},
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/preset-env": "^7.4.5",
"#babel/preset-react": "^7.0.0",
"webpack": "^4.35.0",
"webpack-cli": "^3.3.5"
},
"presets": [
"#babel/preset-env",
"#babel/preset-react"
]
}
This is my webpack.config.js file:
const webpack = require('webpack');
const config = {
entry: __dirname + '/js/index.jsx',
output: {
path: __dirname + '/dist',
filename: 'bundle.js',
},
resolve: {
extensions: ['.js', '.jsx', '.css']
},
};
module.exports = config;
module: {
rules: [
{
test: /\.jsx?/,
exclude: /node_modules/,
use: 'babel-loader'
}
]
}
The error I am getting is:
ERROR in ./js/index.jsx 11:16
Module parse failed: Unexpected token (11:16)
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
|
|
> ReactDOM.render(<h1>Hello World!</h1>, document.getElementById("content"));
|
==============================================
Solution:
1st of all the webpack.config.js was wrong (see accepted answer).
After, I had to install babel-loader with npm install -D babel-loader #babel/core #babel/preset-env webpack and then created .babelrc file at the same path of the other config. files, with the content:
{
"presets": ["#babel/preset-env", "#babel/preset-react"]
}
You are placing the rules in the wrong place.
the correct config is:
const webpack = require('webpack');
const config = {
entry: __dirname + '/js/index.jsx',
output: {
path: __dirname + '/dist',
filename: 'bundle.js',
},
resolve: {
extensions: ['.js', '.jsx', '.css']
},
module: {
rules: [
{
test: /\.jsx?/,
exclude: /node_modules/,
use: 'babel-loader'
}
]
}
};
module.exports = config;
I am learning react and here is my simple project sturcture:
my_project
--node_modules
--index.js
--index.html
--package.json
--.babelrc
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="root"></div>
<script src="index.js"></script>
</body>
</html>
index.js
import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('root')
);
package.json
{
"name": "my_project",
"version": "1.0.0",
"description": "frontend using react js",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "babel src -d dist"
},
"scripts": {
"build": "babel --presets es2015 -d dist"
},
"author": "kishan",
"license": "ISC",
"dependencies": {
"react": "^15.4.2",
"react-dom": "^15.4.2"
},
"devDependencies": {
"babel-cli": "^6.23.0",
"babel-core": "^6.23.1",
"babel-loader": "^6.4.0",
"babel-preset-es2015": "^6.22.0",
"babel-preset-react": "^6.23.0",
"webpack": "^2.2.1"
},
"babel": {
"plugins": ["transform-react-jsx"],
"ignore": [
"foo.js",
"bar/**/*.js"
]
}
}
webpack.config.js
var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
config = {
context: __dirname,
devtool: debug ? "inline-sourcemap" : null,
entry: "./index.js",
output: {
path: __dirname + "/build",
filename: "bundle.js"
},
plugins: debug ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
],
};
module.exports = config;
I am getting following error in console in browser for index.js line 1:
Uncaught SyntaxError: Unexpected token import
Please help me what is wrong with this code?
You forgot to define the babel-loader in webpack file, put this part:
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}
]
}
Use this webpack file:
var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
var config = {
context: __dirname,
devtool: debug ? "inline-sourcemap" : null,
entry: "./index.js",
output: {
path: __dirname + "/build",
filename: "bundle.js"
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}
]
},
plugins: debug ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
],
}
module.exports = config;
Update:
From Webpack Doc:
When using watch mode, webpack installs file watchers to all files,
which were used in the compilation process. If any change is detected,
it’ll run the compilation again. When caching is enabled, webpack
keeps each module in memory and will reuse it if it isn’t changed.
Add babel-loader in webpack to transpile jsx or js
var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
config = {
context: __dirname,
devtool: debug ? "inline-sourcemap" : null,
entry: "./index.js",
output: {
path: __dirname + "/build",
filename: "bundle.js"
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}
]
}
plugins: debug ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
],
};
module.exports = config;
Starting the webpack in watch mode and will not require you to build again to do that add the followign in your package.json
"scripts": {
"build": "webpack --progress --color --config webpack.config.js --watch",
}
You may also use webpack-dev-server in hot-loading mode
I am trying to use node_modules in the browser via WebPack. I've read the tutorial and beginning steps but am stuck.
I have used webpack to generate bundle.js with the webpack config below and upon going to my index.html in Chrome browser I get the error:
Uncaught ReferenceError: require is not defined
at Object.<anonymous> (bundle.js:205)
What additional steps do I have to do to get the browser to recongnize require?
index.html
<script src="bundle.js"></script>
<button onclick="EntryPoint.check()">Check</button>
index.js
const SpellChecker = require('spellchecker');
module.exports = {
check: function() {
alert(SpellChecker.isMisspelled('keng'));
}
};
package.json
{
"name": "browser-spelling",
"version": "1.0.0",
"description": "",
"main": "index.js",
"dependencies": {
"node-loader": "^0.6.0",
"spellchecker": "^3.3.1",
"webpack": "^2.2.1"
}
}
webpack.config.js
module.exports = {
entry: './index.js',
target: 'node',
output: {
path: './',
filename: 'bundle.js',
libraryTarget: 'var',
library: 'EntryPoint'
},
module: {
loaders: [
{
test: /\.node$/,
loader: 'node-loader'
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015']
}
}
]
}
};
In your webpack.config.js you specified that you want to build this bundle for Node.js:
target: 'node',
And webpack decided to keep require calls, because Node.js supports them. If you want to run it in a browser, you should use target: 'web' instead.
In the new "webpack": "^5.75.0", Required has been changed to rules
webpack.config.js
const path = require("path");
var webpack = require("webpack");
module.exports = {
entry: "./index.js",
target: "node",
output: {
filename: "bundle.js",
path: path.resolve(__dirname, "dist"),
},
module: {
rules: [
{
test: /\.node$/,
use: "node-loader",
},
{
test: /\.js$/,
exclude: /node_modules/,
},
],
},
};
package.json
{
"name": "arrybsc",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"bootstrap": "^5.2.3",
"lodash": "^4.17.21"
},
"devDependencies": {
"webpack": "^5.75.0",
"webpack-cli": "^5.0.1"
}
}