"Module parse failed: Unexpected token" when added the class field - node.js

Below TypeScript code (it means that static class fields and other TypeScript features are available) successfully has been built with Webpack:
export default class ConfigRepresentative {
constructor() {
console.log('ok');
}
}
Fails (same if to remove private and static):
export default class ConfigRepresentative {
private static ownInstanceHasBeenCreated: boolean = false;
constructor() {
console.log('ok');
}
}
Error:
ERROR in ./TypeScriptSource/index.ts 7:10
Module parse failed: Unexpected token (7:10)
You may need an appropriate loader to handle this file type.
| export default class ConfigRepresentative {
|
> private static ownInstanceHasBeenCreated: boolean = false;
|
| constructor() {
webpack.config.js
module.exports = {
entry: './TypeScriptSource/index.ts',
output: {
filename: 'index.js',
path: __dirname,
libraryTarget: 'umd'
},
target: 'node',
mode: 'production',
watch: true,
module: {
rules: [
{
test: /\.ts?$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
resolve: {
extensions: ['.ts', '.js']
}
};
For saving your time on reproducing this problem, I attached the souse files.
error.zip

It is because the project was inside node_modules folder. The setting exclude: /node_modules/ cancels the rule {test: /\.ts?$/, use: 'ts-loader'}, but without class property code is pure JavaScript.
(I know that it is bad practice - to develop something inside node_modules, however I don't know the other solution for developing dependencies. In this case, single ConfigRepresentative is useless if it does not used by other project).

Related

Migrating RequireJS/AMD with Plugins to Webpack

I'm working on migrating a large RequireJS application to Webpack. The basic build with Webpack seems to work fine -- I've moved "paths" definitions to "alias" and I've setup loaders for my content and shims, like jQuery.
However, there's a remaining issue I'm not sure how to resolve. Basically the RequireJS app uses the "text-plugin" to include HTML templates, and Webpack is throwing "Module not found" errors for the HTML templates.
An example AMD module I want to bundle looks something like this:
AMD Module with Text Plugin
define([
'security',
'modals',
'text!../templates/contact_info.html'
], function(security, modals, contactInfoTemplate) {
return {
foo: function() { return "bar"; }
};
});
I thought I could use the raw-loader to load the template files. I aliased 'text' to be the 'raw-loader':
text: {
test: /\.html$/,
loader: "raw-loader"
},
However, I'm seeing the following error for all of my templates that are required like above:
Module not found: Error: Can't resolve 'text'
BREAKING CHANGE: It's no longer allowed to omit the '-loader' suffix when using loaders. You need to specify 'text-loader' instead of 'text'.
I tried replacing 'text!...' with 'text-loader!...', and I then see this error complaining that it can't load/find the HTML module!
Module not found: Error: Can't resolve '../templates/contact_info.html'
webpack.config.js, version 3.9.1
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const path = require('path');
const webpack = require('webpack');
let basePath = path.join(__dirname, '/');
module.exports = {
entry: {
'main': basePath + 'js/main.js',
},
context: __dirname,
output: {
path: __dirname + '/build',
filename: '[name].min.js',
libraryTarget: 'amd',
umdNamedDefine: true
},
module: {
rules: [
{
test: /(\.js)$/,
exclude: /(node_modules)/,
use: {
// babel-loader to convert ES6 code to ES5 + amdCleaning requirejs code into simple JS code, taking care of modules to load as desired
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env'],
plugins: []
}
}
},
{
test: /\.css$/,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" }
]
},
{ test: /\.jpg$/, use: [ "file-loader" ] },
{ test: /\.png$/, use: [ "url-loader?mimetype=image/png" ] },
{
test: /\.(html)$/,
use: {
loader: 'raw-loader',
options: {
minimize: true
}
}
}
]
},
resolve: {
modules: [
'js/**/*.js',
'node_modules',
path.resolve('./js')
],
extensions: ['.js'], // File types,
alias: {
text: {
test: /\.html$/,
loader: "raw-loader"
},
bridge: 'libs/bridge',
cache: 'libs/cache',
cards: 'libs/cards',
moment: 'libs/moment',
underscore: 'libs/underscore',
}
},
plugins: [
new CleanWebpackPlugin(['dist']),
new HtmlWebpackPlugin({
filename: 'index.html',
template: '../index.html'
}),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
})
]
};
Anyone know how to get Webpack to play nicely with the RequireJS Text plugin?
Thanks!
Maybe try installing text-loader?
In order for something like 'text!../templates/contact_info.html' to "load" properly, since it is not JS, you need to install text-loader to get webpack to understand the syntax text!.
npm install text-loader --save-dev
humm...i just installed text-loaded and it seems we also have to change text! to text-loader!

Can't Load Browser Dependencies Webpack

I am trying to scaffold an Angular 6 app by hand (ie not using the CLI). I was doing OK until I ran into the following error when running webpack:
ERROR in window is not defined
Now from googling around it looks like I'm missing some polyfills since webpack uses node in order to generate it's output. I've reviewed the examples on Angular's site and added the polyfills.ts file to my application but I still can't get rid of the error.
Here is my webpack.confg.js:
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ScriptExtPlugin = require('script-ext-html-webpack-plugin');
const { AngularCompilerPlugin } = require('#ngtools/webpack');
module.exports = function() {
return {
entry: {
index: "./src/client/client.ts",
polyfills: "./src/client/polyfills.ts"
},
output: {
path: __dirname + "/client-dist",
filename: "[name].client.js"
},
resolve: {
extensions: ['.ts', '.js']
},
module: {
rules: [
{
test: /\.ts$/,
loader: '#ngtools/webpack'
},
{
test: /\.html$/,
loader: 'html-loader',
},
{
test: /\.css$/,
loader: ["style-loader", "css-loader"]
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: __dirname + '/src/client/index.html',
output: __dirname + '/client-dist',
inject: 'head'
}),
new ScriptExtPlugin({
defaultAttribute: 'defer'
}),
new AngularCompilerPlugin({
tsConfigPath: './tsconfig.json',
entryModule: './src/client/app/app.module#AppModule'
})
]
}
}
My polyfills.ts file:
import 'core-js/es6';
import 'core-js/es7/reflect';
import 'zone.js/dist/zone';
And my client.ts file (entry point of my application):
import './polyfills'
import { platformBrowserDynamic } from '#angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
platformBrowserDynamic().bootstrapModule(AppModule);
I'm sure I'm just doing something stupid but any help would be appreciated. Thanks!
EDIT 1:
After reading the article posted by #SureshKumarAriya I tried changing the following in my webpack.config:
new AngularCompilerPlugin({
tsConfigPath: './tsconfig.json',
entryModule: './src/client/app/app.module#AppModule',
skipCodeGeneration: true // This is new
})
And I get a different error: ERROR in Resolution of relative paths requires a containing file.
I'm guessing this means it can't resolve one of the typescript files I reference in client.ts? I'm not sure this has gotten me any closer but still interesting.
As always thanks for the help!
Inside output cofiguration. please add globalObject: "this".
output: {
// ...
globalObject: "this"
}
https://github.com/markdalgleish/static-site-generator-webpack-plugin/issues/130
Seems like your dependencies still rely on the window object.
Do validate
typeof window !== 'undefined'
Please refer to the following link.

TypeError: <X> is not a function when using imported function after webpack

When I push my module to npm, then import it into another application, I get TypeError: <myModule> is not a function.
Is my issue actually with webpack or with the way I am declaring / using my imported function when it is bundled via webpack? or the way I am using babel-loader?
DETAILS:
When myModule's package.json has "main":"src/index.js" which is the pre-webpacked version, it works. When I change it to "main":"dist/index.js" I get the issue.
I'm trying to use it like this:
import { myModule } from '#myNPM/myModuleInNPM'
...
async function someFunction(stuff) {
const scooby = await myModule(stuff)
...
}
my webpack config:
var path = require('path')
const nodeExternals = require('webpack-node-externals')
module.exports = {
entry: './src/index.js',
target: 'node',
mode: 'production',
optimization: {
// We do not want to minimize our code.
minimize: false
},
performance: {
// Turn off size warnings for entry points
hints: false
},
devtool: 'nosources-source-map',
externals: [nodeExternals()],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader'
}
]
}
]
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index.js'
}
}
I found my answer... I needed to specify my libraryTarget in my webpack config. I am now using libraryTarget: 'commonjs' an it works beautifully

Publish multiple Vuejs components in one project to npm using webpack

Im trying to publish a project to npm that contains two or more Vue components so i can import, register and use both components like this:
import Component1 from 'npm-package'
import Component2 from 'npm-package'
this is my webpack file:
const webpack = require('webpack');
const merge = require('webpack-merge');
const path = require('path');
var config = {
output: {
path: path.resolve(__dirname + '/dist/'),
},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel',
include: __dirname,
exclude: /node_modules/
},
{
test: /\.vue$/,
loader: 'vue'
},
{
test: /\.css$/,
loader: 'style!less!css'
}
]
},
externals: {
moment: 'moment'
},
plugins: [
new webpack.optimize.UglifyJsPlugin( {
minimize : true,
sourceMap : false,
mangle: true,
compress: {
warnings: false
}
} )
]
};
module.exports = [
merge(config, {
entry: path.resolve(__dirname + '/src/plugin.js'),
output: {
filename: 'vue-project.min.js',
libraryTarget: 'window',
library: 'VueProject',
}
}),
merge(config, {
entry: path.resolve(__dirname + '/src/index.js'),
output: {
filename: 'vue-project.js',
libraryTarget: 'umd',
library: 'vue-project',
umdNamedDefine: true
},
resolve: {
extensions: ['', '.js', '.vue'],
alias: {
'src': path.resolve(__dirname, '../src'),
'components': path.resolve(__dirname, '../src/components')
}
}
})
];
and this is the index.js file i'm using as the entry point for the build process
import Component1 from './components/folder1/Component1.vue'
import Component1 from './components/folder2/Component2.vue'
export default {
components: {
Component1,
Component2
}
}
The build process using npm run build works fine and i can publish the project to npm and install it using npm install. Importing and using it works fine to, but when i run my project i get the error:
failed to mount component: template or render function not defined.
All other posts o found regarding this error did not solve my problem, as none of them tried to export multiple components.
Both components work completely as intended when im publishing them in two different projects.
What am i missing here? Thanks in advance!
You don't need to export using the components property, you simply need to do:
export {
Component1,
Component2
}
You would then do:
import {Component1} from 'npm-package';
import {Component2} from 'npm-package';
or
import {Component1, Component2} from 'npm-package';
see: https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export

Webpack with babel-loader property types

I'm trying to migrate my node typescript apps (with exprees js server) to ES2015 with using Webpack.
First of all, I would like to use property types. I founded, than I need to user babel-loader and eslint. So, I installed this packages and implement it to my express app.:
This is my webpack.config.js
const webpack = require('webpack');
const WebpackErrorNotificationPlugin = require("webpack-error-notification");
module.exports =
{
entry: './src/test/test.js',
target: 'node',
debug: true,
output: {
path: './bin',
filename: 'test.bundle.js',
},
module: {
preLoaders: [{
test: /\.js?$/,
loaders: ['eslint'],
exclude: /node_modules/
}],
loaders: [{
test: /\.js?$/,
exclude: /node_modules/,
loader: 'babel',
}]
},
eslint: {
failOnWarning: false,
failOnError: true
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
},
output: {
comments: false,
},
}),
new WebpackErrorNotificationPlugin()
]
}
.eslintrc
{
"parser": "babel-eslint",
"parserOptions": {
"sourceType": "module",
"allowImportExportEverywhere": false
}
}
And one of error codes:
export class CmsUserModel {
/**
* (description)
*
* #type {String}
*/
template: string;
/**
* (description)
*
* #type {string}
*/
pages: string[];
constructor() {
this.template = "";
this.pages = new Array<string>();
}
public static ToModel(model: ICmsUserModel) {
return <CmsUserModel>{
template : model.template,
pages : model.pages
};
}
}
There are two problems. The first is, then babal-eslint error handling is not too specified. For example this:
ERROR in ./src/models/cmsUserModel.js
/Users/petrtomasek/Projects/cms/src/models/cmsUserModel.js
44:40 error Parsing error: Unexpected token
✖ 1 problem (1 error, 0 warnings)
ERROR in ./src/models/cmsUserModel.js
Module build failed: Error: Module failed because of a eslint error.
/Users/petrtomasek/Projects/cms/src/models/cmsUserModel.js
44:40 error Parsing error: Unexpected token
✖ 1 problem (1 error, 0 warnings)
It's fine, but I would like to see standard error handling like in default webpack and babel loader with print current error line if is possible..?
And the second error is, then I still cannot use property Types as for example: template: string
What's wrong please?
Thank's for your time!
I think you should try the following steps,
1. npm install --save-dev babel-preset-es2015
2. Add query: { presets: ['es2015'] } to your webpack config with the babel loader.
loaders: [{
test: /\.js?$/,
exclude: /node_modules/,
loader: 'babel',
query: { presets: ['es2015'] }
}]

Resources