I have added the thumbnail component into my project. I got to see the following error in my project after adding it. The error is shown in the following image.
Here's my webpack.config.js file code which might help you on understanding the issue. There's a loader to be specified there. I don't know what's the specified loader for this. Anyone faced the same issue?
Any help?
**/*webpack.config.js*/**
/* eslint comma-dangle: ["error",
{"functions": "never", "arrays": "only-multiline", "objects":
"only-multiline"} ] */
const webpack = require('webpack');
const pathLib = require('path');
const devBuild = process.env.NODE_ENV !== 'production';
const config = {
entry: [
'es5-shim/es5-shim',
'es5-shim/es5-sham',
'babel-polyfill',
'./app/bundles/HelloWorld/startup/registration',
],
output: {
filename: 'webpack-bundle.js',
path: pathLib.resolve(__dirname, '../app/assets/webpack'),
},
resolve: {
extensions: ['.js', '.jsx'],
},
plugins: [
new webpack.EnvironmentPlugin({ NODE_ENV: 'development' }),
],
module: {
rules: [
{
test: require.resolve('react'),
use: {
loader: 'imports-loader',
options: {
shim: 'es5-shim/es5-shim',
sham: 'es5-shim/es5-sham',
}
},
},
{
test: /\.jsx?$/,
use: 'babel-loader',
exclude: /node_modules/,
},
{
test: /\.css$/,
include: /node_modules/,
loaders: ['style-loader', 'css-loader'],
},
],
},
};
module.exports = config;
if (devBuild) {
console.log('Webpack dev build for Rails'); // eslint-disable-line no-console
module.exports.devtool = 'eval-source-map';
} else {
console.log('Webpack production build for Rails'); // eslint-disable-line no-console
}
And Here's the code where I called the component:
import React, { Component } from 'react';
import Thumbnail from 'react-native-thumbnail-video';
class VideoThumnail extends Component {
render() {
return(
<div>
<Thumbnail url="https://www.youtube.com/watch?v=lgj3D5-jJ74" />
</div>
);
}
}
export default VideoThumnail;
You have a rule only for jsx. Try to add js extension in webpack also
{
test: /\.(js|jsx)$/,
use: 'babel-loader',
exclude: /node_modules/,
}
Also i see es6 synax, so try to add .babelrc in project root with this
{
"presets": ["stage-0"]
}
and install babel-preset-env (npm install --save babel-preset-env)
Related
Webpack collected files (.css, .js) into a library and use it in another React project. The styles specified in the component do not pass, although the .css file is present and the styles are there.
UiButton.jsx file
import styles from './UiButton.module.css';
const UiButton = () => {
return (
<>
<button className={styles.button}>Text</button>
</>
);
}
export default UiButton;
index.js file
import UiButton from './UiButton/UiButton';
import './index.css';
export { UiButton };
Webpack.config.js file
const path = require('path');
const webpack = require('webpack');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
// const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
entry: { main: './src/index.js' },
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index.js',
libraryTarget: "umd",
library: "uilibrarytest"
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.css$/,
use: [ 'style-loader', MiniCssExtractPlugin.loader, 'css-loader' ]
}
]
},
plugins: [
new CleanWebpackPlugin(),
new MiniCssExtractPlugin({
filename: 'index.css',
}),
// new HtmlWebpackPlugin({
// template: './public/index.html',
// }),
new webpack.ProvidePlugin({
"React": "react",
}),
],
resolve: {
extensions: ['.js', '.jsx'],
},
}
This is what webpack builds:
.button {
background: red;
}
html {
margin: 0;
padding: 0;
}
How to make it so that when using a component from a given library, the styles are also pulled to it ???
Loaders in Webpack are evaluated from right to left. In your configuration the evaluation order is 'css-loader', MiniCssExtractPlugin.loader, and finally 'style-loader'. But 'style-loader' only injects styles into the DOM. You need MiniCssExtractPlugin.loader to be the first element in the "use" array. See below...
{
test: /\.css$/,
use: [ MiniCssExtractPlugin.loader, 'css-loader' ]
}
Furthermore you can tell webpack to use MiniCssExtractPlugin.loader during production and at other times use 'style-loader'.
const isProduction = process.env.NODE_ENV == 'production';
const stylesHandler = isProduction ? MiniCssExtractPlugin.loader : 'style-loader';
...other config
{
test: /\.css$/,
use: [ stylesHandler, 'css-loader' ]
}
And in your package.json scripts,
"build": "webpack --mode=production --node-env=production"
I have a variable in my vars.scss that I want to access from Javascript in root/app/app.vue.
root/app/scss/vars.scss
:export {
cursor: #fff;
}
root/app/app.vue
<template>
<div id="yes">
</div>
</template>
<script lang="ts">
import Vue from 'vue';
import colors from '#/scss/vars.scss';
export default Vue.extend({
mounted() {
console.log(colors.cursor);
},
});
</script>
<style >
</style>
I have read approximately 30 different stackoverflow questions that appear to be dealing with the similar problem of importing variables into the style block of the .vue file, as well as the identical problem of importing the variables directly into the Javascript code. As a result, my webpack.config.js looks like the following:
root/webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const webpack = require('webpack');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const env = process.env.NODE_ENV
module.exports = {
entry: './app/index.ts',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'staticfiles')
},
resolve: {
extensions: [ '.ts', '.js', '.vue', '.scss', '.sass'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'#': path.resolve(__dirname, '/app/')
}
},
plugins: [
new HtmlWebpackPlugin(),
new CleanWebpackPlugin(),
new webpack.HotModuleReplacementPlugin(),
new VueLoaderPlugin()
],
module: {
rules: [
{
enforce: 'pre',
test: /\.(js|vue|ts)$/,
loader: 'eslint-loader',
exclude: /node_modules/
},
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
// Since sass-loader (weirdly) has SCSS as its default parse mode, we map
// the "scss" and "sass" values for the lang attribute to the right configs here.
// other preprocessors should work out of the box, no loader config like this necessary.
'scss': 'vue-style-loader!css-loader!sass-loader',
'sass': 'vue-style-loader!css-loader!sass-loader?indentedSyntax',
}
// other vue-loader options go here
}
},
{
test: /\.css$/,
use: [
'vue-style-loader',
'css-loader'
]
},
{
test: /\.tsx?$/,
loader: 'ts-loader',
exclude: /node_modules/,
options: {
appendTsSuffixTo: [/\.vue$/],
}
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]'
}
},
{
test: /\.s(a|c)ss$/,
use: [ {
loader: "style-loader",
options: {
sourceMap: env === 'development',
}
}, {
loader: "css-loader",
options: {
sourceMap: env === 'development',
}
}, {
loader: "sass-loader",
options: {
sourceMap: env === 'development',
}
},
'vue-style-loader'],
}]
}
};
I have also tried, in the test: /\.s(a|c)ss$/ section, to put vue-style-loader at the beginning of the array.
I have tried many combinations of filenames when attempting to import the .scss file, such as relative (../scss/vars.scss), removing the extension, using .css as an extension, etc.
The error I get is:
ERROR in /home/Documents/application/app/app.vue.ts
[tsl] ERROR in /home/Documents/application/app/app.vue.ts(10,28)
TS2307: Cannot find module '#/scss/vars.scss'.
My question:
In a project that uses vue-style-loader and vue-loader to build .vue files with webpack, how can I import .scss variables into the <script> portion of a .vue file? (please note - I am NOT attempting to import them into the <style> section of the .vue file)
An example based on my comment:
SCSS fragment:
$foo: #333;
body {
--variable-foo: $foo;
}
And then anywhere in the JavaScript
const value = document.body.style.getPropertyValue("--variable-foo");
console.log(value); // outputs "#333"
I've been googling for a couple hours now and can't seem to resolve my issue.
I have a webpack/React/Typescript/Mobx setup and am attempting to use firebase.
Here is my webpack config: (boilerplate from this repo)
var webpack = require('webpack');
var path = require('path');
// variables
var isProduction = process.argv.indexOf('-p') >= 0;
var sourcePath = path.join(__dirname, './src');
var outPath = path.join(__dirname, './dist');
// plugins
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var WebpackCleanupPlugin = require('webpack-cleanup-plugin');
module.exports = {
context: sourcePath,
entry: {
main: './main.tsx'
},
output: {
path: outPath,
filename: 'bundle.js',
chunkFilename: '[chunkhash].js',
publicPath: '/'
},
target: 'web',
resolve: {
extensions: ['.js', '.ts', '.tsx'],
// Fix webpack's default behavior to not load packages with jsnext:main module
// (jsnext:main directs not usually distributable es6 format, but es6 sources)
mainFields: ['module', 'browser', 'main'],
alias: {
app: path.resolve(__dirname, 'src/app/'),
assets: path.resolve(__dirname, 'src/assets/')
}
},
module: {
rules: [
// .ts, .tsx
{
test: /\.tsx?$/,
use: [
isProduction
? 'ts-loader'
: {
loader: 'babel-loader',
options: {
babelrc: false,
plugins: ['react-hot-loader/babel']
}
},
'ts-loader'
],
// : ['babel-loader?plugins=react-hot-loader/babel&presets=', 'ts-loader'],
exclude: /node_modules/
},
// css
{
test: /\.css$/,
exclude: /node_modules/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{
loader: 'css-loader',
query: {
modules: true,
sourceMap: !isProduction,
importLoaders: 1,
localIdentName: '[local]__[hash:base64:5]'
}
},
{
loader: 'postcss-loader',
options: {
ident: 'postcss',
plugins: [
require('postcss-import')({ addDependencyTo: webpack }),
require('postcss-url')(),
require('postcss-cssnext')(),
require('postcss-reporter')(),
require('postcss-browser-reporter')({
disabled: isProduction
})
]
}
}
]
})
},
{
test: /\.css$/,
include: /node_modules/,
use: ['style-loader', 'css-loader']
},
// static assets
{ test: /\.html$/, use: 'html-loader' },
{ test: /\.(png|jpg)$/, use: 'url-loader?limit=10000' },
{ test: /\.webm$/, use: 'file-loader' }
]
},
optimization: {
splitChunks: {
name: true,
cacheGroups: {
commons: {
chunks: 'initial',
minChunks: 2
},
vendors: {
test: /[\\/]node_modules[\\/]/,
chunks: 'all',
priority: -10
}
}
},
runtimeChunk: true
},
plugins: [
new WebpackCleanupPlugin(),
new ExtractTextPlugin({
filename: 'styles.css',
disable: !isProduction
}),
new HtmlWebpackPlugin({
template: 'assets/index.html'
})
],
devServer: {
contentBase: sourcePath,
hot: true,
inline: true,
historyApiFallback: {
disableDotRule: true
},
stats: 'minimal'
},
devtool: 'cheap-module-eval-source-map',
node: {
// workaround for webpack-dev-server issue
// https://github.com/webpack/webpack-dev-server/issues/60#issuecomment-103411179
fs: 'empty',
net: 'empty'
}
};
Just by including firebase in my app i relentlessly end up with this error:
Uncaught TypeError: Cannot read property 'navigator' of undefined auth.esm.js?69b5:10
I have tested by including a simple component like so:
import * as React from 'react';
import * as Styles from './styles.css';
import 'app/utils/FirebaseUtil';
interface TestProps {}
export const Test: React.StatelessComponent<TestProps > = () => (
<div className={Styles.root}>
{'Hello World'}
</div>
);
FirebaseUtil:
import * as firebase from 'firebase';
const config = {
apiKey: '**my key here**',
authDomain: '** my domain here **'
};
firebase.initializeApp(config);
export const fbAuth = firebase.auth;
No matter what I seem to do I get the navigator error. Even if i dont export the auth object. As far as I can tell its related to babel-loader adding strict-mode according to this SO question, i think? All other related searches seem to have to do with firebase-ui, which i am not using in any way.
But I have no idea how he manages to turn off strict mode, not to mention the OP is not using typescript and I am using ts-loader in this case. I can't for the life of me figure out how to get it working. Aside from all of this if I do try use the firebase object for auth() for example I get a bunch of warnings from webpack about auth not existing on the firebase object. Totally stumped.
So in case anyone else runs into this problem. It appears it was a package version issue. Im assuming that the package versions specifically included in the boilerplate i used didn't play well with firebase.
I updated typescript, react-hot-loader, and most likely the issue webpack from version 3.0.4 to 4.12.1 and things seem to be working ok now. Also with the updates I now import firebase like so:
import firebase from '#firebase/app';
import '#firebase/auth';
Hope this helps someone.
In my case I fixed this importing functions
import firebase from 'firebase/app'
import 'firebase/functions'
import 'firebase/analytics'
I got the following example from HERE to make a higher order component for passing context reliably.
However, there is a Unexpected token error passing getChildContext() function when compiling the script using webpack:
getChildContext = () => getChildContext(this.props);
^^^
Code:
const provideContext =
(childContextTypes, getChildContext) => (Component) => {
class ContextProvider extends React.Component {
getChildContext = () => getChildContext(this.props);
render() {
return <Component {...this.props} />;
}
}
ContextProvide.childContextTypes = childContextTypes;
return ContextProvider;
};
Is there a workaround way of passing the function?
My webpack config:
var common = {
output: {path: BUILD_DIR},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel',
include: APP_DIR,
query: {
presets: ['es2015', 'react']
}
},
{
test: /\.css$/,
loader: "style-loader!css-loader"
},
{
test: /\.(png|woff|woff2|eot|ttf|svg)$/,
loader: 'url-loader?limit=100000'
},
{
test: /\.(png|jpg)$/,
loader: 'file-loader'
}
]
},
resolve: {
alias: {
'react': path.join(__dirname, 'node_modules', 'react'),
'react-dom': path.join(__dirname, 'node_modules', 'react-dom')
},
extensions: ['', '.js']
},
};
config.push(
merge(common, {
entry: {
ItemPage:APP_DIR+'/page/'+fileName+'.js',
},
devtool: 'source-map',
output: {
filename: "[name].js",
libraryTarget: 'umd',
library: "[name]"
},
externals: [{
react: {
root: 'React',
commonjs2: 'react',
commonjs: 'react',
amd: 'react',
},
"react-dom": "ReactDOM"
}]
})
);
module.exports = config;
You are getting Unexpected token because you are missing one babel plugin, transform-class-properties which is included in stage-1 preset
With stage-1, it works
Without stage-1, it does not work
So in order to fix it, you have to
1º Install stage-1
npm install --save-dev babel-preset-stage-1
2º Add it to .babelrc
{
"presets": ["react","es2015","stage-1"]
}
Or to the webpack config
query: {
presets: ["react","es2015","stage-1"]
}
In my project I use Webpack with React and NodeJS. I want to generate a bundle.js and style.css file. Currently I've got the following code:
var webpack = require('webpack')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
module.exports = {
entry: './index.js',
output: {
path: 'public',
filename: 'bundle.js',
publicPath: ''
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015']
}
},
{ test: /\.scss$/, loader: ExtractTextPlugin.extract('css!sass') }
]
},
plugins: [
new ExtractTextPlugin('public/style.css')
]
}
But when I run webpack only the JS file is created in the ./public map:
Asset Size Chunks Chunk Names
bundle.js 844 kB 0 [emitted] main
+ 222 hidden modules
Following examples/tutorials it's only oriented on CSS files, or obvious mistakes where made like not implementing ExtractText.
I've also downloaded the packages sass-loader node-sass. In some examples I did found those packages where included, in some they weren't.
EDIT (require style in index.js):
import React from 'react'
import { render } from 'react-dom'
import { Router, browserHistory } from 'react-router'
import routes from './modules/routes'
require('./public/style.css')
render(
<Router routes={routes} history={browserHistory} />,
document.getElementById('app')
)
EDIT (webpack.config.js):
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015']
}
},
{
test : /\.scss$/,
include : path.join(__dirname, './public/sass'),
loaders : ["style", "css", "sass"]
},
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract('css!sass')
}
]
},
sassLoader: {
includePaths: [path.join(__dirname, './public/sass')]
},
plugins: [
new ExtractTextPlugin(path.join(__dirname, './public/style.css'))
]
My folder structure looks like this:
webpack.config.js
index.js
/public
index.html
bundle.js (generated)
/sass
style.scss
basics.scss (imported in style.scss)
Make sure that you require your style file.
e.g.
require('../sass/app.scss');
and I think you need style loader as well
e.g.
{
test : /\.scss$/,
include : path.join(__dirname, 'sass'),
loaders : ["style", "css", "sass"]
}
These three loaders perform following operations
Turn your scss files into plain CSS with the sass loader
Resolve all the imports and url(...)s in the CSS with the help of CSS loader
Insert those styles into the page with the style loader
You need a combination of the ExtractTextPlugin and the style loader.
module: {
loaders: [
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract('style-loader', 'css-loader!sass-loader'),
},
],
}
...
plugins: [
new ExtractTextPlugin(path.join(__dirname, 'public', 'style.css')),
],
In my working configs, I also have a possibly extraneous entry in resolve:
resolve: {
loaders: [
{
test: /\.(css|scss)$/,
loader: ExtractTextPlugin.extract('style-loader', 'css-loader'),
},
],
},
The other error might be how you're including it in index.js. You're using require('./public/style.css') rather than require('./public/style.scss').