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'] }
}]
Related
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!
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
I am trying to configure my first node react app.
I keep getting an error that says "Can't resolve babel-loader".
Googling that error, I found a couple of suggestions which do not work.
The first is to add the following to my webpack.config.js
// resolveLoader: {
// modulesDirectories: '/usr/local/lib/node_modules'
// },
Trying that produces an error that says:
Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
- configuration.resolveLoader has an unknown property 'modulesDirectories'. These properties are valid:
object { alias?, aliasFields?, cachePredicate?, descriptionFiles?, enforceExtension?, enforceModuleExtension?, extensions?, fileSystem?, mainFields?, mainFiles?, moduleExtensions?, modules?, plugins?, resolver?, symlinks?, unsafeCache?, useSyncFileSystemCalls? }
The next suggestion is to try:
resolveLoader: {
fallback: '/usr/local/lib/node_modules'
},
That produces a similar error.
Does anyone have any advice on how to get started with this configuration. Understanding the documentation is proving difficult - every second word is jargon and I can't find a reference point to find fundamental understanding of what needs to be done to get started in this setup.
Webpack.config.js is:
module.exports = {
entry: './app/app.jsx',
output: {
path: __dirname,
filename: './public/bundle.js'
},
resolve: {
modules: [__dirname, 'node_modules'],
alias: {
Greeter: 'app/components/Greeter.jsx',
GreeterMessage: 'app/components/GreeterMessage.jsx',
GreeterForm: 'app/components/GreeterForm.jsx',
},
extensions: ['.js', '.jsx']
},
// resolveLoader: {
// fallback: '/usr/local/lib/node_modules'
// },
module :{
rules:[{
// use : 'babel-loader',
loader: 'babel-loader',
query :{
presets:['react','es2015']
// ,'es2017'
},
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/
}
]
}
};
I had the same problem; I fixed it by installing the babel-loader module:
yarn add -D babel-loader
or
npm install --save babel-loader
I have a small trial web application that I'm working on that uses the vue webpack template (https://github.com/vuejs-templates/webpack). I'm pretty new to webpack so I was assuming that I could add in to plugins a new webpack.ProvidePlugin and it would be available globally but when I do a npm run dev I get the following error:
/var/www/public/leadsStatsDashboard/liveleadstats/src/components/Hello.vue
18:17 error 'd3' is not defined no-undef
Which sounds like to me that it can't find the d3 reference. I'm no sure if there's some configuration I skipped over or what but any help would be appreciated. Here is the source for my files
Webpack.dev.conf.js:
var path = require('path')
var config = require('../config')
var utils = require('./utils')
var webpack = require('webpack')
var projectRoot = path.resolve(__dirname, '../')
module.exports = {
plugins: [
new webpack.ProvidePlugin({
d3: 'd3',
crossfilter: 'crossfilter',
dc: 'dc'
})
],
entry: {
app: './src/main.js'
},
output: {
path: config.build.assetsRoot,
publicPath: config.build.assetsPublicPath,
filename: '[name].js'
},
resolve: {
extensions: ['', '.js', '.vue'],
fallback: [path.join(__dirname, '../node_modules')],
alias: {
'src': path.resolve(__dirname, '../src'),
'assets': path.resolve(__dirname, '../src/assets'),
'components': path.resolve(__dirname, '../src/components'),
'd3': path.resolve(__dirname, '../bower_components/d3/d3.min.js'),
'crossfilter': path.resolve(__dirname, '../bower_components/crossfilter/crossfilter.min.js'),
'dc': path.resolve(__dirname, '../bower_components/dcjs/dc.js')
}
},
resolveLoader: {
fallback: [path.join(__dirname, '../node_modules')]
},
module: {
preLoaders: [
{
test: /\.vue$/,
loader: 'eslint',
include: projectRoot,
exclude: /node_modules/
},
{
test: /\.js$/,
loader: 'eslint',
include: projectRoot,
exclude: /node_modules/
}
],
loaders: [
{
test: /\.vue$/,
loader: 'vue'
},
{
test: /\.js$/,
loader: 'babel',
include: projectRoot,
exclude: /node_modules/
},
{
test: /\.json$/,
loader: 'json'
},
{
test: /\.html$/,
loader: 'vue-html'
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url',
query: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url',
query: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
}
]
},
eslint: {
formatter: require('eslint-friendly-formatter')
},
vue: {
loaders: utils.cssLoaders()
}
}
Hello.vue
<template>
<div id="pieChartContainer">
</div>
</template>
<script>
export default {
data () {
return {
// note: changing this line won't causes changes
// with hot-reload because the reloaded component
// preserves its current state and we are modifying
// its initial state.
msg: 'Hello World! This is a test'
}
},
ready () {
console.log(d3.version)
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1 {
color: #42b983;
}
</style>
Your error isn't emitted from webpack, but from eslint.
I think the webpack part works as it should, in fact!
no-undef complains that you are using the global d3 without importing or defining it somewhere.
The good news is, that's easy to fix. Use any of the following three possibilities:
Just add the following block to your .eslintrc.js:
"globals": {
"d3": true
}
...or use eslint comments within the file that requires d3 implicitly (but that doesn't make much sense as you made it available globally and you would need to do this in every file you wish to use the global var):
/* eslint-disable no-undef */
...or you could relax the eslint rule in your .eslintrc.js config:
'rules': {
// all other rules...
'no-undef': 0
}
Additional links:
Direct link to the template's eslintrc file
The eslint 'standard' file the template extends
Further reading on eslint's no-undef rule
I tried to get webpack, typescript and react.js working together via awesome-typescript-loader, but I constantly get errors.
I am using awesome typescript loader at Version 0.3.0-rc.2 and webpack 1.8.9
This is my webpack.config.js:
module.exports = {
entry: './ui/index.ts',
output: {
path: __dirname + '/build-ui',
filename: 'app.js',
publicPath: 'http://localhost:8090/assets'
},
module: {
loaders: [
{
test: /\.jsx$/,
loader: 'jsx-loader?insertPragma=React.DOM&harmony'
},
{
test: /\.css$/,
loader: "style-loader!css-loader"
},
{
test: /\.scss$/,
loader: "style-loader!css-loader!sass-loader"
},
{
test: /\.(png|jpg)$/,
loader: 'url-loader?limit=8192'
},
{
test: /\.ts$/,
loader: 'awesome-typescript-loader'
}
]
},
resolve: {
extensions: ['', '.js', '.jsx', '.ts']
}
};
When I run the webpack dev server and my index.ts looks like this:
alert('hello');
It states the following error:
ERROR in ./ui/index.ts
/Users/..../typings/node/node.d.ts:29:12
Subsequent variable declarations must have the same type. Variable 'require' must be of type 'WebpackRequire', but here has type '{ (id: string): any; resolve(id: string): string; cache: any; extensions: any; main: any; }'.
Same when I put in the reference path.
When I try to import the React.js via import React = require('react'); it states:
ERROR in ./ui/index.ts
Module build failed: Cannot resolve module 'child_process' in /..../typings/node
Required in /..../typings/node/node.d.ts
I copied the node.d.ts file from the loader repo, still no luck.
Has anybody been able to get this combination work smoothly? Or should I just use a different web packager?
I'd really would like to get it to work with webpack.
All you're missing is a key target: 'node'.
This makes sure that the environment you are targeting is Node.js and not the browser, and will therefore ignore native dependencies.
Final Config:
module.exports = {
entry: './ui/index.ts',
target: 'node',
output: {
path: __dirname + '/build-ui',
filename: 'app.js',
publicPath: 'http://localhost:8090/assets'
},
module: {
loaders: [
{
test: /\.jsx$/,
loader: 'jsx-loader?insertPragma=React.DOM&harmony'
},
{
test: /\.css$/,
loader: "style-loader!css-loader"
},
{
test: /\.scss$/,
loader: "style-loader!css-loader!sass-loader"
},
{
test: /\.(png|jpg)$/,
loader: 'url-loader?limit=8192'
},
{
test: /\.ts$/,
loader: 'awesome-typescript-loader'
}
]
},
resolve: {
extensions: ['', '.js', '.jsx', '.ts']
}
};
You could consider using a different webpack TypeScript loader. I know a few had issues with node stuff. There are also a couple starter kits that may help out.
Disclaimer: I'm the maintainer of ts-loader.
Try creating a tsconfig.json file.
For example, as you are using awesome-typescript-loader this should work:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"sourceMap": true,
"noEmitHelpers": true
},
"exclude": [
"node_modules"
],
"awesomeTypescriptLoaderOptions": {
"forkChecker": true
},
"compileOnSave": false,
"buildOnSave": false,
"atom": { "rewriteTsconfig": false }
}