Webpack2 + babel all but one js file are converted to es5 - javascript

I'm using webpack and babel to convert my js and vue2 files to es5 and compile into a single build.js
This is my .babelrc
{
"presets": ["latest", 'stage-1'],
"plugins": [
"transform-runtime",
"transform-es2015-arrow-functions"
],
"comments": false
}
and webpack.config.js
var path = require('path'),
webpack = require('webpack');
require("babel-polyfill");
module.exports = {
entry: ['babel-polyfill', './src'],
output: {
path: './dist/',
filename: 'build.js'
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
scss: 'style-loader!css-loader!sass-loader',
styl: 'style-loader!css-loader!stylus-loader'
}
}
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.styl$/,
use: [
'style-loader',
'css-loader',
{
loader: 'stylus-loader',
},
],
}
]
},
resolve: {
modules: [
path.resolve(__dirname, 'src'),
path.resolve(__dirname, 'node_modules')
],
alias: {
vue: 'vue/dist/vue.common.js'
},
extensions: ['.js', '.vue']
},
plugins: [
// new webpack.DefinePlugin({
// 'process.env': {
// 'NODE_ENV': JSON.stringify('production')
// }
// })
]
}
Running the following command, successfuly compiles all js and vue files including the imported ones into build.js
./node_modules/webpack/bin/webpack.js --progress --watch --display-error-details
All es6 compatible codes are converted to es5 except for BaseModal.js in https://github.com/vue-bulma/modal/
BaseModal.js resides in node_modules/vue-bulma-modal/src/ and is imported by Modal.vue in the same package
I import Modal over index.js of the same package by
import {Modal} from 'vue-bulma-modal'
and BaseModal.js ends up in build.js as it is, without being converted to es5.
But if i copy Modal.vue and BaseModal.js directly into my code and update the import paths accordingly , it is converted to es5 just fine without any problems.
What is it that I'm doing wrong in my webpack.config.js?

Related

WebPack 1.x - Using a file from outside webpack root

I have this project architecture:
Root
Project1
package.json
webpack.config
Project2
package.json
webpack.config
Common
file1.js
I want to be able to use file1.js in side each project.
I am using old webpack 1.13.1.
I have tried using an alias:
resolve: {
alias: {
commons: path.resolve(__dirname, ".../../Common/")
}
}
I have tried both ways:
import ProcessTree from '../../Common/file1';
import ProcessTree from 'commons/file1';
Any ideas?
this is my webpack config:
import webpack from 'webpack';
import path from 'path';
let commonPath= path.resolve(__dirname, '..', '..', 'Common');
export default {
devtool: 'eval-source-map',
entry: [
'./src/index'
],
target: 'web',
output: {
path: __dirname + '/dist', // Note: Physical files are only output by the production build task `npm run build`.
publicPath: '/',
filename: 'bundle.js'
},
resolve: {
alias: {
commons: commonPath
}
},
devServer: {
contentBase: './src'
},
module: {
loaders: [
{
test: /\.js$/,
include: [
path.join(__dirname, 'src'),
commonPath
],
loaders: ['babel']
},
{ test: /(\.css)$/, loaders: ['style', 'css?sourceMap'] },
{ test: /(\.scss)$/, loaders: ['style', 'css?sourceMap', 'sass?sourceMap'] },
{ test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file' },
{ test: /\.(woff|woff2)$/, loader: 'url?prefix=font/&limit=5000' },
{ test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/octet-stream' },
{ test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?mimetype=image/svg+xml' }
]
},
node: {
fs: "empty",
child_process: 'empty',
}
};
Make sure the path is included in whichever module loader rule you want to process files within the Common folder with.
For example:
module: {
loaders: [
{
test: /\.js?$/,
include: [
path.resolve(__dirname),
path.resolve(__dirname, "../../Common")
],
exclude: /node_modules/,
loader: "babel-loader"
}
]
}

Using Imports with .Net, React.Js, and Url.Content

I am using a .Net MVC framework, and trying to render a jsx (React) file that has imports. I am including this file in the razor page (cshtml) through the standard Url.Content injection as follows:
<script src="#Url.Content("~/js/queue/QueueIndex.js")"></script>
<script>
ReactDOM.render(React.createElement(QueueIndex), document.getElementById("queue-index"));
jQuery(window).on("load scroll", function () {
'use strict'; // Start of use strict
// Loader
$("#dvLoading").fadeOut("fast");
});
</script>
If I do not have an import at the top of my React file (QueueIndex.jsx) the page loads just fine. However, I would like to import the react-table package, but if include any imports in my QueueIndex.jsx file, the page breaks.
The error I'm getting is require is not defined.
I think the solution is somewhere in the use of webpack, here is my config:
const webpack = require("webpack");
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
entry: {
nhqueue: './wwwroot/js/queue/QueueIndex.jsx'
},
output: {
path: __dirname + '/wwwroot/js/',
publicPath: '/wwwroot/js/',
filename: '[name].bundle.js'
},
module: {
preLoaders: [
],
loaders: [
{
test: /\.css$/,
loader: "style-loader!css-loader"
},
{ test: /\.tsx?$/, loaders: ['babel', 'ts'] },
{ test: /\.json$ /, loader: "json-loader" },
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: "babel",
query:
{
presets: ['react']
}
}
],
externals: {
"moment": "moment",
},
},
devtool: 'source-map',
target: 'web',
plugins: [
new CleanWebpackPlugin(['./wwwroot/js/*.js'], {
root: __dirname,
verbose: true,
dry: false
}),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production')
}
}),
new webpack.optimize.UglifyJsPlugin()
],
resolve: {
extensions: ['', '.jsx', '.js', '.tsx', '.ts']
},
node: {
fs: "empty",
child_process: "empty"
}
}
Unfortunately, I have had no luck there. Please let me know if you have any ideas of how to resolve this issue. Thanks!
Also, Here is the Babel configuration:
{"presets" : ["es2015", "react"]}

Vue CLI Webpack template with vue-form-wizard not transpiling to es5

I started a project using the vue-cli webpack (simple) template.
When I try to build for release using npm run build I get my dist folder with the expected build.js, etc. and when testing the build version the app works in all browsers except IE (11).
The error in IE referenced a Promise so I looked in the dist.js file and saw the new Promise() syntax. I am not very familiar with vue-loader and babel but I thought all the es6+ code would be transpiled to es5 when I run the build command.
I have not modified the webpack.config.js from what is default with the vue-cli webpack template.
Is my expectation wrong about transpilation or am I missing something?
.babelrc
{
"presets": [
["env", { "modules": false }],
"stage-3"
]
}
webpack.config.js
var path = require('path')
var webpack = require('webpack')
module.exports = {
entry: './src/main.js',
output: {
path: path.resolve(__dirname, './dist'),
publicPath: '/dist/',
filename: 'build.js'
},
module: {
rules: [
{
test: /\.css$/,
use: [
'vue-style-loader',
'css-loader'
],
}, {
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
}
// other vue-loader options go here
}
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]'
}
}
]
},
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js'
},
extensions: ['*', '.js', '.vue', '.json']
},
devServer: {
historyApiFallback: true,
noInfo: true,
overlay: true
},
performance: {
hints: false
},
devtool: '#eval-source-map'
}
if (process.env.NODE_ENV === 'production') {
module.exports.devtool = '#source-map'
// http://vue-loader.vuejs.org/en/workflow/production.html
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
}),
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
compress: {
warnings: false
}
}),
new webpack.LoaderOptionsPlugin({
minimize: true
})
])
}
node - 6.9.2 | npm - 3.10.2 | vue - 2.9.2
Update 1/3/18
Following the babel-polyfill answer and some more searching I was able to get this working for the production build (npm run build) by changing my 'entry' prop in the webpack.config.js file to
entry: ['babel-polyfill', './src/main.js']
and adding the babel-polyfill import statement to my main.js
import 'babel-polyfill'
after adding babel-loader and babel-polyfill npm packages to my dependencies
ES6 to ES5 transpilation only handles syntax transformation, not polyfills (these are more like runtime features).
You can either use babel-polyfill (which includes all ES6 related polyfills) or just es6-promise.

how to ready react app with webpack

I'm new to React and Webpack and all this stuff. I've created a React app with Webpack and I used webpack-dev-server to create and debug my app.
So in my webpack.config.js file I have this code:
var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
var path = require('path');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
context: path.join(__dirname, "src"),
devtool: debug ? "inline-sourcemap" : false,
entry: "./js/client.js",
module: {
loaders: [
{
test: /\.js?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-0'],
plugins: ['react-html-attrs', 'transform-decorators-legacy', 'transform-class-properties'],
}
},
{
test: /\.scss$/,
use: debug ? [{
loader: "style-loader" // creates style nodes from JS strings
}, {
loader: "css-loader" // translates CSS into CommonJS
}, {
loader: "sass-loader" // compiles Sass to CSS
}] : ExtractTextPlugin.extract({ fallback: "style-loader", use: "css-loader" })
}
]
},
output: {
path: __dirname + "/src/",
filename: "client.min.js"
},
plugins: debug ? [] : [
new ExtractTextPlugin('style.min.css'),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
],
externals: {
"jquery": "jQuery",
"react": "React",
"react-dom": "ReactDOM",
"animejs": "anime"
}
};
When I use webpack-dev-server --content-base src --inline --hot, I see my app working in localhost:8080 but now I want to make the app ready for production. so I ran these codes in my terminal:
$: NODE_ENV=production
$: webpack
It doesn't change anything! So first question: what is wrong with NODE_ENV=production? When I change the first line of my webpack to var debug = process.env.NODE_ENV === "production"; //false it works.
There are other problems!
I'm using sass and When debug === false and I open my index.html file in browser, my styles aren't compiled! Just all of my sass code is copied to style.min.css file The problem should be with this part of code:
{
test: /\.scss$/,
use: debug ? [{
loader: "style-loader" // creates style nodes from JS strings
}, {
loader: "css-loader" // translates CSS into CommonJS
}, {
loader: "sass-loader" // compiles Sass to CSS
}] : ExtractTextPlugin.extract({ fallback: "style-loader", use: "css-loader" })
}
And the last problem is with absolute paths! I have this code in my app:
<img src="/images/avatar.jpg">
It works when I use webpack-dev-server but when I use webpack, the image is not found as it tries to open it from the root of my linux.
So these are my questions:
why NODE_ENV=production doesn't work?
How should I compile sass and put the css in style.min.css?
How can I use absolute paths in my app?
thanks in advance
How should I compile sass and put the css in style.min.css?
Try following config
{
test: /\.scss$/,
use: debug ? [{
loader: "style-loader" // creates style nodes from JS strings
}, {
loader: "css-loader" // translates CSS into CommonJS
}, {
loader: "sass-loader" // compiles Sass to CSS
}] : ExtractTextPlugin.extract({
fallback: "style-loader",
use: [
{
loader: "css-loader",
options: {
modules: true,
},
},
{
loader: "sass-loader",
options: {
modules: true,
},
},
],
}),
},
How can I use absolute paths in my app?
A better way to import images in react app is using file loader in webpack and then directly importing images in application like you import other modules. First add file-loader in webpack like this
{
test: /\.(jpg|png)$/,
loader: "file-loader",
},
and then the public path of your server in webpack
output: {
path: __dirname + "/src/",
publicPath: "http://localhost:3000/static", // Your server public path
filename: "client.min.js"
},
Then in directly import image and put in src like this
import avatar from "../images/avatar.jpg";
<img src={avatar} />

Getting error when build production build with webpack and extract-text-plugin

I have an error when trying to build a production build of my React application:
/home/andrey/Projects/Datarisk/app-frontend/node_modules/extract-text-webpack-plugin/index.js:28
if(c.isInitial()) return;
^
TypeError: Cannot read property 'isInitial' of undefined
This is my webpack production config:
import path from 'path';
import webpack from 'webpack';
import ManifestPlugin from 'webpack-manifest-plugin';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import globals from './globals';
const { SRC_PATH, DIST_PATH } = globals;
export default {
entry: {
app: [
'babel-polyfill',
path.resolve(SRC_PATH, './client/index.js')
],
},
output: {
path: DIST_PATH,
chunkFilename: '[name].[chunkhash].js',
filename: '[name].[chunkhash].js'
},
resolve: {
extensions: ['.js', '.jsx', '.scss'],
modules: [
path.resolve(SRC_PATH, './client'),
'node_modules',
],
alias: {
'#components': path.resolve(SRC_PATH, './client/components'),
'#': path.resolve(SRC_PATH, './client'),
},
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: 'babel-loader',
},
{
test: /\.scss$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader?modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]', 'sass-loader']
})
},
{
test: /\.(png|woff|woff2|eot|ttf|svg)$/,
use: 'url-loader?limit=100000'
}
]
},
plugins: [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin(),
new ExtractTextPlugin("[name].[chunkhash].css"),
new ManifestPlugin(),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production'),
'process.env.BROWSER': JSON.stringify(true),
}),
],
}
I am using the following versions:
Webpack: v2.6.0
extract-text-webpack-plugin: v2.1.0
Node: v6.9.4
I also use CSS Modules with SASS.
Thank you.

Categories

Resources