React's Uncaught Error: addComponentAsRefTo after building with webpack - node.js

I'm trying to build this package:
https://github.com/searchkit/searchkit/ (version v0.10.1)
with webpack and use this with my modules:
node v6.1.0
npm v3.8.6
Build strategy:
fetch repository from github
npm install
npm run build
inside /node_modules/
nothing special is done.
But after trying to use this module withun my components I get those cases.
Case is that if I build with:
searchkit/src/core/react/SearchkitProvider.tsx
import * as React from "react";
import {SearchkitManager} from "../SearchkitManager"
export interface SearchkitProps {
searchkit:SearchkitManager
children?:any
}
export class SearchkitProvider extends React.Component<SearchkitProps,any> {
static childContextTypes = {
searchkit:React.PropTypes.instanceOf(SearchkitManager)
}
static propTypes = {
searchkit:React.PropTypes.instanceOf(SearchkitManager).isRequired,
children:React.PropTypes.element.isRequired
}
componentWillMount() {
this.props.searchkit.setupListeners()
}
componentDidMount(){
this.props.searchkit.completeRegistration()
}
componentWillUnmount(){
this.props.searchkit.unlistenHistory()
}
getChildContext(){
return {searchkit:this.props.searchkit}
}
render(){
return (
<div>IT DOES WORK!!</div>
);
}
}
using by
class Listing extends React.Component {
render() {
return (
<div>
<SearchkitProvider searchkit={searchkit}>
<div></div>
</SearchkitProvider>
</div>
);
}
}
It DOES work properly with proper response, but If I change module's source to:
export class SearchkitProvider extends React.Component<SearchkitProps,any> {
(...)
render(){
return (
<div><input ref="REF" /></div>
);
}
}
it throws this error Uncaught Error: addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created inside a component's render method, or you have multiple copies of React loaded.
I'm not really sure what dependency is made while I'm doing that kind of change ? Should I look for duplicated React instances even though it's working when I'm not using input with ref ?
Webpack.config.js:
const path = require('path')
const webpack = require('webpack')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const copyrightBanner = require("fs").readFileSync("./COPYRIGHT", "utf-8")
const autoprefixer = require('autoprefixer')
module.exports = {
entry: {
"ignore":['./theming/index.ts'],
"bundle":['./src/index.ts']
},
output: {
path: path.join(__dirname, 'release'),
filename: '[name].js',
library:["Searchkit"],
libraryTarget:"umd",
publicPath: '',
css: 'theme.css'
},
resolve: {
extensions:[".js", ".ts", ".tsx","", ".webpack.js", ".web.js", ".scss"],
alias: { react: path.resolve('../react') }
},
postcss: function () {
return [autoprefixer]
},
plugins: [
new webpack.BannerPlugin(copyrightBanner, {entryOnly:true}),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new ExtractTextPlugin("theme.css", {allChunks:true}),
new webpack.optimize.UglifyJsPlugin({
mangle: {
except: ['require', 'export', '$super']
},
compress: {
warnings: false,
sequences: true,
dead_code: true,
conditionals: true,
booleans: true,
unused: true,
if_return: true,
join_vars: true,
drop_console: true
}
})
],
externals: {
"react": "React",
"react-dom":"ReactDOM"
},
module: {
loaders: [
{
test: /\.tsx?$/,
loaders: ['ts'],
include: [path.join(__dirname, 'src'),path.join(__dirname, 'theming')]
},
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract(require.resolve("style-loader"),require.resolve("css-loader")+"!"+require.resolve("postcss-loader")+"!"+require.resolve("sass-loader")),
include: path.join(__dirname, 'theming')
},
{
test: /\.(jpg|png|svg)$/,
loaders: [
'file-loader?name=[path][name].[ext]'
],
include: path.join(__dirname, 'theming')
}
]
}
};
npm ls react:
├── react#0.14.8
└─┬ UNMET PEER DEPENDENCY searchkit#0.10.1
└── react#0.14.8
npm ERR! peer dep missing: searchkit#0.9.x, required by searchkit-multiselect#0.0.1

Related

importing react-virtuoso throws error "You may need an appropriate loader to handle this file type."

My project works fine but after installing and importing react-virtuoso it throws error.
ERROR in ./~/react-virtuoso/dist/index.mjs
Module parse failed: C:\Users\Rocky\Documents\betterdash\node_modules\react-virtuoso\dist\index.mjs Unexpected token (364:22)
You may need an appropriate loader to handle this file type.
| }
| const Component = forwardRef((propsWithChildren, ref) => {
| const { children, ...props } = propsWithChildren;
| const [system2] = useState(() => {
| return tap(init(systemSpec), (system22) => applyPropsToSystem(system22, props));
# ./src/components/order-viewer.jsx 13:21-46
# ./src/main.js
# multi whatwg-fetch ./src/main.js
Here is my webpack.config.js
const path = require("path");
const webpack = require("webpack");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
entry: ["whatwg-fetch", "./src/main.js"],
output: {
path: path.join(__dirname, "dist"),
filename: "bundle.js",
publicPath: "/",
},
module: {
loaders: [
{
test: /.jsx?$/,
loader: "babel-loader",
include: path.join(__dirname, "src"),
exclude: /node_modules/,
query: {
presets: ["es2015", "react", "flow"],
plugins: ["transform-flow-strip-types"],
},
},
{
test: /\.s?css$/,
loaders: ExtractTextPlugin.extract({
use: ["css-loader", "sass-loader"],
fallback: "style-loader",
}),
},
],
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new ExtractTextPlugin({
filename: "style.css",
allChunks: true,
disable: process.env.NODE_ENV === "development",
}),
],
devtool: "source-map",
};
I tried deleting node_modules then run npm install but it doesn't solve the problem. If I remove the part of code that imports the react-virtuoso the error also gone.
import { Virtuoso } from "react-virtuoso";
I had the same problem with Jest and I noticed they have renamed the index.js file to index.cjs from version 4.0.0 to version 4.0. I would assume you have to do something similar with Webpack.
transform: {
'^.+\\.(cjs|js|jsx)$': [
'babel-jest',
{ configFile: './babel.config.js' }
]
},
If you install V4.0.0 it will work if that is the same issue.

Webpack does not transpile TailwindCss used in SCSS

I am trying to use scss with tailwindcss, but I cannot get webpack to transpile the tailwind code into destination site.css.
This is my scss used.
_base.scss
#import "tailwindcss/base";
#import "tailwindcss/components";
#import "tailwindcss/utilities";
// Also tried below
#import '~tailwindcss/base.css';
#import '~tailwindcss/components.css';
#import '~tailwindcss/utilities.css';
Once transpiled, I expected the file to have bunch of tailwind styling, like below:
site.css
from-green-500{--gradient-from-color:#48bb78;--gradient-color-stops:var(--gradient-from-color),var(--gradient-to-color,rgba(72,187,120,0))}.from-green-600{--gradient-from-color:#38a169;--gradient-color-stops:var(--gradient-from-color),var(--gradient-to-color,rgba(56,161,105,0))}...
But instead, I got the raw import statements below.
#tailwind base;#tailwind components;#tailwind utilities; ...
My webpack.common.js is below. Does anyone have suggestions on how to properly get the actual transpiled the css content into site.css?
webpack.common.js
'use strict';
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const TSConfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const ESLintPlugin = require('eslint-webpack-plugin');
const SOURCE_ROOT = __dirname + '/src/main/webpack';
const resolve = {
extensions: ['.js', '.ts'],
plugins: [new TSConfigPathsPlugin({
configFile: './tsconfig.json'
})]
};
module.exports = {
resolve: resolve,
entry: {
site: SOURCE_ROOT + '/site/main.ts'
},
output: {
filename: (chunkData) => {
return chunkData.chunk.name === 'dependencies' ? 'clientlib-dependencies/[name].js' : 'clientlib-site/[name].js';
},
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.tsx?$/,
exclude: /node_modules/,
use: [
{
loader: 'ts-loader'
},
{
loader: 'glob-import-loader',
options: {
resolve: resolve
}
}
]
},
{
test: /\.(sc|sa|c)ss$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
url: false
}
},
{
loader: 'postcss-loader',
options: {
postcssOptions: {
plugins: [require('autoprefixer')]
}
}
},
{
loader: 'sass-loader',
},
{
loader: 'glob-import-loader',
options: {
resolve: resolve
}
}
]
}
]
},
plugins: [
new CleanWebpackPlugin(),
new ESLintPlugin({
extensions: ['js', 'ts', 'tsx']
}),
new MiniCssExtractPlugin({
filename: 'clientlib-[name]/[name].css'
}),
new CopyWebpackPlugin({
patterns: [
{ from: path.resolve(__dirname, SOURCE_ROOT + '/resources'), to: './clientlib-site/' }
]
})
],
stats: {
assetsSort: 'chunks',
builtAt: true,
children: false,
chunkGroups: true,
chunkOrigins: true,
colors: false,
errors: true,
errorDetails: true,
env: true,
modules: false,
performance: true,
providedExports: false,
source: false,
warnings: true
}
};

Module build error when running Vuetify with Sass

I am using Webpack with Vuetify and I get a SASS error when compiling. My webpack config file is:
'use strict'
const path = require('path');
const { VueLoaderPlugin } = require("vue-loader");
module.exports = {
mode: 'development',
entry: './index.js',
output: {
filename: 'app.js',
path: path.resolve(__dirname, 'js'),
},
module: {
rules: [
{ test: /\.vue$/, use: 'vue-loader' },
{
test: /\.(scss|sass|css)/,
use: [
'vue-style-loader',
'css-loader',
{
loader: 'sass-loader',
// Requires sass-loader#^7.0.0
// options: {
// implementation: require('sass'),
// fiber: require('fibers'),
// indentedSyntax: true // optional
// },
// Requires sass-loader#^8.0.0
options: {
implementation: require('sass'),
sassOptions: {
fiber: require('fibers'),
indentedSyntax: true // optional
},
},
},
],
}
]
},
plugins: [new VueLoaderPlugin()]
};
The error I receive when building is:
ERROR in ./node_modules/vuetify/dist/vuetify.min.css (./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ref--1-2!./node_modules/vuetify/dist/vuetify.min.css)
Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
SassError: Expected newline.
╷
1 │ #charset "UTF-8";
│ ^
I'm convinced I must be missing some setting in the options for the style loaders somewhere, but I don't know what. Can anyone see where I'm going wrong?

Publish multiple Vuejs components in one project to npm using webpack

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

#ngtools/webpack: missing app.module.ngfactory

I am trying to use the #ngtools/webpack plugin to create an AoT version of my Angular 4 app within webpack 2, but I am having difficulty understanding what this plugin produces.
In particular, I have a main.aot.ts entry point in my webpack for AoT, which looks like this:
// main.aot.ts
import { platformBrowser } from '#angular/platform-browser';
import { AppModuleNgFactory } from '../compiled/src/app/app.module.ngfactory';
const platform = platformBrowser();
platform.bootstrapModuleFactory(AppModuleNgFactory);
and an extract of my webpack.config.js looks like this:
if (envOptions.MODE === 'prod') {
config.module.rules.push(
{test: /\.ts$/, loader: '#ngtools/webpack'}
);
config.plugins.push(
new AotPlugin({
tsConfigPath: path.resolve(__dirname, './app/tsconfig.json'),
entryModule: path.resolve(__dirname, './app/src/app.module#AppModule')
}),
new webpack.optimize.UglifyJsPlugin({
beautify: false,
mangle: {
screw_ie8: true,
keep_fnames: true
},
compress: {
warnings: false,
screw_ie8: true
},
comments: false
})
);
}
Does this #ngtools/webpack plugin generate module files in the same way that the ngc compiler does, for inclusion in main.aot.ts? If not, how does it work? There aren't many examples of this on the web.
The thing about #ngtools/webpack is that it creates those .ngfactory files in memory. Therefore there is no need to have any main.aot.ts.
main.ts:
import { platformBrowserDynamic } from '#angular/platform-browser-dynamic';
import { enableProdMode } from '#angular/core';
import { AppModule } from './app.module';
if (process.env.ENV === 'production') {
enableProdMode();
}
platformBrowserDynamic().bootstrapModule(AppModule);
In your webpack config:
var aotPlugin = new ngToolsWebpack.AotPlugin({
tsConfigPath: helpers.root('tsconfig.json'),
entryModule: helpers.root('app', 'app.module#AppModule')
});
module: {
rules: [
{
test: /\.ts$/,
use: '#ngtools/webpack'
}
]
},
plugins: [
aotPlugin
]
Now, when you run the webpack the #ngtools/webpack will internally compile the Angular out of the box.
It's worth noting it's a good practice to have #ngtools/webpack only for production build because error messages it produces are bollocks.

Resources