Getting Babel 6 to work with IE8 (via. Gulp/Webpack) - internet-explorer-8

I've got Babel 6 working nicely with Gulp and Webpack. I now need to polyfill it to get IE8 support.
I've installed the babel-polyfill, but can't get it working and the docs and Google haven't helped so far.
My Gulp task (inc. Webpack config):
gulp.task('webpack', function(callback) {
var webpackConfig = {
context: __dirname + '../../../js',
entry: {
homepage: [
'babel-polyfill',
'./public/homepage/homepage.js'
]
},
output: {
path: __dirname + '../../../dist/public/scripts/',
filename: '[name].bundle.js'
},
module: {
loaders: [
{
loader: 'babel-loader',
test: /\.js$/, // Only run .js files through Babel
include: /js/, // Only include the /js dir
query: {
//plugins: ['transform-runtime'], // Disabled pending fix to https://github.com/babel/babel/issues/2954
presets: ['es2015'],//, 'stage-0'
}
}
]
}
};
webpack(webpackConfig, function(err, stats) {
if (err) {
throw new gutil.PluginError('webpack', err);
}
gutil.log('[webpack]', stats.toString({
// output options
}));
callback();
});
});
From the docs (https://babeljs.io/docs/usage/polyfill/):
Usage in Node / Browserify / Webpack
To include the polyfill you need to require it at the top of the entry point to > your application.
require("babel-polyfill");
Usage in Browser
Available from the dist/polyfill.js file within a babel-polyfill npm release. This needs to be included before all your compiled Babel code. You can either prepend it to your compiled code or include it in a before it.
NOTE: Do not require this via browserify etc, use babel-polyfill.
I've tried simply adding the polyfill.js file to the top of the page, but IE8 still isn't happy with the compiled code's use of the default keyword.
I've also tried adding the polyfill to the webpack process, as per http://jamesknelson.com/using-es6-in-the-browser-with-babel-6-and-webpack/ and other suggestions from Google
What am I doing wrong?

Related

Gatsby Develop Failing using gatsby-plugin-sass

After installing the gatsby-plugin-sass module:
When I try to run gatsby build, I get the following error:
ERROR
Unknown error from PostCSS plugin. Your current PostCSS version is 6.0.23, but autoprefixer uses 7.0.26. Perhaps this is the source of the error below.
ERROR #98123 WEBPACK
Generating development JavaScript bundle failed
Browser queries must be an array or string. Got object.
File: src/indexs.sass
failed Building development bundle - 9.200s
I have been working on a resolution to this for hours. I have tried:
custom webpack rules in gatsby-node.js for sass files
reading, re-reading, and re-re-reading the instruction on gatsby's site
updating PostCSS using npm in every way I know how
So far, nothing has worked.
Why is it so complicated to get sass working with gatsby? When the documentation on gatsby's site makes it seem so easy?
Any suggestions what I can do to get this working?
in gatsby-node.js:
exports.onCreateWebpackConfig = ({
stage,
rules,
loaders,
plugins,
actions,
}) => {
// console.log('rules',rules)
// console.log('rules.css',rules.css())
// console.log('rules',rules.postcss())
actions.setWebpackConfig({
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
// Creates `style` nodes from JS strings
'style-loader',
// Translates CSS into CommonJS
'css-loader',
// Compiles Sass to CSS
'sass-loader',
],
},
],
},
plugins: [
plugins.define({
__DEVELOPMENT__: stage === `develop` || stage === `develop-html`,
}),
],
})
}
In gatsby-config.js:
{
resolve: `gatsby-plugin-postcss`,
options: {
postCssPlugins: [require(`postcss-preset-env`)({ stage: 0 })],
},
},
`gatsby-plugin-sass`,
the sass import line in gatsby-browser.js:
import "./src/indexs.sass"
Using sass instead of node-sass saved my day.
remove node-sass
npm uninstall node-sass
or
yarn remove node-sass
and add sass aka dart-sass
npm install --save-dev sass
or
yarn add sass
then edit gatsby-config.js
plugins: [
{
resolve: `gatsby-plugin-sass`,
options: {
implementation: require("sass"),
},
},
]
now run gatsby develop
:)
I'm a bit late to the party but hopefully this might help someone.
I have Sass setup and working with Gatsby without to much extra config required.
Install both node-sass and gatsby-plugin-sass via npm.
npm install --save node-sass gatsby-plugin-sass
Include gatsby-plugin-sass in your gatsby-config.js file in plugins: [] as below with any other Gatsby plugins you maybe using.
module.exports = {
siteMetadata: {
title: `#`,
description: `#`,
author: `#`,
},
plugins: [
`gatsby-plugin-sass`,
],
}
Write your styles as .sass or .scss files and import your main styles.scss (or whatever you prefer to name it) either in your main Layout.js file or gatsby-browser.js file as below using the path to the location of your styles.scss file.
import "./src/styles/styles.scss"
I hope this works for you but if you have any other trouble add a comment and I'll try to reply back.
I hope someone chimes in on this to show how exactly to set up gatsbys sass plugin. I could not get it to work at all.
But I did find a workaround in my case:
I removed gatsby-plugin-sass from the plugins array in gatsby-config.js, turning it off (but I did not uninstall it using npm)
I installed postcss-node-sass and postcss
I added this info to the plugins array in gatsby-config.js:
{
resolve: `gatsby-plugin-postcss`,
options: {
postCssPlugins: [
require(`postcss-preset-env`)({ stage: 0 }),
require(`postcss-node-sass`)(),
],
},
},
I added a custom rule for webpack in gatsby-node.js:
exports.onCreateWebpackConfig = ({
stage,
rules,
loaders,
plugins,
actions,
}) => {
// console.log('rules',rules)
// console.log('rules.css',rules.css())
// console.log('rules',rules.postcss())
actions.setWebpackConfig({
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
// Creates `style` nodes from JS strings
'style-loader',
// Translates CSS into CommonJS
'css-loader',
// Compiles Sass to CSS
'sass-loader',
],
},
],
},
plugins: [
plugins.define({
__DEVELOPMENT__: stage === `develop` || stage === `develop-html`,
}),
],
})
}

Webpack 1.x Hot Module Replacement Modules not updating

I'm trying to integrate Angular 2 with HMR in Visual Studio 2015. I have 2 projects with the same file contents and same directory structure and both uses HMR with Angular 2. But the HMR for each project looks for different to update the bundle. i.e. For App1, it looks for Typescript files (And JS are not generated for them in VS) like:
Having Module A depends upon B, and B Upon C. If C is updated, the whole bundle gets updated that works good.
But in App2, it looks for 1 Typescript file main.ts and 2 Javascript files, like:
If C is updated, the module don't get updated, unless I explicitly modify C's Javascript file (Generated by VS on build)!
How do I tell Webpack HMR to look for these Typescript files and update the bundle if I changed any of them.
My webpack.config.js are same for both projects like:
var path = require('path');
var webpack = require('webpack');
module.exports = {
resolve: { extensions: [ '', '.js', '.ts' ] },
entry: { 'main-client': './ClientApp/main.ts' },
output: {
filename: '[name].js',
path: path.join(__dirname, './wwwroot/dist'),
publicPath: '/dist/'
},
module: {
loaders: [
{ test: /\.ts$/, include: /ClientApp/, loader: 'ts' },
{ test: /\.html$/, loader: 'raw' }
]
}
};
I had the same problem and fixed it by enabling HMR in main.ts.
import { platformBrowserDynamic } from '#angular/platform-browser-dynamic';
import { enableProdMode } from '#angular/core';
import { AppModule } from './app/app.module';
// Enables Hot Module Replacement.
declare var module: any;
if (module.hot) {
module.hot.accept();
}
platformBrowserDynamic().bootstrapModule(AppModule);

Error when combining sass-loader with css-modules

I'm getting the following error when using SASS's map-get.
ERROR in ./src/special.scss
Module build failed: ModuleBuildError: Module build failed: Unknown word (11:14)
9 |
10 | #mixin mediaquery($name) {
> 11 | #media #{map-get($breakpoints, $name)} {
| ^
12 | #content;
13 | }
14 | }
This is only happening when I use both the sass-loader and another loader.
I first thought this was caused by the PostCSS Loader, but it seems like it's the sass-loading causing problems and not transforming the scss when using css-modules.
I've created a sample repo illustrating the problem: https://github.com/tiemevanveen/sass-css-components-fail-example.
You can use the different branches to test:
master: CSS Modules + SASS
postcss CSS Modules + SASS + PostCSS
log-source: Uses CSS modules + SASS + Custom source logging module
no-css-modules: SASS + Custom source logging module
Only the first and the last branch run without errors.
I've created the log-source example to see what the sass-loader is returning and it looks like it's not transforming the sass (but this might also be me misinterpreting how the loaders work).
The other example without css modules does show the right transformed code..
I'm puzzled why the master branch (without postcss or another custom loader) is working fine though.. if something would be wrong with the sass-loader then that one should also fail right?
I've filed an issue, but I'm thinking this has more chance on StackOverflow since it's such a specific problem and might be more a config problem. Here's my webpack config:
const webpack = require('webpack');
const path = require('path');
const autoprefixer = require('autoprefixer');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const WriteFilePlugin = require('write-file-webpack-plugin');
module.exports = {
devtool: 'source-source-map',
debug: true,
context: path.resolve(__dirname, './src'),
entry: {
app: './index.js'
},
output: {
path: path.resolve(__dirname, './static'),
filename: '[name].js',
publicPath: '/static/'
},
devServer: {
outputPath: path.resolve(__dirname, './static'),
},
plugins: [
new webpack.NoErrorsPlugin(),
new ExtractTextPlugin('[name].css'),
new WriteFilePlugin()
],
module: {
loaders: [
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract('style-loader', [
'css?modules&importLoaders=1&localIdentName=[path]_[name]_[local]',
// 'postcss-loader',
'sass'
])
},
// + js loader
]
},
postcss: [
autoprefixer({ browsers: ['> 0.5%'] })
],
resolveLoader: {
fallback: [
path.resolve(__dirname, 'loaders'),
path.join(process.cwd(), 'node_modules')
]
},
resolve: {
extensions: ['', '.js', '.json'],
}
};
You need to increase the importLoaders query parameter as you add loaders. That feature is poorly documented and confusing, but in your samples repo, importLoaders=2 with both Sass and PostCSS works.

WebSocket shim error with Webpack

I'm having trouble creating a WebSocket object on a webpack project. When I call new WebSocket("") it appears as though I get back the constructor as opposed to a new object of that constructor. I have a simple web page that does not use webpack and there everything works fine. Stepping through the working version with the Chrome debugger looks like this:
I cannot step into the WebSocket constructor, it just jumps to the next line. Now with my webpacked app it does step into the constructor where I see this:
and upon stepping out I see this:
I'm really not sure what I'm doing wrong here, how can I fix this? The app is not to be hosted by a webpack server, I'm only using webpack for packaging. All of this is on Chrome on OSX; below is my webpack.config.js
var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'eval',
entry: [
// 'webpack-dev-server/client?http://localhost:3000',
// 'webpack/hot/only-dev-server',
'./src/turborabbit'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.HotModuleReplacementPlugin()
],
module: {
loaders: [{
test: /\.js$/,
loaders: ['react-hot', 'babel'],
include: path.join(__dirname, 'src')
}]
}
};
EDIT:
The module I'm importing and having trouble with is rserve. I have a workaround which is the ugliest thing I have ever done. The module only uses underscore and websocket in the offending file; I have overridden the require call for the module using imports-loader and injected underscore via the ProvidePlugin. This is the relevant portion of webpack config:
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.ProvidePlugin({
'_': 'underscore'
})
],
module: {
loaders: [{
test: /\.js$/,
loaders: ['imports', 'react-hot', 'babel'],
include: path.join(__dirname, 'src')
}]
}
And I load the module as follows:
var Rserve = require ('imports?require=>(function(x){return(x==="ws"?global.WebSocket:_);})!rserve');
I sincerely hope there's a better way
I've found a better solution by aliasing ws in webpack and making a shim that simply returns WebSocket. Relevant portion of webpack.config:
resolve: {
alias: {
ws: path.resolve ('./') + '/src/shim/ws.js'
}
}
and in src/shim/ws.js:
module.exports = WebSocket || MozWebSocket;

using d3.js as an external in webpack

I'm using this tutorial to setup a React.js project with webpack. The webpack.config.js below is almost an exact copy (except that I'm using an app and 'dist' folder), and I am also adding d3.js as an external. Because React is added as an external it lets me do require('react') in any of my app files without including it in the bundle. I wish to do the same with d3.js and have installed it as a node_module, and listed it in the externals area of my webpack config, but when I do require('d3') i get an error message that it's not available.
How can I use d3 (or jQuery for that matter) as an external if I have it installed as a node_module?
this is my project setup
/app
/dist
/node_modules
package.json
webpack.config.js
module.exports = {
entry: './app/index.jsx',
output: {
path: './dist',
filename: 'bundle.js', //this is the default name, so you can skip it
//at this directory our bundle file will be available
//make sure port 8090 is used when launching webpack-dev-server
publicPath: 'http://localhost:8090/assets'
},
module: {
loaders: [
{
//tell webpack to use jsx-loader for all *.jsx files
test: /\.jsx$/,
loader: 'jsx-loader?insertPragma=React.DOM&harmony'
}
]
},
externals: {
//don't bundle the 'react' npm package with our bundle.js
//but get it from a global 'React' variable
'react': 'React',
'd3': 'd3'
},
resolve: {
modulesDirectories: ['app', 'node_modules'],
extensions: ['', '.js', '.jsx']
}
}
I know this question has been open a while, but hopefully this answer is still useful!
If you have installed d3 (or jQuery) as a node_module, you can use the webpack ProvidePlugin to tie an arbitrary key to a module.
The key will be then be available to require anywhere in your webpack app.
E.g. webpack.config.js
{
...lots of webpack config here...
...
plugins: [
new webpack.ProvidePlugin({
d3: 'd3',
$: 'jquery'
})
]
...
}
Then in my-file.js
var d3 = require('d3')
Hope that helps!

Resources