Is there a way to reference a process.env.NODE_ENV in a scss file by passing it to the sass-loader in postcss for rollup. If so anyone know how to go about this?
UPDATE1
Ok, so this is my rollup.config.js. I'm getting a weird issue where sometimes the $env is undefined and sometimes it is set to the right process.env.NODE_ENV
import serve from "rollup-plugin-serve";
import livereload from "rollup-plugin-livereload";
import babel from '#rollup/plugin-babel';
import { nodeResolve } from '#rollup/plugin-node-resolve';
import commonjs from '#rollup/plugin-commonjs';
import replace from '#rollup/plugin-replace';
import postcss from 'rollup-plugin-postcss';
import { uglify } from 'rollup-plugin-uglify';
const build = process.env.BUILD ? process.env.BUILD : 'development';
export default {
input: "src/index.js",
output: {
file: "dist/bundle.js",
sourcemap: true,
compact: true
},
plugins: [
postcss({
use: {
sass: {
data: "$env: " + process.env.NODE_ENV + ";"
}
},
}),
nodeResolve({
extensions: [".js"],
}),
replace({
'process.env.NODE_ENV': JSON.stringify(build)
}),
babel({
presets: ["#babel/preset-react"],
}),
commonjs(),
build === 'production' && uglify(),
serve({
verbose: true,
contentBase: ["", "public"],
host: "localhost",
port: 3000,
}),
build === 'development' &&
livereload({ watch: "dist" }),
]
};
Related
I´m trying to setup a uitkit template with
webpack 4
sass loader
MiniCssExtractPlugin
uikit
What I would like to achieve is that a build automatically converts sass to css and that resulting css is injected into src/index.html.
webpack.config.js
const HtmlWebPackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.html$/,
use: [
{
loader: "html-loader",
options: { minimize: true }
}
]
},
{
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: "css-loader",
options: {
modules: true,
sourceMap: true,
importLoader: 4
}
},
"sass-loader"
]}
]
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html"
}),
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
})
]
};
index.js
import UIkit from 'uikit';
import Icons from 'uikit/dist/js/uikit-icons';
import style from "uikit/src/scss/uikit.scss"
UIkit.use(Icons);
Unfortunately a build fails with
ERROR in ./node_modules/uikit/src/scss/uikit.scss (./node_modules/css-loader??ref--6-1!./node_modules/sass-loader/lib/loader.js!./node_modules/uikit/src/scss/uikit.scss)
Module build failed (from ./node_modules/sass-loader/lib/loader.js):
$inverse-base-color: $inverse-global-color !default;
Undefined variable: "$inverse-global-color".
in new_proj/node_modules/uikit/src/scss/components/base.scss (line 607, column 49)
I would be thankful if one could explain What I´m doing wrong and why sass loader cannot find the variable $inverse-global-color.
I´ve found the answer. It´s working like this:
index.js
...
import style from "./main.scss"
...
main.scss
// 1. Your custom variables and variable overwrites.
$global-link-color: #DA7D02;
// 2. Import default variables and available mixins.
#import "uikit/src/scss/variables-theme.scss";
#import "uikit/src/scss/mixins-theme.scss";
// 3. Your custom mixin overwrites.
#mixin hook-card() { color: #000; }
// 4. Import UIkit.
#import "uikit/src/scss/uikit-theme.scss";
What is your workplace?
Hello, I would like to ask what is your approach to developing the frontend and backend simultaneously?
I am into Webpack, but, what to do when I want to edit framework?
Do I need to run webpack in or out of the box?
Is it possible to reference webpack --watch or some other module to server as proxy? And if so how to set for example *.php files on change to force refresh page.
So far I have worked separately on the framework and particularly on frontend. Now I do not really know how to combine together, especially when many modules of webpack2 is obsolete.
Windows X, Docker(laradock), Webpack, SASS, JS, PHP
Thank you for the future suggestions.
You should use webpack-dev-server as proxy to support multiple hosts.
Then you will be able to load 'backend' from server and developing in another enviroment using all benefits from webpack MHR inlining.
Here is my webpack.config.js
var path = require('path');
var htmlWebPack = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var webpack = require('webpack')
var ProvidePlugin = require('webpack/lib/ProvidePlugin');
var BrowserSyncPlugin = require('browser-sync-webpack-plugin');
var buildPath = path.join(__dirname); // Local /public/
var serverURL = 'http://localhost:8080/' // Webpack-dev-server
var proxyURL = 'http://LaraDock.dev:85/' // External server (laradock)
var proxy = {
'*': proxyURL
};
module.exports = {
devtool: 'cheap-eval-source-map',
context: path.join(__dirname, 'resources'), // ABSOLUTE ROUTE ./
entry: {
app: [
'webpack-dev-server/client?' + serverURL,
'webpack/hot/only-dev-server',
path.join(__dirname, 'resources/assets/js/app.js')
]
},
output: {
publicPath: serverURL + buildPath,
path: path.resolve(__dirname, buildPath),
filename: "js/[name].bundle.js"
},
resolve: {
alias: {
'vue$': 'vue/dist/vue.common.js'
},
},
module: {
loaders: [
// JS
{
test: /\.js$/, // ON WHAT TYPE USE THIS LOADER
loader: 'babel-loader',
include: path.join(__dirname, 'resources', 'assets', 'js'),
},
// VUE
{
test: /\.vue$/,
loader: 'vue-loader',
include: path.join(__dirname, 'resources', 'assets', 'js'),
},
// STYLE
{
test: /\.(sass|scss|css)$/,
loader: ['style-loader', 'css-loader', 'sass-loader'],
include: path.join(__dirname, 'resources', 'assets', 'scss'),
},
// FILES
{
test: /\.(jpe?g|png|gif|svg|ico)$/i,
loader: "file-loader?name=[path][name].[ext]&context=./resources/assets"
},
// FONTS
{
test: /\.(otf|eot|svg|ttf|woff)$/,
loader: 'url-loader?limit=10000'
},
{
test: /\.woff2?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: "url-loader?limit=10000"
},
{
test: /\.(ttf|eot|svg)(\?[\s\S]+)?$/,
loader: 'file-loader'
},
// BOOTSTRAP
{
test: /bootstrap\/public\/js\/umd\//,
loader: 'imports?jQuery=jquery'
},
],
},
devServer: {
contentBase: serverURL + buildPath,
proxy: proxy,
historyApiFallback: true,
hot: true,
noInfo: true,
stats: {
errors: true,
colors: true,
errorDetails: true,
reasons: false,
hash: false,
version: false,
timings: false,
assets: false,
chunks: false,
modules: false,
children: false,
source: false,
warnings: false,
publicPath: false
}
},
plugins: [
new webpack.NoEmitOnErrorsPlugin(),
new BrowserSyncPlugin(
// BrowserSync options
{
// Webpack-dev-server endpoint
host: 'http://localhost',
port: 80,
// proxy the Webpack Dev Server endpoint
// (which should be serving on http://localhost:80/) through BrowserSync
proxy: serverURL,
// Files
files: ['public/*', 'app/**/*.php', 'config/**/*.php', 'resources/views/**/*.php'],
},
// plugin options
{
// prevent BrowserSync from reloading the page
// and let Webpack Dev Server take care of this
reload: false
}),
new ExtractTextPlugin({
filename: './css/[name].style.css',
disable: false,
allChunks: true
}),
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery",
"Tether": 'tether' // Bootstrap v4 problem
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin()
],
};
Currently, I use webpack to build a single JS file which represents my app. How do I split my React app UI shell from rest of the app logic, so that I can have the service Worker cache it?
My webpackpack config file looks like this, that generates a single index_bundle.js file(no css file):
import webpack from 'webpack'
import path from 'path'
import HtmlWebpackPlugin from 'html-webpack-plugin'
import autoprefixer from 'autoprefixer'
const LAUNCH_COMMAND = process.env.npm_lifecycle_event
const isProduction = LAUNCH_COMMAND === 'production'
process.env.BABEL_ENV = LAUNCH_COMMAND
const PATHS = {
root: path.join(__dirname),
app: path.join(__dirname, 'app'),
build: path.join(__dirname, 'dist')
}
const HTMLWebpackPluginConfig = new HtmlWebpackPlugin({
template: PATHS.app + '/index.html',
filename: 'index.html',
inject: 'body'
})
const productionPlugin = new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production')
}
})
const productionPlugin2 = new webpack.optimize.UglifyJsPlugin({
compressor: {
warnings: false
}
})
const base = {
entry: [
'babel-polyfill',
PATHS.app
],
output: {
path: PATHS.build,
filename: 'index_bundle.js'
},
module: {
loaders: [
{test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader'},
{test: /\.css$/, loader: 'style!css?sourceMap&modules&localIdentName=[name]__[local]___[hash:base64:5]&importLoader=1!postcss'}
]
},
postcss: [ autoprefixer({ browsers: ['last 2 versions'] }) ],
resolve: {
root: path.resolve('./app')
}
}
const developmentConfig = {
devtool: 'cheap-module-inline-source-map',
devServer: {
contentBase: PATHS.build,
historyApiFallback: true,
hot: true,
inline: true,
progress: true
},
plugins: [HTMLWebpackPluginConfig, new webpack.HotModuleReplacementPlugin()]
}
const productionConfig = {
devtool: 'cheap-module-source-map',
plugins: [HTMLWebpackPluginConfig, productionPlugin, productionPlugin2]
}
export default Object.assign({}, base, isProduction === true ? productionConfig : developmentConfig)
My "Instant Loading with Service Workers" talk from the Chrome Dev Summit 2015 covers creating a PWA using the App Shell + dynamic model, powered by React.
The code sample for it is part of the sw-precache library's repo: https://github.com/GoogleChrome/sw-precache/tree/master/app-shell-demo
(It's not necessarily the most idiomatic React code in the world, but the general concepts, especially when it comes to the service worker implementation, should hold.)
I'm using webpack and React with react-css-modules and scss files. When i try and build it gives me an error on every file that imports scss files -
ERROR in ./app/components/Buttons/Button.scss
Module build failed: ReferenceError: window is not defined
I have googled for a solid day and a half and have got no where! Please help!
Here's my webpack set up:
var webpack = require('webpack');
var PROD = (process.env.NODE_ENV === 'production');
var precss = require('precss');
var autoprefixer = require('autoprefixer');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var HTMLWebpackPluginConfig = new HtmlWebpackPlugin({
template: __dirname + '/app/index.html',
filename: 'index.html',
inject: 'body'
});
module.exports = {
entry: [
'./app/index.jsx'
],
output: {
path: __dirname + '/dist',
filename: PROD ? 'bundle.min.js' : 'bundle.js'
},
watchOptions: {
poll: true
},
module: {
preLoaders: [
{
test: /\.jsx$|\.js$/,
loader: 'eslint-loader',
include: __dirname + '/assets',
exclude: /bundle\.js$/
}
],
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: "babel-loader",
query: {
presets: ['es2015', 'react']
}
},
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract('style', ['style!css?sourceMap&localIdentName=[local]___[hash:base64:5]!resolve-url!sass?outputStyle=expanded'])
}
]
},
postcss: [autoprefixer({ browsers: ['last 2 versions'] })],
resolve: {
extensions: ['', '.js', '.jsx']
},
plugins: PROD ? [
new webpack.optimize.UglifyJsPlugin({
compress: { warnings: false }
})
] : [
HTMLWebpackPluginConfig,
new ExtractTextPlugin("styles.css", {
allChunks: true
})
]
};
Thanks in advance!
This question keeps popping up when I tried to resolve the same error for Webpack 2, scss, extracttextplugin, and react. The following worked for me.
{
test:/\.scss$/,
use:ExtractTextPlugin.extract({fallback:"style-loader",use:["css-loader","sass-loader"]}),
include:path.join(__dirname,"client/src"),
},
Hope this helps.
I think you have to change it to this, the second parameter goes as a string instead of array. Also removed the repeated use of the style loader.
loader: ExtractTextPlugin.extract('style', 'css?sourceMap&localIdentName=[local]___[hash:base64:5]!resolve-url!sass?outputStyle=expanded')
I'm trying to compile Angular2 with webpack; here is my setup: I have a vendor.ts file where I have:
import 'es6-shim/es6-shim.min';
import 'reflect-metadata/Reflect.js';
import 'zone.js/dist/zone';
import '#angular/platform-browser';
import '#angular/platform-browser-dynamic';
import '#angular/core';
import '#angular/common';
import '#angular/http';
import '#angular/router-deprecated';
My webpack.config.js:
"use strict";
let path = require('path');
let webpack = require("webpack");
let CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin;
let ProvidePlugin = webpack.ProvidePlugin;
let UglifyJsPlugin = webpack.optimize.UglifyJsPlugin;
module.exports = {
devtool: 'source-map',
debug: true, // set false in production
cache: true,
entry: {
vendor: './app/vendor.ts',
app: './app/main.ts'
},
output: {
filename: './public/assets/js/[name].js'
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(true),
new webpack.optimize.CommonsChunkPlugin({name: 'vendor', filename: './public/assets/js/vendor.js', minChunks: Infinity}),
new UglifyJsPlugin({
compress: {
warnings: false
}
})
],
module: {
loaders: [
{
test: /\.ts$/,
loader: 'ts-loader',
query: {
'ignoreDiagnostics': [
2403, // 2403 -> Subsequent variable declarations
2300, // 2300 -> Duplicate identifier
2374, // 2374 -> Duplicate number index signature
2375 // 2375 -> Duplicate string index signature
]
},
exclude: [/\.(spec|e2e)\.ts$/, /node_modules\/(?!(ng2-.+))/]
}
]
},
resolve: {
extensions: ["", ".ts", ".js"]
}
};
So, all is fine, webpack is compiling the stuff, but it's too slow. It's taking 15089ms. I'm planning to add this as a gulp task but this won't work, I have to wait like 3-5 seconds for each save. Is it possible to have a setup where if the chunks don't change, to prevent compilation? This would improve the performance a lot. Thank you in advance for any help.
You have to disable webpack.optimize.* plugins, switch devtool to eval and add transpileOnly: true to ts-loader query.