How to get dynamic imports to work in webpack 4 - javascript

I'm trying to migrate my app to webpack 4. My head hurts already.
Dynamic imports - this is my method of code splitting (page by page). But I can't get it to work. Have set up very simple tester with following packages:
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-plugin-transform-async-to-generator": "^6.24.1",
"babel-polyfill": "^6.26.0",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"css-loader": "^0.28.11",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"mini-css-extract-plugin": "^0.4.0",
"react": "^16.4.1",
"react-dom": "^16.4.1",
"webpack": "^4.12.0",
"webpack-cli": "^3.0.8",
"webpack-dev-server": "^3.1.4"
}
Here is my main test app:
import React from "react";
import ReactDOM from "react-dom";
import style from "./main.css";
import pageLoader from './pageLoader';
class App extends React.Component {
render() {
let page = pageLoader();
return (
<div>
<p>React here!</p>
{page}
</div>
);
}
};
export default App;
ReactDOM.render(<App />, document.getElementById("app"));
and my page I want to load dynamically with separate bundle.
import React from "react";
import ReactDOM from "react-dom";
import style from "./main.css";
const Page1 = () => {
return (
<div>
<p>Page1 here!</p>
</div>
);
};
export default Page1;
Here's my webpack.config so far:
const path = require('path');
const HtmlWebPackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
entry: {
polyfill: 'babel-polyfill',
app: './src/index.js'
},
output: {
filename: '[name].bundle.js',
chunkFilename: '[name].bundle.js', //name of non-entry chunk files
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.html$/,
use: [
{
loader: "html-loader",
options: { minimize: true }
}
]
},
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, "css-loader"]
},
]
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html"
}),
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
})
]
};
Now here's the part that errors on build. Here's the function which calls the dynamic import:
function pageLoader() {
return import(/* webpackChunkName: "page1" */ './Page1')
.then(page => {
return page.default;
});
}
export default pageLoader;
I get this error on build:
ERROR in ./src/test/pageLoader.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: Unexpected token (2:8)
1 | function pageLoader() {
> 2 | return import(/* webpackChunkName: "page1" */ './Page1')
| ^
3 | .then(page => {
4 | return page;
5 | });
Everything I have read says this is the way to set this up. What am I doing wrong?

I was facing the same issue the fix was:
npm install --save-dev #babel/plugin-syntax-dynamic-import
add following line to .babelrc
"plugins": ["#babel/plugin-syntax-dynamic-import"],
Sources:
https://webpack.js.org/guides/code-splitting/#dynamic-imports
https://babeljs.io/docs/plugins/syntax-dynamic-import/#installation

Just an update for those going down this path: If you are using React, I would recommend react-loadable, makes it extremely easy to do dynamic imports on a per-component basis... a lot of large companies use it.

Related

Font awesome component not working inside vue custom elements

I have a vue 3 project, Where I created a custom element. But font-awesome component is not working inside that custom element.
main.ts
import {createApp, defineCustomElement} from 'vue';
import App from './App.vue';
import router from './router.ts';
import { FontAwesomeIcon } from '#fortawesome/vue-fontawesome';
import MyElement from './component/MyElement.ce.vue';
const myCustomElement = defineCustomElement(MyElement);
customElements.define(`my-custom-element`, myCustomElement);
const app = createApp(App);
app.use(router);
app.component('font-awesome-icon', FontAwesomeIcon);
app.mount("#app");
App.vue
<template>
<div>
<my-custom-element />
</div>
</template>
<script>
export default {
name:'MainApp'
}
</script>
./component/MyElement.ce.vue
<template>
<div>
<h1>my element should work with icon</h1>
<font-awesome-icon icon="fa-brands fa-twitter" />
</div>
</template>
<script>
import { library } from '#fortawesome/fontawesome-svg-core';
import { faTwitter } from '#fortawesome/free-brands-svg-icons';
library.add(faTwitter);
export default {
name: "MyElement",
}
</script>
<style>
h1{
color: red;
}
</style>
webpack.config.js
const path = require('path');
const { VueLoaderPlugin } = require('vue-loader');
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry: path.resolve(__dirname, './src/main.ts'),
output: {
path: path.resolve(__dirname, './dist'),
},
devServer: {
hot: true,
historyApiFallback: {
rewrites: [
{ from: /.*/, to: path.join('./', 'index.html') },
],
},
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options:{
compilerOptions:{
isCustomElement: (tag) => tag.includes('-')
}
}
},
{
test: /\.ts$/,
loader: 'ts-loader',
options: {
appendTsSuffixTo: [/\.vue$/]
}
},
{
test: /\.css$/i,
use: ["css-loader"],
},
]
},
plugins: [
new VueLoaderPlugin(),
new HtmlWebpackPlugin({
template: path.resolve(__dirname, './index.html'),
inject: 'body',
}),
]
}
package.json
{
"dependencies": {
"#fortawesome/fontawesome-svg-core": "^6.2.1",
"#fortawesome/free-brands-svg-icons": "^6.2.1",
"#fortawesome/free-regular-svg-icons": "^6.2.1",
"#fortawesome/free-solid-svg-icons": "^6.2.1",
"#fortawesome/vue-fontawesome": "^3.0.2",
"#vue/compiler-sfc": "^3.2.41",
"fine-uploader": "^5.16.2",
"fine-uploader-wrappers": "^1.0.1",
"html-webpack-plugin": "^5.5.0",
"ts-loader": "^9.4.1",
"typescript": "^4.8.4",
"vue": "^3.2.41",
"vue-loader": "^17.0.0",
"vue-router": "^4.1.6",
"webpack": "^5.74.0",
"webpack-dev-server": "^4.11.1"
},
"devDependencies": {
"css-loader": "^6.7.2",
"webpack-cli": "^4.10.0"
},
"scripts": {
"start": "webpack-dev-server --mode development"
}
}
Everything works including the style but FontAwesomeIcon is not working as it is supposed to.
This is what it shows in the browser
Can anyone point me in the right direction? Any help would be appreciated.
checkout if your icon available in fontawesome version 6.2.1
Turns out there is an npm package vue3-webcomponent-wrapper. I implemented it and used i tag of font-awesome which solved my issue. I don't know if this is the perfect solution but this is the only solution I found.

React Component Library with Webpack 5 and Babel 7 ERROR in ./src/index.js Module parse failed: Unexpected token

My goal:
I am creating a React component library in JavaScript with Webpack 5 and Babel 7 that is published to npm. I want consumers to import individual components into their React apps. I also want to add a development server for stakeholders to add components to the component library.
When running the app locally with 'npm run build && npm run serve' (npx webpack serve) I keep getting this error message:
ERROR in ./src/index.js 20:2
Module parse failed: Unexpected token (20:2)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|
| root.render(
> <App />
| );
Here is my setup:
./webpack.config.common.js
const path = require('path');
module.exports = {
entry: {
index: './src/index.js',
MyCoolButton: './src/components/buttons/MyCoolButton',
RandomButton: './src/components/buttons/RandomButton',
StyledButton: './src/components/buttons/StyledButton',
theme: './src/tokens/Theme'
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
},
optimization: {
runtimeChunk: 'single',
},
resolve: {
alias: {
path: path.resolve(__dirname, 'src')
},
extensions: ['.js', '.jsx']
},
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",
],
},
{
// The test property identifies which file or files should be transformed
test: /\.(js|jsx)$/,
resolve: {
extensions: [".js", ".jsx"]
},
exclude: /[\\/]node_modules[\\/]/,
// The use property indicates which loader should be used to do the transforming.
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env', '#babel/preset-react']
}
},
},
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
}
],
},
};
./webpack.config.prod.js
const { merge } = require('webpack-merge');
const commonConfig = require('./webpack.config.common');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = merge(commonConfig, {
mode: 'production',
// do not include source maps on prod build
// devtool: 'inline-source-map',
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
// Load css to separate file
MiniCssExtractPlugin.loader,
// Translates CSS into CommonJS
'css-loader',
// Compiles Sass to CSS
'sass-loader',
],
},
],
},
optimization: {
// minimize: true,
minimizer: [
// For webpack#5 you can use the `...` syntax to extend existing minimizers (i.e. `terser-webpack-plugin`), uncomment the next line
// `...`,
new CssMinimizerPlugin({
test: /\.foo\.css$/i,
}),
new TerserPlugin({
terserOptions: {
parse: {
// We want terser to parse ecma 8 code. However, we don't want it
// to apply minification steps that turns valid ecma 5 code
// into invalid ecma 5 code. This is why the `compress` and `output`
ecma: 8,
},
compress: {
ecma: 5,
inline: 2,
},
mangle: {
// Find work around for Safari 10+
safari10: true,
},
output: {
ecma: 5,
comments: false,
}
},
// Use multi-process parallel running to improve the build speed
parallel: true,
}),
],
},
plugins: [
new CleanWebpackPlugin(),
new MiniCssExtractPlugin({
filename: 'styles.[contenthash].css',
})
],
// As you publish your code as React component, apart from set React as peer dependency you have to set the react as externals to use the react at the consumer library.
externals: {
'react': {
commonjs: 'react',
commonjs2: 'react',
amd: 'React',
root: 'React'
},
'react-dom': {
commonjs: 'react-dom',
commonjs2: 'react-dom',
amd: 'ReactDOM',
root: 'ReactDOM'
}
},
});
./babel.config.js
{
"plugins": [
"babel-plugin-module-resolver"
],
"presets": [
["#babel/preset-env"], // instead of "#babel/preset-es2015",
["#babel/preset-react"]
]
}
./src/index.js
export {default as MyCoolButton} from './components/buttons/MyCoolButton';
export {default as RandomButton} from './components/buttons/RandomButton';
export {default as StyledButton} from './components/buttons/StyledButton';
export {theme} from './tokens/Theme';
import './tokens/theme.scss'; // need import to generate minified css flat file
// kitchen sink for component development
import React from "react";
import { createRoot } from 'react-dom/client';
import App from './App';
const rootElement = document.getElementById('app');
const root = createRoot(rootElement);
root.render(
<App />
);
App.jsx
import React, { Component } from 'react';
import StyledButton from "./components/buttons/StyledButton";
import RandomButton from "./components/buttons/RandomButton";
class App extends Component {
render() {
return (
<div>
<div className='container body'>
<div className='row'>
<div className='col-12 text-center mb-4 mt-4'>
<h1>Welcome to the Kitchen Sink Page</h1>
</div>
<div className='col-6'>
<RandomButton />
</div>
<div className='col-6'>
<StyledButton />
</div>
</div>
</div>
</div>
);
}
}
export default App;
and my package.json
...
"peerDependencies": {
"prop-types": "^15.6.0",
"react": "^16.0.0",
"react-dom": "^16.0.0",
"babel-core": "^6.0.0",
"webpack": "^4.0.0"
},
"devDependencies": {
"#babel/cli": "^7.17.0",
"#babel/core": "^7.17.2",
"#babel/preset-env": "^7.16.11",
"#babel/preset-react": "^7.16.7",
"#semantic-release/changelog": "^6.0.1",
"#semantic-release/commit-analyzer": "^9.0.2",
"#semantic-release/git": "^10.0.1",
"#semantic-release/npm": "^9.0.0",
"#semantic-release/release-notes-generator": "^10.0.3",
"#testing-library/react": "^12.1.2",
"babel-core": "^7.0.0-bridge.0",
"babel-loader": "^7.1.5",
"babel-plugin-module-resolver": "^4.1.0",
"commitizen": "^4.2.4",
"css-loader": "^6.6.0",
"css-minimizer-webpack-plugin": "^3.4.1",
"cz-conventional-changelog": "^3.3.0",
"eslint": "^8.8.0",
"eslint-plugin-jest": "^26.1.0",
"eslint-plugin-react": "^7.28.0",
"jest": "^27.5.0",
"path": "^0.12.7",
"prop-types": "^15.6.0",
"react": "^18.0.0",
"react-dom": "^18.0.0",
"sass": "^1.49.7",
"sass-loader": "^12.4.0",
"semantic-release": "^19.0.2",
"style-loader": "^1.3.0",
"styled-components": "^5.3.3",
"webpack": "^5.68.0",
"webpack-cli": "^4.9.2",
"webpack-dev-server": "^4.7.4"
},
"dependencies": {
"babel-plugin-styled-components": "^2.0.2",
"babel-preset-react": "^6.24.1",
"clean-webpack-plugin": "^4.0.0",
"html-webpack-plugin": "^5.5.0",
"mini-css-extract-plugin": "^2.5.3",
"optimize-css-assets-webpack-plugin": "^6.0.1",
"terser-webpack-plugin": "^5.3.1",
"webpack-merge": "^5.8.0"
},
...
I have browsed countless stackoverflow posts and answers, blog posts and I am having a hard time debugging this 'unexpected token' error.
I am new to Webpack so if anyone can see if I am doing something wrong in the Webpack config files, in way the React app is being bundled, or by loading Babel loaders, I would really appreciate some pointers.

Error while building code with Istanbul plugin

I am trying to generate a code coverage report for my ReactJS project with babel-istanbul-plugin. When I add "istanbul" as a plugin in my .babelrc file and ty to build, I get this error:
ERROR in ./src/entryPoints/App.jsx
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: /Users/kuli/Sites/persona/src/entryPoints/App.jsx: You gave us a visitor for the node type "ClassPrivateProperty" but it's not a valid type
at verify (/Users/kuli/Sites/persona/node_modules/babel-traverse/lib/visitors.js:196:13)
at Object.explode (/Users/kuli/Sites/persona/node_modules/babel-traverse/lib/visitors.js:72:3)
at traverse (/Users/kuli/Sites/persona/node_modules/babel-traverse/lib/index.js:77:12)
at NodePath.traverse (/Users/kuli/Sites/persona/node_modules/babel-traverse/lib/path/index.js:144:25)
at Object.enter (/Users/kuli/Sites/persona/node_modules/istanbul-lib-instrument/dist/visitor.js:611:12)
at PluginPass.enter (/Users/kuli/Sites/persona/node_modules/babel-plugin-istanbul/lib/index.js:90:23)
at newFn (/Users/kuli/Sites/persona/node_modules/babel-traverse/lib/visitors.js:276:21)
at NodePath._call (/Users/kuli/Sites/persona/node_modules/babel-traverse/lib/path/context.js:76:18)
at NodePath.call (/Users/kuli/Sites/persona/node_modules/babel-traverse/lib/path/context.js:48:17)
at NodePath.visit (/Users/kuli/Sites/persona/node_modules/babel-traverse/lib/path/context.js:105:12)
at TraversalContext.visitQueue (/Users/kuli/Sites/persona/node_modules/babel-traverse/lib/context.js:150:16)
at TraversalContext.visitSingle (/Users/kuli/Sites/persona/node_modules/babel-traverse/lib/context.js:108:19)
at TraversalContext.visit (/Users/kuli/Sites/persona/node_modules/babel-traverse/lib/context.js:192:19)
at Function.traverse.node (/Users/kuli/Sites/persona/node_modules/babel-traverse/lib/index.js:114:17)
at traverse (/Users/kuli/Sites/persona/node_modules/babel-traverse/lib/index.js:79:12)
at File.transform (/Users/kuli/Sites/persona/node_modules/babel-core/lib/transformation/file/index.js:548:35)
at /Users/kuli/Sites/persona/node_modules/babel-core/lib/transformation/pipeline.js:50:19
at File.wrap (/Users/kuli/Sites/persona/node_modules/babel-core/lib/transformation/file/index.js:564:16)
at Pipeline.transform (/Users/kuli/Sites/persona/node_modules/babel-core/lib/transformation/pipeline.js:47:17)
at transpile (/Users/kuli/Sites/persona/node_modules/babel-loader/lib/index.js:50:20)
at Object.module.exports (/Users/kuli/Sites/persona/node_modules/babel-loader/lib/index.js:173:20)
# multi babel-polyfill ./src/entryPoints/App.jsx App[1]
I am adding all the info i think is relevant. Please let me know if you need any more.
My .babelrc file:
{
"presets": ["env", "stage-0", "react"],
"plugins": [
"istanbul",
"react-hot-loader/babel",
"transform-decorators-legacy"
]
}
App.jsx file:
import React from 'react';
import ReactDOM from 'react-dom';
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import { BrowserRouter, Route } from 'react-router-dom';
import rootReducer from './profile/reducers/index.js';
import ErrorBoundary from './profile/components/ErrorBoundary';
import App from './profile/components/App.js';
const store = createStore(
rootReducer,
compose(
applyMiddleware(thunk),
window.devToolsExtension ? window.devToolsExtension() : f => f
)
);
ReactDOM.render(
<Provider store={store}>
<ErrorBoundary>
<BrowserRouter>
<div>
<Route path="/" component={App}/>
</div>
</BrowserRouter>
</ErrorBoundary>
</Provider>,
document.getElementById('root')
);
if (module.hot) {
module.hot.accept();
}
Dev Dependencies:
"devDependencies": {
"ajv": "6.2.1",
"babel-core": "6.26.0",
"babel-eslint": "^6.1.2",
"babel-loader": "7.1.4",
"babel-polyfill": "6.26.0",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "6.24.1",
"babel-preset-stage-0": "^6.24.1",
"classnames": "^2.2.5",
"css-loader": "0.23.1",
"dotenv": "^7.0.0",
"eslint": "^3.19.0",
"eslint-loader": "^1.5.0",
"eslint-plugin-react": "^5.0.1",
"file-loader": "^0.9.0",
"html-webpack-plugin": "3.2.0",
"json-loader": "^0.5.4",
"node-sass": "^4.9.2",
"postcss-loader": "^0.9.1",
"prettier-eslint": "^8.8.2",
"react-hot-loader": "^4.3.3",
"redux-devtools": "^3.2.0",
"redux-devtools-dock-monitor": "^1.1.1",
"redux-devtools-log-monitor": "^1.0.11",
"rimraf": "^2.5.2",
"sass-loader": "^7.0.3",
"stats-webpack-plugin": "^0.3.1",
"style-loader": "0.13.1",
"url-loader": "0.5.7",
"webpack": "^4.16.2",
"webpack-cleanup-plugin": "0.5.1",
"webpack-cli": "^3.1.0",
"webpack-dev-server": "^3.1.5"
}
webpack.config.js
const webpack = require('webpack');
const path = require('path');
const loaders = require('./webpack.loaders');
const commonConfig = require('./webpack.common');
var HtmlWebpackPlugin = require('html-webpack-plugin');
// const envKeys = commonConfig.getEnvKeys();
module.exports = {
entry: {
workflow: ['babel-polyfill', './src/index'],
},
output: commonConfig.output,
// https://webpack.js.org/configuration/devtool/#devtool
devtool: 'cheap-module-source-map',
resolve: {
extensions: commonConfig.extensions,
alias: commonConfig.alias,
},
module: {
rules: [{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loaders: ['babel-loader'],
},
{
test: /\.(s?)css$/,
loader: ['style-loader', 'css-loader', 'sass-loader']
},
{
test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
loader: "file"
},
{
test: /\.(woff|woff2)$/,
loader: "url?prefix=font/&limit=5000"
},
{
test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
loader: "url?limit=10000&mimetype=application/octet-stream"
},
{
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
loader: "url?limit=10000&mimetype=image/svg+xml"
},
{
test: /\.gif/,
loader: "url-loader?limit=10000&mimetype=image/gif"
},
{
test: /\.jpg/,
loader: "url-loader?limit=10000&mimetype=image/jpg"
},
{
test: /\.png/,
loader: "url-loader?limit=10000&mimetype=image/png"
}
]
},
plugins: [
// new webpack.HotModuleReplacementPlugin(),
new webpack.DefinePlugin('development'),
new HtmlWebpackPlugin({
template: './src/index.html'
})
],
devServer: {
contentBase: path.join(__dirname, 'build'),
compress: true,
port: 9003
},
};
Thanks for your help.
It seems to be an issue with babel itself =>
https://github.com/babel/babel/issues/10065
Run across the same problem today when deleting my package-lock and my npm cache.
Turns out it was the package istanbul-lib-instrument who got updated to 3.1.0 to 3.3.0 which was importing a bad version of babel-types.
Just fixed the version of istanbul-lib-instrument and everything was okay.
It can be babel-eslint also in your case.

Hot Module Replacement with Webpack, Express & Babel (babel-loader) not working with React Components (Error: Ignored an update to unaccepted module)

I am new to React webpack and such and I am trying to implement Hot Module replacement into my workflow. I am using webpack, express, Babel ES6 with React and I believe I have all the loaders that i need.
I have got HMR working for my CSS files and it updates CSS perfectly but for some reason, when I try and update a React component, I get the following error and have to refresh the page in order to see my changes. I've been struggling the whole day so any assistance would be greatly received! The error I get is the following (my code follows afterward):
>Ignored an update to unaccepted module 28 -> 17
>
[HMR] The following modules couldn't be hot updated: (Full reload needed)
This is usually because the modules which have changed (and their parents) do not know how to hot reload themselves. See https://webpack.js.org/concepts/hot-module-replacement/ for more details.
>
[HMR] - ./app/scripts/libs/index.js
index.js (Entry)
import React from 'react';
import ReactDOM from 'react-dom';
import style from 'css/main.css';
import Sections from 'components/Sections/index.js';
ReactDOM.render(
<div>
<h2>Hek</h2>
<Sections></Sections>
</div>,
document.getElementById('app')
)
console.log('check for me');
index.js (Sections Component)
import React from 'react';
import ReactDOM from 'react-dom';
export class Sections extends React.Component{
render(){
return(
<div>
<h1>Yo yo yo wahts</h1>
<p>hlfgdfd</p>
</div>
)
}
}
module.exports = Sections;
BuildScript.js
'use strict';
var express = require('express'); //get the express module
var webpack = require('webpack');
var webpackDevMiddleware = require('webpack-dev-middleware');
var webpackHotMiddleware = require('webpack-hot-middleware');
var app = express(); //create a new instance of that class
var config = require('../../../webpack.config.js');
var compiler = webpack(config);
app.use(webpackDevMiddleware(compiler, {
publicPath: config.output.publicPath
}));
app.use(webpackHotMiddleware(compiler));
app.listen(3000, function () {
// return console.log('Example app listening on port 3000!');
});
Webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const webpack = require('webpack');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
module.exports = {
entry: [ 'webpack-hot-middleware/client' , './app/scripts/libs/index.js'], //Can also use "main" property
output: {
path: path.resolve(__dirname, 'tmp'), //resolves the absolute path
filename: '[name].bundle.js', //
publicPath: '/'
},
devtool: 'inline-source-map',
resolve:{
alias: {
components: path.resolve(__dirname, 'app/scripts/components'),
fonts: path.resolve(__dirname, 'app/scripts/fonts'),
images: path.resolve(__dirname, 'app/images'),
sass: path.resolve(__dirname, 'app/styles/sass'),
css: path.resolve(__dirname, 'app/styles/css')
}
},
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader'] //to use the CSS imported - in your index.js file you
},
{
test: /\.scss$/,
use: ['style-loader', 'css-loader', 'sass-loader']
},
{
test: /\.(jpg|png|svg|gif)$/,
use:['file-loader']
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: ['file-loader']
},
{
test: /\.js$/,
loader: 'babel-loader',
query: {
presets: ['env', 'react']
}
}
]
},
plugins:[
new HtmlWebpackPlugin({
title: 'African Banker Awards 2018',
template: './app/scripts/libs/template.ejs',
inject: 'body'
}),
new CleanWebpackPlugin(['tmp']),
new webpack.HotModuleReplacementPlugin()
//new UglifyJsPlugin()
]
};
NPM Packages Installed
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-plugin-syntax-dynamic-import": "^6.18.0",
"babel-preset-env": "^1.6.1",
"babel-preset-react": "^6.24.1",
"clean-webpack-plugin": "^0.1.17",
"css-loader": "^0.28.7",
"eslint": "^4.10.0",
"file-loader": "^1.1.5",
"html-webpack-plugin": "^2.30.1",
"install": "^0.10.1",
"npm": "^5.5.1",
"sass-loader": "^6.0.6",
"style-loader": "^0.19.0",
"uglifyjs-webpack-plugin": "^1.1.4",
"webpack": "^3.10.0",
"webpack-dev-middleware": "^2.0.1",
"webpack-hot-middleware": "^2.21.0"
}
}

Importing react with webpack Error: Cannot resolve module 'react'

I'm getting an error Error: Cannot resolve module 'react' (and react-dom) with webpack. This has to be the hardest project setup I've had to deal with and I'm really not sure why its not working. I've also checked for similar issues on so, and can't seem to find a solution.
webpack.config.js
module.exports = {
entry: './static/js/base/base.jsx',
output: {
path: __dirname + '/static/scripts',
filename: 'bundle.js'
},
resolve: {
extensions: ['', '.js', '.jsx']
},
module: {
loaders: [
{
test: /\.jsx?$/,
loader: 'babel',
exclude: /node_modules/,
query: {
cacheDirectory: true,
presets: ['react', 'es2015']
}
}
]
}
}
base.jsx
import React from 'react';
import ReactDOM from 'react-dom';
class Navigation extends React.Component {
// ...
constructor(props) {
super(props);
[
// Functions & Event Handlers declaration
].forEach(method => { this[method] = this[method].bind(this); });
this.state = {
hello: 'Hello World!',
};
}
render() {
return (
<div>
<div href="#" class="header item">
WINPMP Login
</div>
<div class="right menu">
<a class="ui primary button item">Students</a>
<a class="ui button item">Teachers</a>
</div>
</div>
);
}
}
React.render(<Navigation/>, document.getElementById('nav'));
I've run npm install, everything is there. Why won't it import properly? How can I make this work?
And my package.json
"devDependencies": {
"babel": "^6.5.2",
"babel-core": "^6.11.4",
"babel-loader": "^6.2.4",
"babel-preset-es2015": "^6.9.0",
"babel-preset-react": "^6.11.1",
"bower": "^1.7.9",
"react": "^15.2.1",
"react-dom": "^15.2.1",
"webpack": "^1.13.1",
"webpack-dev-server": "^1.14.1"
}
Try creating a .babelrc file in your project root which looks like this:
{
presets: [
"es2015", "react"
]
}
and pull out the 'query' field from your webpack config 'loader'

Categories

Resources