So let me start my saying I am fairly new to WebPack and React, but I have something basic working (at least it works in the browser). I am however an ok C# developer, so want to use Visual Studio as my editor of choice. I have created a fairly simple webpack setup and created a dummy solution file (Visual Studio 2015 update 3), where I have created a web site from file system.
I have a working (in the browser) Webpack + TypeScript + React + Babel setup which as I say works famously in the browser. It is largely based on the official guidelines for using TypeScript with React https://www.typescriptlang.org/docs/handbook/react-&-webpack.html
I have followed that tutorial to the letter and even though it runs in the browser just fine also suffers from the same issue as my richer webpack setup.
So what is the issue exactly?
The main issue is that my setup doesn't seem to recognise "React" as a valid module import inside of a TSX file (even though everything is fine in the browser).
I have have read so many posts that talk about different Webpack settings, and tsconfig.json settings that my head is spinning.
I thought it might be better to show you some of my files to see if anyone knows how to fix my issue
.babelrc
{ "presets": ["es2015"] }
package.json (I am using NPM)
{
"name": "task1webpackconfig",
"version": "1.0.0",
"description": "webpack 2 + TypeScript 2 + Babel example",
"repository": {
"type": "git",
"url": "git+https://github.com/sachabarber/MadCapIdea.git"
},
"keywords": [
"babel",
"typescript",
"webpack",
"bundling",
"javascript",
"npm"
],
"author": "sacha barber",
"homepage": "https://github.com/sachabarber/MadCapIdea#readme",
"dependencies": {
"#types/react": "^15.0.23",
"#types/react-dom": "^15.5.0",
"lodash": "^4.17.4",
"react": "^15.5.4",
"react-dom": "^15.5.4"
},
"devDependencies": {
"#types/lodash": "^4.14.63",
"#types/react": "^15.0.23",
"#types/react-dom": "^15.5.0",
"awesome-typescript-loader": "^3.1.3",
"babel-core": "^6.24.1",
"babel-loader": "^7.0.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-es2015-native-modules": "^6.9.4",
"source-map-loader": "^0.2.1",
"typescript": "^2.3.2",
"webpack": "^2.4.1"
}
}
tsconfig.json
{
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"moduleResolution": "Node",
"outDir": "./dist/",
"sourceMap": true,
"noImplicitAny": true,
"module": "commonjs",
"target": "es5",
"jsx": "react"
},
"include": [
"./src/**/*"
]
}
webpack.config.js
let _ = require('lodash');
let webpack = require('webpack');
let path = require('path');
let babelOptions = {
"presets": ["es2015"]
};
function isVendor(module) {
return module.context && module.context.indexOf('node_modules') !== -1;
}
let entries = {
index: './index.tsx'
};
module.exports = {
context: __dirname + '/src',
entry: entries,
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
},
devServer: {
open: true, // to open the local server in browser
contentBase: __dirname,
},
// Enable sourcemaps for debugging webpack's output.
devtool: "source-map",
resolve: {
extensions: [".tsx", ".ts", ".js", ".jsx"],
modules: [path.resolve(__dirname, "src"), "node_modules"]
//modulesDirectories: ['src', 'node_modules'],
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
names: ['vendor'],
minChunks: function (module, count) {
// creates a common vendor js file for libraries in node_modules
return isVendor(module);
}
}),
new webpack.optimize.CommonsChunkPlugin({
name: "commons",
chunks: _.keys(entries),
minChunks: function (module, count) {
// creates a common vendor js file for libraries in node_modules
return !isVendor(module) && count > 1;
}
})
],
module: {
rules: [
// All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader' 1st
// then 'babel-loader'
// NOTE : loaders run right to left (think of them as a cmd line pipe)
{
test: /\.ts(x?)$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: babelOptions
},
{
loader: 'awesome-typescript-loader'
}
]
},
// All files with a '.js' extension will be handled by 'babel-loader'.
{
test: /\.js$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: babelOptions
}
]
},
// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
{
enforce: "pre",
test: /\.js$/,
loader: "source-map-loader"
}
]
}
};
When I run webpack all seems fine
Some of you may be wondering about my project structure which looks like this
And let me just show you that the typings for React/ReactDom are also present
Like I say when I run this, all seems ok, I get what I expect
A working react web page
A set of bundle files (which Index.html uses)
A Source map for my code
So this tells me the React module can be loaded by webpack/browser are working ok.
But when I try and edit the TSX (typescript JSX files) I see this
Typescript is 100% working for my own files, just cant seem to see React stuff.
Like I say I have tried so many suggested fixes and none have worked, please help me someone
Related
I get an error when importing #material-ui to my React component.
Module not found: Error: Can't resolve './utils.
I can import other libraries like lodash but with #material-ui there's issue. I tried reinstall node_modules but error still occur.
import React, { useEffect } from "react";
import _ from "lodash";
import Button from "#material-ui/core";
export default function Dashboard() {
useEffect(() => {
console.log("Test");
const testVar = "test";
console.log(_.split(testVar));
return () => {
// cleanup;
};
}, []);
return (
<div>
<Button>Login</Button>
</div>
);
package.json
{
"name": "views",
"version": "1.0.0",
"description": "",
"main": "index.js",
"dependencies": {
"#material-ui/core": "^4.10.2",
"#material-ui/icons": "^4.9.1",
"lodash": "^4.17.15",
"react": "^16.13.1",
"react-dom": "^16.13.1"
},
"devDependencies": {
"#types/lodash": "^4.14.157",
"#types/react": "^16.9.38",
"#types/react-dom": "^16.9.8",
"source-map-loader": "^1.0.0",
"ts-loader": "^7.0.5",
"typescript": "^3.9.5",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.12"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack --mode=development --watch --progress",
"dev:nowatch": "webpack --mode=development"
},
"keywords": [],
"author": "",
"license": "ISC"
}
webpack.config.js
var path = require("path");
module.exports = {
mode: "development",
// Enable sourcemaps for debugging webpack's output.
devtool: "source-map",
entry: {
dashboard: "./Dashboard/index",
// creator: "./Creator/index",
},
output: {
path: path.resolve(__dirname, ""),
filename: "./[name]/dist/index.js",
},
resolve: {
// Add '.ts' and '.tsx' as resolvable extensions.
extensions: [".ts", ".tsx"],
modules: [path.resolve(__dirname, "./"), "node_modules"],
},
module: {
rules: [
{
test: /\.ts(x?)$/,
exclude: /node_modules/,
use: [
{
loader: "ts-loader",
},
],
},
// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
{
enforce: "pre",
test: /\.js$/,
loader: "source-map-loader",
},
],
},
// When importing a module whose path matches one of the following, just
// assume a corresponding global variable exists and use that instead.
// This is important because it allows us to avoid bundling all of our
// dependencies, which allows browsers to cache those libraries between builds.
externals: {
react: "React",
"react-dom": "ReactDOM",
},
};
tsconfig.json
{
"compilerOptions": {
"lib": ["es6", "dom"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"outDir": "./dist/",
"sourceMap": true,
"target": "es5",
"jsx": "react",
"allowJs": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true
}
}
Example errors
ERROR in ./node_modules/#material-ui/core/esm/index.js
Module not found: Error: Can't resolve './withMobileDialog' in 'C:\Users\user\Documents\Code\calendarapp\UI\Client\views\node_modules\#material-ui\core\esm'
# ./node_modules/#material-ui/core/esm/index.js 240:0-65 240:0-65 241:0-35 241:0-35
# ./Dashboard/Dashboard.tsx
# ./Dashboard/App.tsx
# ./Dashboard/index.tsx
ERROR in ./node_modules/#material-ui/core/esm/index.js
Module not found: Error: Can't resolve './withWidth' in 'C:\Users\user\Documents\Code\calendarapp\UI\Client\views\node_modules\#material-ui\core\esm'
# ./node_modules/#material-ui/core/esm/index.js 242:0-51 242:0-51 243:0-28 243:0-28
# ./Dashboard/Dashboard.tsx
# ./Dashboard/App.tsx
# ./Dashboard/index.tsx
Found solution.
In webpack.config.js add ".js", ".jsx" to resolve.
resolve: {
// Add '.ts' and '.tsx' as resolvable extensions.
extensions: [".ts", ".tsx", ".js", ".jsx"],
},
If I can add something and if I remember correctly, the import Button from "#material-ui/core"; should have curly brackets around "Button" like so import {Button} from "#material-ui/core";
First create your react app
Then
Install material ui core and icons modules
Then
Go package.json and check dependencies if found material ui core and icons then first copy icons line
Then paste on file which u use like as index.js
Then
U only add /icon name
For example:-
Import add from #material-ui/icons
You add only
#material-ui/icons/add
💯% solved with proof
I am trying to add react components (typescript) in the form of .tsx files to be rendered on some of my asp.net core mvc .cshtml pages but cannot seem to get things working properly. Is there a good way to do this?
You basically need to use webpack and modify your .csproj to do a yarn build before running to transpile your typescript and connect all of the dependencies into a bundle.
Start by adding Nuget packages: Yarn.MSBuild and Microsoft.TypeScript.MSBuild to your project.
tsconfig.json: (put in root dir of your project)
{
"typeAcquisition": {
"enable": true
},
"compileOnSave": false,
"compilerOptions": {
"sourceMap": true,
"module": "commonjs",
"target": "es6",
"noImplicitAny": false,
"jsx": "react",
"outDir": "wwwroot/dist",
"moduleResolution": "node"
},
"exclude": [
"node_modules",
"wwwroot"
]
}
^^Note that this will make it so that your .tsx files transpile into folder: wwwroot/dist, change outDir if you want it somewhere else
package.json (put in root dir of your project)
{
"scripts": {
"webpack": "webpack"
},
"devDependencies": {
"#types/react": "^16.4.6",
"#types/react-dom": "^16.0.6",
"#types/webpack-env": "^1.13.6",
"aspnet-webpack": "^3.0.0",
"awesome-typescript-loader": "^5.2.0",
"babel-core": "^6.26.3",
"bootstrap": "4.3.1",
"clean-webpack-plugin": "^0.1.19",
"typescript": "^2.9.2",
"webpack": "^4.15.1",
"webpack-cli": "^3.0.8",
"webpack-dev-middleware": "^3.1.3",
"webpack-hot-middleware": "^2.22.2"
},
"dependencies": {
"react": "^16.4.1",
"react-dom": "^16.4.1",
"react-hot-loader": "^4.0.0"
}
}
^^add whatever npm dependencies you need in your package.json (obviously) as well as your typescript #type dependencies. These are just the minimum viable packages for react and hot reloading.
Webpack.targets (put in root dir of your project)
<Project>
<Target Name="EnsureNodeModulesInstalled"
BeforeTargets="Build"
Inputs="yarn.lock;package.json"
Outputs="node_modules/.yarn-integrity">
<Yarn Command="install" />
</Target>
<Target Name="PublishWebpack"
BeforeTargets="Publish">
<ConvertToAbsolutePath Paths="$(PublishDir)">
<Output TaskParameter="AbsolutePaths" PropertyName="AbsPublishDir" />
</ConvertToAbsolutePath>
<Yarn Command="run webpack --env.prod --env.publishDir=$(AbsPublishDir)" />
</Target>
</Project>
^^this file Webpack.target is to be added to your .csproj file (I added it at the end) and should be added like so:
In your .csproj:
<Import Project="Webpack.targets" />
webpack.config.js: (put in root dir of your project)
const path = require('path');
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = (env) => {
const isDevBuild = !(env && env.prod);
const outputDir = (env && env.publishDir)
? env.publishDir
: __dirname;
return [{
mode: isDevBuild ? 'development' : 'production',
devtool: 'inline-source-map',
stats: { modules: false },
entry: {
'App': './ClientApp/App.tsx',
},
watchOptions: {
ignored: /node_modules/
},
output: {
filename: "dist/[name].js",
path: path.join(outputDir, 'wwwroot'),
publicPath: '/'
},
resolve: {
// Add '.ts' and '.tsx' as resolvable extensions.
extensions: [".ts", ".tsx", ".js", ".json"]
},
devServer: {
hot: true
},
module: {
rules: [
// All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
{
test: /\.tsx?$/,
include: /ClientApp/,
loader: [
{
loader: 'awesome-typescript-loader',
options: {
useCache: true,
useBabel: true,
babelOptions: {
babelrc: false,
plugins: ['react-hot-loader/babel'],
}
}
}
]
}
]
},
plugins: [
new CleanWebpackPlugin(path.join(outputDir, 'wwwroot', 'dist')),
new CheckerPlugin()
]
}];
};
^^Note the entry point and modules->rules->include. That means webpack is being configured to look in a folder called ClientApp (in the root dir of your project) for the .tsx files to be transpiled. If you want your .tsx files elsewhere simply change these up. The entry point also specifies that the file entry point is App.tsx, put your highest level react component (that depends on all of your other components) into here or simply include it in this file.
Now add WebpackDevMiddleware to your Startup->Configure function:
app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
{
HotModuleReplacement = true
});
Now if in your App.tsx file you select a div (say one with id: 'root') and render your component in it, all you need to do to add your React component to your .cshtml file is include the transpiled App.js (in wwwroot/dist) to the .cshtml along with a div with id: 'root' and bam. You have react components that can be added to .cshtml without using any SPA bs 🚀
Credit:
https://natemcmaster.com/blog/2018/07/05/aspnetcore-hmr/
I have a React build configuration using Webpack, ESlint, Prettier and TypeScript.
When I run the build it looks like I'm getting TypeScript linting errors that should be nullified by the #typings/react or #typings/react-dom packages.
Looking at the documentation I shouldn't need to define accessibility modifiers or return types for React Components: https://www.typescriptlang.org/docs/handbook/jsx.html
This seems like the same issue as here: Missing return type on function - in react (typescript) code
but installing the typings packages hasn't resolved the issue for me. Please note, I have also tried removing the #typings/react package as the #typings/react-dom has this as a dependency and this doesn't resolve the issue.
Webpack config
const webpack = require('webpack');
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
const path = require('path');
const createWebpackConfig = () => {
const isProd =
process.env &&
process.env.NODE_ENV &&
process.env.NODE_ENV === 'production';
return {
entry: ['#babel/polyfill', './index.tsx'],
mode: isProd ? 'production' : 'development',
module: {
rules: [
{
enforce: 'pre',
test: /(\.jsx|\.js|\.ts|\.tsx)$/,
exclude: /node_modules/,
loader: 'eslint-loader'
},
{
test: /(\.jsx|\.js)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
'#babel/preset-react',
[
'#babel/preset-env',
{
targets: 'cover 99.5% in GB'
}
]
],
plugins: [
'#babel/plugin-proposal-class-properties',
'#babel/plugin-proposal-object-rest-spread'
],
cacheDirectory: true
}
}
},
{
test: /(\.tsx|\.ts)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
'#babel/preset-typescript',
'#babel/preset-react',
[
'#babel/preset-env',
{
targets: 'cover 99.5% in GB'
}
]
],
plugins: [
'#babel/plugin-proposal-class-properties',
'#babel/plugin-proposal-object-rest-spread'
],
cacheDirectory: true
}
}
}
]
},
resolve: {
modules: [path.resolve(__dirname, '/'), 'node_modules'],
extensions: ['.ts', '.tsx', '.js', '.jsx'],
enforceExtension: false
},
target: 'web',
optimization: {
splitChunks: {
chunks: 'all',
maxInitialRequests: Infinity,
minSize: 0,
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendor'
},
main: {
name: 'main'
}
}
}
},
output: {
path: path.join(__dirname, 'bundles'),
filename: '[name].app.js',
chunkFilename: '[name].bundle.js',
pathinfo: true
},
plugins: [
new CaseSensitivePathsPlugin(),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(isProd ? 'production' : 'development')
}
})
]
};
};
module.exports = createWebpackConfig;
ESLint config
{
"parser": "#typescript-eslint/parser", // Specifies the ESLint parser
"extends": [
"plugin:react/recommended",
"plugin:#typescript-eslint/recommended", // Uses the recommended rules from the #typescript-eslint/eslint-plugin
"prettier/#typescript-eslint", // Uses eslint-config-prettier to disable ESLint rules from #typescript-eslint/eslint-plugin that would conflict with prettier
"plugin:prettier/recommended" // Enables eslint-plugin-prettier and displays prettier errors as ESLint errors. Make sure this is always the last configuration in the extends array.
],
"parserOptions": {
"ecmaVersion": 10, // Allows for the parsing of modern ECMAScript features
"sourceType": "module", // Allows for the use of imports
"jsx": true
},
"rules": {
"prettier/prettier": [
"error",
{
"singleQuote": true,
"endOfLine": "auto"
}
]
}
}
tsconfig.json
{
"compilerOptions": {
"module": "esnext",
"allowSyntheticDefaultImports": true,
"allowJs": true,
"jsx": "preserve"
},
"exclude": ["node_modules"]
}
package.json
{
"name": "reacttypescripttest",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "cross-env NODE_ENV=development webpack --config ./webpack.config.js --progress --colors --watch --display-error-details"
},
"author": "",
"license": "ISC",
"dependencies": {
"#babel/core": "^7.5.5",
"#babel/plugin-proposal-class-properties": "^7.5.5",
"#babel/plugin-proposal-object-rest-spread": "^7.5.5",
"#babel/polyfill": "^7.4.4",
"#babel/preset-env": "^7.5.5",
"#babel/preset-react": "^7.0.0",
"#babel/preset-typescript": "^7.3.3",
"#types/react": "^16.8.24",
"#types/react-dom": "^16.8.5",
"#typescript-eslint/eslint-plugin": "^1.13.0",
"#typescript-eslint/parser": "^1.13.0",
"babel-loader": "^8.0.6",
"case-sensitive-paths-webpack-plugin": "^2.2.0",
"cross-env": "^5.2.0",
"eslint": "^6.1.0",
"eslint-config-prettier": "^6.0.0",
"eslint-loader": "^2.2.1",
"eslint-plugin-prettier": "^3.1.0",
"eslint-plugin-react": "^7.14.3",
"mini-css-extract-plugin": "^0.8.0",
"prettier": "^1.18.2",
"prettier-eslint": "^9.0.0",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"typescript": "^3.5.3",
"webpack-cli": "^3.3.6"
},
"devDependencies": {
"webpack": "^4.39.1"
}
}
File causing error (index.tsx)
import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
render() {
return <div>Running!</div>;
}
}
ReactDOM.render(<App />, document.getElementById('app'));
Errors
5:3 error Missing accessibility modifier on method definition render #typescript-eslint/explicit-member-accessibility
5:9 warning Missing return type on function #typescript-eslint/explicit-function-return-type
The first error Missing accessibility modifier on method definition render is saying that you did not declare your render method as public or private or any other type (more reading on types. When working with Typescript all class methods need to have be declared accordingly, depending if you want to have them accessible outside your class instance or not. For render method it should be public. Code below should work nicely for you:
public render() {
return <div>Running!</div>;
}
When it comes the 2nd error your're having, it means that your linter expects the render method to have declared what's the output of its' execution. The correct type for render method is React.ReactNode, so your final code should look like below (assuming you're not importing ReactNode in the import statement earlier)
public render(): React.ReactNode {
return <div>Running!</div>;
}
Edit 1
Even if TS itself doesn't require all these annotations, the linter you're using does. See their default rules- as you can see, the rules you're having trouble with are not turned off. The solution there would be disabling them in your app eslint config, like below:
"rules": {
"#typescript-eslint/explicit-function-return-type": "off",
"#typescript-eslint/explicit-member-accessibility": "off"
}
If anyone is running into this AND using a tsx file already. Makre sure that you've configured vscode to associate tsx files with TypescriptReact and not just Typescript. When the tsx file is open, bottom right click on Typescript and set association.
I added SASS to my project because I like using SASS for my CSS. In my app folder I made CSS folder and a SCSS folder. I run sass --watch scss:css to map over my scss changes to the css folder. This is working great, I think. In my webpack I added a loader to handle SCSS and SASS and added the files need to my package.json. In order to start using the SASS styles do I need to include them in my index.html file or do I need to import them into each component I want to use them with the new es6 import x from 'xpath' thing?
Here are my package.json and webpack.config.js files
{
"name": "newaccount",
"version": "1.0.0",
"description": "a form submission for new accounts",
"main": "App.js",
"scripts": {
"start": "webpack-dev-server"
},
"author": "---",
"license": "ISC",
"dependencies": {
"react": "^15.4.1",
"react-dom": "^15.4.1",
"react-hot-loader": "^1.3.1",
"react-router": "^3.0.0"
},
"devDependencies": {
"babel-core": "^6.18.2",
"babel-loader": "^6.2.8",
"babel-preset-es2015": "^6.18.0",
"babel-preset-react": "^6.16.0",
"css-loader": "^0.26.1",
"html-webpack-plugin": "^2.24.1",
"node-sass": "^3.13.0",
"sass": "^0.5.0",
"sass-loader": "^4.0.2",
"style-loader": "^0.13.1",
"webpack": "^1.13.3",
"webpack-dev-server": "^1.16.2"
}
}
webpack.config.js
var HtmlWebpackPlugin = require('html-webpack-plugin');
var path = require('path');
var HTMLWebpackPluginConfig = new HtmlWebpackPlugin({
template: __dirname + '/app/index.html',
filename: 'index.html',
inject: 'body'
});
module.exports = {
entry: [
'./app/App.js'
],
output: {
path: __dirname + '/public',
filename: "index_bundle.js"
},
plugins: [HTMLWebpackPluginConfig],
devServer: {
inline:true,
contentBase: './public',
port: 3333
},
module: {
loaders: [{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader"
}, {
test: /\.scss$/,
include: path.join(__dirname, "app"),
loaders: ["style", "css", "sass"]
},
{
test: /\.scss$/,
loader: 'style!css!sass'
}]
}
};
My file structure is basically an app folder and a public folder. Inside app you have components / containers / css / scss / utils and inside public is jus the bundle.js and index.html files.
You should not be using an external Sass command with Webpack. You need to put the Sass content in Webpack's dependency graph. To do this, tell Webpack you are using the files, which is done with require(). At the top of your Javascript file for the page needing the style, add
require('./path/to/sass/scss')
In development mode, this will turn your Sass code into Javascript that will inject the built CSS rules into the page. It's strange I know, but it gives you hot reloading of styles. You should also have a separate production build Webpack config using the ExtractTextPlugin to pull the built CSS out into a separate file, and load that file in your production HTML.
Further reading: Webpack: When to Use and Why.
My webpack.config.js file was loading scss and sass twice, changed it to
{
test: /\.scss$/,
loader: 'style!css!sass'
}]
by removing
{
test: /\.scss$/,
include: path.join(__dirname, "app"),
loaders: ["style", "css", "sass"]
},
Now I can include my SASS files in my react components. Now I need to figure out how to access my images inside of my SASS files - seems to toss mass errors =(
I tried all options listed here and other sites but none seem to work.
I was able to install webpack reactjsand other components correctly for my 1st test application (MyApp).
For my next application project, I wanted to leverage all npm-modules from 1st app so that I don't have to download all modules again and keep them centrally.
However, I keep getting above error about missing "es2015". webpack under my 1st app project does not report this problem. The strange thing is even if I change preset from es2015 to say XXes2015, I still get the same message.
My webpack.config.js:
var path = require('path');
var isDev=true;
const cssModulesNames = `${isDev ? '[path][name]__[local]__' : ''}[hash:base64:5]`;
var config = {
entry: path.resolve(__dirname, 'js\\main.js'),
output: {
path: path.resolve(__dirname, '.'),
filename: '.\\bundle.js'
},
resolveLoader: {
modulesDirectories: [ '../../../../Documents/API/react/examples/MyApp/node_modules' ]
},
module: {
loaders: [{
test: /\.jsx?$/,
loader: 'babel',
query:
{
presets: [ 'es2015', 'react',"stage-0"]
}
}]
}
};
module.exports = config;
My package.jason:
{
"name": "App1",
"version": "1.13.1",
"description": "",
"main": ".",
"dependencies": {
"babel-core": "latest",
"babel-loader": "latest",
"babel-preset-es2015": "latest",
"babel-preset-react": "latest",
"babel-preset-stage-0": "latest"
},
"devDependencies": {},
"scripts": {
"test": "jest --verbose"
},
"jest": {
"scriptPreprocessor": "<rootDir>/node_modules/babel-jest",
"unmockedModulePathPatterns": [
"<rootDir>/node_modules/react",
"<rootDir>/node_modules/react-dom",
"<rootDir>/node_modules/react-addons-test-utils",
"<rootDir>/node_modules/fbjs"
]
},
"author": "XX",
"license": "ISC"
}
My .bablrc :
{ "presets": ["es2015", "stage-0", "react"] }
If I change entry es2015 to say esXX2015 in webpack.config.js or .babelrc, it gives same error. I expected it to look for different preset.
Hope someone can throw more light on this and help me out !
Thanks.
make sure your filename is: .babelrc instead of .bablrc
you can try to add babel-loaderon your webpack.config
change loader: 'babel' to loader: 'babel-loader'
Looks like you expect the resolveLoader.modulesDirectories config parameter to tell babel where to find presets. This parameter is used by webpack to find loaders (such as babel-loader), but not by babel.
There is a typo in your question. It should be .babelrc not .bablrc
The content of `.babelrc' should like below. The order is important.
stage-0 → ES2015 → JSX → ES5
{
"presets": [
"stage-0",
"es2015",
"react"
]
}
I suggest you to have presets either in .babelrc file or in webpack.config file to maintain single source of truth. So remove the query entry in your webpack.config and add a exclude entry to ignore js/jsx files from inside the node-modeuls folder (update it as below...)
loaders: [{
test: /\.jsx?$/,
exclude: /node-modules/,
loader: 'babel'
}]
I finally managed to solve the issue by creating node-modules symbolic link to previous projects node_module directory. While this achieved what I wanted, I am bit not happy that various settings in webpack.config.js that I tried could not achieve this. Hope someone comes with right settings, so that webpack behavior is much more clearer ( to me at least). Hope this helps someone else trying to solve similar problem...