I got a project that is compiled with webpack and everything works well, but we are moving to rollupJS and i'm stuked with a file that is imported.
utils/init-jquery.jsx:
global.$ = global.jQuery = require('jquery');
require('jquery-mask-plugin');
require('fancybox')(global.$);
require('libraries/jquery.unserialize');
This file is imported for example in this file app.jsx:
import React from 'react';
import { render } from 'react-dom';
import InitJquery from 'common/utils/init-jquery';
import Init from 'common/utils/init';
...
I got stuked with this error in the console chrome:
Uncaught ReferenceError: global is not defined(…)
my rollup config:
var multiEntry = require('rollup-plugin-multi-entry');
var babel = require('rollup-plugin-babel');
var uglify = require('rollup-plugin-uglify');
var rollupIncludePaths = require('rollup-plugin-includepaths');
var nodeResolve = require( 'rollup-plugin-node-resolve');
var commonjs = require( 'rollup-plugin-commonjs');
var replace = require( 'rollup-plugin-replace');
const includePathOptions = {
paths: ['target/scripts'],
extensions: ['.jsx','.js']
};
var cache;
module.exports = function(grunt) {
return {
options: {
plugins: function () {
return [
rollupIncludePaths(includePathOptions),
replace({
'process.env.NODE_ENV': JSON.stringify( 'production' )
}),
nodeResolve({ jsnext: true, main: true }),
commonjs({
// extensions: [ '.js' ],
sourceMap: true,
//include: 'target/scripts/common/utils',
//ignoreGlobal: true,
namedExports: {
// left-hand side can be an absolute path, a path
// relative to the current directory, or the name
// of a module in node_modules
'formsy-react': [ 'Form', 'Mixin' ],
'react-dom': [ 'render' ],
'react': [ 'Component' ]
}
}),
babel({
babelrc: false,
presets: [["es2015",{modules:false}], "react"],
exclude: ['*/__tests__/**/*', './node_modules/**/*'],
plugins: ["external-helpers"]
}),
uglify()
];
},
cache:cache,
sourceMap: true,
format: 'cjs',
},
main: {
dest: './target/scripts/checkout/cart.bundle.js',
src: './target/scripts/checkout/cart/app-cart.jsx', // Only one source file is permitted
}
};
};
Related
I have the following structure:
-mfp/
- react-host/
- webpack.dev.js
- index.js
- bootstrp.js
- src/
- App.js
- angular-remote/
- webpack.config.js
- src/
- main.ts
- bootstrp.ts
- app/
- app.module.ts
my webpack.config.js in my angular-remote look the following
const webpack = require('webpack');
const ModuleFederationPlugin = require('webpack/lib/container/ModuleFederationPlugin');
module.exports = {
output: {
uniqueName: "ang",
publicPath: "http://localhost:8082/"
},
optimization: {
runtimeChunk: false
},
plugins: [
new ModuleFederationPlugin({
library: { type: 'var', name: 'ang' },
name: "ang",
filename: "remoteEntry.js",
exposes: {
'./angApp': './src/app/app.component.ts',
},
shared: {
'#angular/core': { eager: true, singleton: true },
'#angular/common': { eager: true, singleton: true },
'#angular/router': { eager: true, singleton: true },
},
}),
],
};
My webpack.dev.js in my react-remote look the following
const { merge } = require('webpack-merge');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ModuleFederationPlugin = require('webpack/lib/container/ModuleFederationPlugin');
const packageJson = require('../package.json');
module.exports = = {
module: {
rules: [
{
test: /\.m?js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-react', '#babel/preset-env'],
plugins: ['#babel/plugin-transform-runtime'],
},
},
},
],
},
mode: 'development',
devServer: {
port: 8081,
historyApiFallback: {
index: 'index.html',
},
},
plugins: [
new ModuleFederationPlugin({
name: 'marketing',
filename: 'remoteEntry.js',
exposes: {
'./MarketingApp': './src/bootstrap',
},
shared: packageJson.dependencies,
}),
new HtmlWebpackPlugin({
template: './public/index.html',
}),
],
};
My app.module.ts is the following:
import { BrowserModule } from '#angular/platform-browser';
import { AppComponent } from './app.component';
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [],
// bootstrap: []
bootstrap: [AppComponent]
})
export class AppModule { }
Still I don't see my angular app in my react, I can import in my react-host App.js the following
import angApp from 'ang/angApp'
without any error,I even see at the network tab in the console the call's to the JS return successfully but nothing appears.
I found a wonderful git repo that implements exactly what I intended to do. if any one come across this issue, worth checking it out.
I keep getting this error:
src/legacy/widgetlib.tsx → dist/withReact16/browser.js...
{
code: 'MISSING_NODE_BUILTINS',
message: "Creating a browser bundle that depends on Node.js built-in module ('punycode'). You might need to include https://www.npmjs.com/package/rollup-plugin-node-builtins",
modules: [ 'punycode' ],
toString: [Function]
}
I have included rollup-plugin-node-builtins in multiple different ways and I've googled all over the place. Every "solution" I've found seems to basically be the same thing, but it isn't working for me. I am also not even directly using punycode. Two of my dependencies have it as a dependency. I am using twitter-text lib and oauth-signature. If I comment out those two imports I no longer get this problem. Here is my complete rollup.config.js file:
import resolve from '#rollup/plugin-node-resolve';
import postcss from 'rollup-plugin-postcss';
import commonjs from '#rollup/plugin-commonjs';
import babel from 'rollup-plugin-babel';
import json from '#rollup/plugin-json';
import image from '#rollup/plugin-image';
import replace from 'rollup-plugin-replace';
import gzipPlugin from 'rollup-plugin-gzip';
import { terser } from 'rollup-plugin-terser';
import includePaths from 'rollup-plugin-includepaths';
import builtins from 'rollup-plugin-node-builtins';
import globals from 'rollup-plugin-node-globals';
import React from 'react';
import ReactDOM from 'react-dom';
const extensions = ['.js', '.jsx', '.ts', '.tsx'];
const { PRODUCTION } = process.env;
const CODES = [
'THIS_IS_UNDEFINED',
'MISSING_GLOBAL_NAME',
'CIRCULAR_DEPENDENCY',
];
const globalVars = {
react: 'React',
'react-dom': 'ReactDOM',
};
const discardWarning = warning => {
if (CODES.includes(warning.code)) {
return;
}
// eslint-disable-next-line no-console
console.error(warning);
};
const commonConfig = {
onwarn: discardWarning,
plugins: [
replace({
'process.env.NODE_ENV': JSON.stringify(
PRODUCTION ? 'production' : 'development'
),
}),
image(),
globals(),
builtins(),
resolve({
jsnext: true,
extensions,
preferBuiltins: true,
browser: true,
mainFields: ['browser', 'jsnext', 'module', 'main'],
}),
includePaths({
paths: ['src'],
extensions: [...extensions, '.scss', '.json'],
}),
commonjs({
include: 'node_modules/**',
namedExports: {
react: Object.keys(React),
'react-dom': Object.keys(ReactDOM),
},
}),
babel({
extensions,
runtimeHelpers: true,
babelrc: true,
exclude: 'node_modules/**',
}),
json(),
postcss({
plugins: [],
}),
terser(),
],
};
const browserLibWithReact16 = {
...commonConfig,
input: 'src/legacy/widgetlib.tsx',
output: {
format: 'iife',
sourcemap: true,
name: 'WLIB',
file: 'dist/withReact16/browser.js',
},
plugins: [...commonConfig.plugins, gzipPlugin()],
};
const npmWLIBWithReact16 = {
...commonConfig,
input: 'src/widgetlib.tsx',
output: {
file: 'dist/withReact16/WLIB.js',
format: 'esm',
sourcemap: true,
},
};
const npmLibNoReact = {
...commonConfig,
external: Object.keys(globalVars),
input: 'src/widgetlib.tsx',
output: {
file: 'dist/index.js',
format: 'esm',
sourcemap: true,
},
};
export default [npmLibNoReact, npmWLIBWithReact16, browserLibWithReact16];
The error is only happening for the browserLibWithReact16 config.
Any help would be appreciated.
Any ideas why the module is not found during the tests?
In karma.conf.js I've specified all the dependencies under the files property i.e angular, angular-mocks
But I have a feeling that app.component.ts and main.ts are not being compiled hence why they're not being found?
karma.conf.js
var webpackConfig = require('./webpack.test.config');
module.exports = function(config) {
'use strict';
var _config = {
basePath: '',
frameworks: ['jasmine', 'karma-typescript'],
files: [
'node_modules/angular/angular.js',
'node_modules/angular-mocks/angular-mocks.js',
'src/app/app.component.ts',
'src/main.ts',
{
pattern: 'src/app/**/*.+(ts|html)'
}
],
preprocessors: {
'**/*.ts': ['karma-typescript']
},
webpack: webpackConfig,
karmaTypescriptConfig: {
bundlerOptions: {
entrypoints: /\.spec\.ts$/
},
compilerOptions: {
lib: ['ES2015', 'DOM']
}
},
reporters: ['progress', 'karma-typescript'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['Chrome'],
singleRun: true
};
config.set(_config);
};
webpack.test.config.js
var webpack = require('webpack');
var path = require('path');
module.exports = {
devtool: 'inline-source-map',
resolve: {
extensions: ['.ts', '.js']
},
module: {
rules: [{
test: /\.ts$/,
loaders: [{
loader: 'awesome-typescript-loader',
options: {
configFileName: path.join(__dirname, 'src', 'tsconfig.json')
}
}]
},
{
test: /\.html$/,
loader: 'html-loader'
}
]
}
};
app.component.spec.ts
import { AppComponent } from './app.component';
describe('Component: AppComponent', () => {
let Users;
beforeEach(function() {
angular.mock.module('myapp');
});
beforeEach(inject(function(_Users_: any) {
console.log(_Users_);
}));
});
app.component.ts
export class AppComponent implements ng.IComponentOptions {
static registeredName = 'dummy';
template: any;
constructor() {
this.template = require('./app.component.html');
}
}
main.ts
import { AppComponent } from "./app/app.component";
angular.module("myapp", ['pascalprecht.translate'])
.component(AppComponent.registeredName, new AppComponent())
.config(["$translateProvider", function($translateProvider: any) {
$translateProvider.determinePreferredLanguage();
}]);
I am trying to execute jasmine test case of react+redux on webpack+karma background.
But getting below error
Below I have added webpack,karma config and react+redux component file.
1 ] karma.config.js
var webpackConfig = require('./webpack.config.js');
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
'app/assets/test/**/*Spec.js',
'app/assets/test/**/*Spec.jsx'
],
preprocessors: {
'app/assets/test/**/*Spec.js': ['webpack'],
'app/assets/test/**/*Spec.jsx': ['webpack']
},
webpack: webpackConfig,
reporters: ['kjhtml'],
port: 9876,
colors: true,
config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: true,
concurrency: Infinity
})
}
2 ] react home.jsx component
import CarouselContainer from 'containers/carouselContainer'
import CurrentTracks from 'containers/currentTracks'
export default class Home extends React.Component {
render() {
return (
<div>
<CarouselContainer />
<CurrentTracks />
</div>
)
}
}
3 ] home.Spec.jsx -
import React from 'react';
import { shallow } from 'enzyme';
import ReactTestUtils from 'react-addons-test-utils'
import {Home} from 'pages/home'
describe("User suite", function() {
const wrapper = shallow(<Home/>);
expect(wrapper.length).toEqual(1);
});
4 ] Webpack.config.js -
var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var autoprefixer = require('autoprefixer');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var merge = require('webpack-merge');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var BUILD = path.join(__dirname, 'build');
var APP = path.join(__dirname, 'app');
var JS = path.join(APP, 'assets', 'javascript');
var env = process.env.NODE_ENV;
console.log('Webpack env: ' + env)
var sassLoaders = [
'css-loader',
'postcss-loader',
'sass-loader?indentedSyntax=sass&includePaths[]=' + APP
];
var commonConfig = {
entry: [ path.join(JS, 'index.jsx') ],
module: {
loaders: [
{ test: /\.jsx?$/, exclude: /node_modules/, loaders: ['babel-loader'] },
{ test: /\.css/, loader: 'style-loader!css-loader?name=assets/css/[name]-[hash].[ext]' },
{ test: /\.png|jpg|gif$/, loader: 'file-loader?name=assets/images/[name]-[hash].[ext]' },
{ test: /\.xlsx$/, loader: 'file-loader?name=assets/file/[name].[ext]' },
{ test: /\.sass$/, loader: ExtractTextPlugin.extract('style-loader', sassLoaders.join('!')) },
{ test: /\.(woff|woff2|svg|ttf|eot|ico)$/, loader: 'file-loader?name=assets/fonts/[name].[ext]' }
]
},
output: {
filename: 'assets/javascript/[name]-[hash].js',
path: BUILD,
publicPath: '/'
},
externals: {
'jsdom': 'window',
'cheerio': 'window',
'react/lib/ExecutionEnvironment': true,
'react/addons': true,
'react/lib/ReactContext': 'window'
},
plugins: [
new HtmlWebpackPlugin({
template: 'app/index.html',
inject: 'body',
filename: 'index.html',
favicon: path.join(APP, 'assets', 'images', 'favicon.ico')
}),
new ExtractTextPlugin('assets/stylesheet/[name]-[hash].min.css'),
new CopyWebpackPlugin([
{ from: path.join(APP,'assets/javascript/vendor'), to: 'assets/vendor' }
]),
new CopyWebpackPlugin([
{ from: path.join(APP,'assets/test'), to: 'assets/test' }
]),
new webpack.ProvidePlugin({
React: "react",
"_": "lodash"
})
],
postcss: [
autoprefixer({
browsers: ['last 2 versions']
})
],
resolve: {
root: path.join(APP, 'assets'),
alias: {
config: '../../../../configs',
images: 'images',
actions: 'javascript/actions',
containers: 'javascript/containers',
components: 'javascript/components',
common: 'components/common',
constants: 'javascript/constants',
javascript: 'javascript',
layout: 'components/layout',
mywagers: 'pages/myWagers',
pages: 'components/pages',
home: 'pages/home',
utility: 'javascript/utility',
wagers: 'pages/wagers',
sheets: 'wagers/betPad/sheets'
},
extensions: ['', '.js', '.jsx', '.sass'],
modulesDirectories: ['app', 'node_modules']
}
};
var devConfig = {
devtool: 'inline-source-map',
entry: ['webpack-hot-middleware/client?reload=true'],
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(env || 'development')
})
],
module: {
postLoaders: [
{
test: /\.js$/,
exclude: [/node_modules/,/vendor/],
loader: "jshint-loader"
}
]
}
};
var prodConfig = {
plugins: [
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(env || 'production')
})
]
};
var config;
switch (env) {
case 'development':
config = merge(devConfig, commonConfig);
break;
default:
config = merge(prodConfig, commonConfig);
break;
}
module.exports = config;
It looks like Home is a default export, so in your spec on line 4, you should be importing as a default.
So the line should look like
import Home from 'pages/home';
instead of
import {Home} from 'pages/home';
I've been using css-modules with mocha, enzyme and css-modules-require-hook without any problems.
Foo.js
import React from 'react';
import styles from './Foo.css';
const Foo = () => <div className={ styles.foo }>Foo component</div>;
export default Foo;
Foo.css
.foo {
color: rebeccapurple;
}
Foo.test.js
import Foo from './Foo';
describe('<Foo />', () => {
it('should render proper markup', () => {
const wrapper = shallow(<Foo />);
expect(wrapper.find('.foo')).to.have.length(1);
});
});
I started using Karma with karma-webpack-with-fast-source-maps and now the test fails because the styles in Foo.js is an array and it's not using keys to keep original class name.
[[376, '.Foo__foo___3QT3e {
color: rebeccapurple;
}
', '']]
I've tried importing the css-modules-require-hook in test-bundler.js for karma-webpack but that throws a bunch of errors.
WARNING in ./~/css-modules-require-hook/preset.js
Critical dependencies:
13:7-22 the request of a dependency is an expression
# ./~/css-modules-require-hook/preset.js 13:7-22
// many more warnings
ERROR in ./~/css-modules-require-hook/lib/index.js
Module not found: Error: Cannot resolve module 'fs' in /Users/qmmr/code/streetlife/composer/code/site/node_modules/css-modules-require-hook/lib
# ./~/css-modules-require-hook/lib/index.js 14:19-32
// more errors
PhantomJS 2.1.1 (Mac OS X 0.0.0) ERROR
SyntaxError: Unexpected token ')'
webpack.config.test.js
/* eslint-disable */
var path = require('path');
const CSS_MODULES_LOADER = [
'modules',
'importLoaders=1',
'localIdentName=[name]__[local]___[hash:base64:5]'
].join('&');
module.exports = {
resolve: {
extensions: [ '', '.js' ],
},
devtool: 'inline-source-map',
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel',
query: {
cacheDirectory: true,
plugins: [ 'transform-runtime', 'transform-class-properties', 'transform-export-extensions' ],
presets: [ 'es2015', 'react', 'stage-2' ],
}
},
{
test: /\.css$/,
loader: `css?${ CSS_MODULES_LOADER }`,
include: path.join(__dirname, '/css/modules'),
},
{ test: /\.json$/, loader: 'json' },
],
},
externals: {
'cheerio': 'window',
'react/addons': true,
'react/lib/ExecutionEnvironment': true,
'react/lib/ReactContext': true
},
};
karma.conf.js
// Karma configuration
var webpackConfig = require('./webpack.config.test');
module.exports = function(config) {
config.set({
basePath: '',
frameworks: [ 'mocha' ],
plugins: [
'karma-mocha',
'karma-phantomjs-launcher',
'karma-webpack-with-fast-source-maps'
],
files: [
{
pattern: './testBundler.js',
watched: false,
served: true,
included: true,
},
],
exclude: [],
preprocessors: {
[ './test-bundler.js' ]: [ 'webpack' ]
},
webpack: webpackConfig,
webpackMiddleware: {
noInfo: true,
stats: 'errors-only',
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: [ 'PhantomJS' ],
singleRun: true,
concurrency: Infinity,
})
}
test-bundler.js
// ---------------------------------------
// Test Environment Setup
// ---------------------------------------
import React from 'react';
import chai from 'chai';
import sinon from 'sinon';
import { shallow, mount } from 'enzyme';
// require('css-modules-require-hook/preset'); // Fix css-modules not rendering in tests
global.React = React;
global.expect = chai.expect;
global.sinon = sinon;
global.shallow = shallow;
global.mount = mount;
// ---------------------------------------
// Require Tests
// ---------------------------------------
// for use with karma-webpack-with-fast-source-maps
const __karmaWebpackManifest__ = new Array(); // eslint-disable-line
const inManifest = (path) => ~__karmaWebpackManifest__.indexOf(path);
const testsContext = require.context('../react', true, /\.test\.js$/);
// only run tests that have changed after the first pass.
const testsToRun = testsContext.keys().filter(inManifest);
(testsToRun.length ? testsToRun : testsContext.keys()).forEach(testsContext);
How can I use css-modules-require-hook in my setup (karma + webpack)?
EDIT: I've created a repository https://github.com/qmmr/yab to show the issue. When running npm run test:mocha the test passes. When running npm run test it fails (this is the karma-webpack integration).