I am working on the create-react-app project with typescript. I am trying to use _ (lodash) globally. I followed manuals step by step trying to figure out how to do it, but without any success.
I followed this tutorial https://www.npmjs.com/package/customize-cra. My package.json contains between dependecies:
"babel-plugin-transform-decorators-legacy": "^1.3.5",
"react-app-rewired": "^2.1.8",
"save-dev": "^0.0.1-security"
In devDependencies:
"customize-cra": "^1.0.0"
Based on tutorials I changed also scripts:
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",...
My config-overrides.js is located in root folder:
const { addDecoratorsLegacy, override, disableEsLint } = require('customize-cra')
const webpack = require('webpack')
function myOverrides(config) {
if (!config.plugins) {
config.plugins = []
}
config.plugins.push(
new webpack.ProvidePlugin({
_: 'lodash',
}),
)
return config
}
module.exports = override(
addDecoratorsLegacy(),
disableEsLint(),
myOverrides
)
I try to use join(['Hello', 'webpack'], ' ') but failed with error.
TypeScript error in C:/Users/.../webapp/src/index.tsx(27,1): Cannot find name 'join'. TS2304
Does anybody have any idea what should go wrong?
Thank you.
Related
I am trying to load the Css, Images and fonts using the webpack. Here is my webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.js',
mode: 'development',
output: {
filename: "main.js",
path: path.resolve(__dirname,"dist")
},
module:{
rules:[
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},
{
test: /\.(png|svg|jpg|jpeg|gif)$/i,
type: "asset/resource",
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/i,
type: "asset/resource",
},
],
},
};
This is my package.json
{
"name": "restaurant-page",
"version": "1.0.0",
"description": "",
"private": true,
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"watch": "webpack --watch",
"build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"css-loader": "^6.2.0",
"style-loader": "^3.2.1",
"webpack": "^5.51.1",
"webpack-cli": "^4.8.0"
},
"dependencies": {}
}
This is my index.js. When I uncomment the ./styles.css import I get the
main.js:290 Uncaught Error: Automatic publicPath is not supported in this browser in chrome console and my js imports doesn't work but it dosen't throw me error while building project when I run npm run build commmand in terminal. I tried using css import in each js module-- in home.js etc--file but that also doesn't work.
// import './style.css';
import { homeContent, removeIntroContent } from './Modules/home.js';
import { aboutContent, removeAboutContent } from './Modules/about.js';
import { reviewsContent, removeReviewContent } from './Modules/reviews.js';
const home = document.getElementById("home-btn");
const review = document.getElementById("review-btn");
const about = document.getElementById("about-btn");
homeContent();
home.addEventListener("click",()=>{
removeReviewContent();
removeAboutContent();
const id = document.getElementById("intro-content");
if(id != null) return;
homeContent();
});
review.addEventListener("click",()=>{
removeAboutContent();
removeIntroContent();
const id = document.getElementById("reviews");
if(id != null) return;
reviewsContent();
});
about.addEventListener("click",()=>{
removeReviewContent();
removeIntroContent();
const id = document.getElementById("about");
if(id != null) return;
aboutContent()
});
I have pushed the code to github if anyone want to look at file structure
Here is the link
ps: If I use the link tag to add css to html it works exactly as I want it to but that defeats the purpose of using webpack
I am having trouble with Webpack as well and I came across your question. I don't have a sure solution to your problem, but I hope to steer you in the right direction.
At first glance, I am wondering if editing your package.json file to use your webpack-config when you run 'npm run build' instead of the default webpack config. This could help activate the loaders you are trying to use, or atleast populate error messages that would allow you to investigate further. Editing your package.json would look like:
"scripts": {
"test": "echo \\\"Error: no test specified\\\" && exit 1",
"watch": "webpack --watch",
"build": "webpack --config ./webpack-config.js"
}
Your dependencies make sense and your file path for style.css seems correct, so I am wondering if Webpack does not know how to load your styles, fonts, images without your config file.
Can read more about Webpack configuration here.
https://webpack.js.org/configuration/
Hope I was able to help, good luck! If you have any further questions I'd be happy to help, as I'm learning Webpack too.
I have made a npm module in a private git repo and I'm trying to access it in another application.
I'm using reactjs, webpack and npm
So I have the module:
dist
src
| form-mapper
| formMapper.js
| myfile.js
| index.js
package.json
webpack.config.js
Webpack.config.js is like this:
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js'
}
}
Package.json is like this:
{
"name": "my-awesome-module",
"version": "1.0.0",
"license": "ISC",
"main": "./dist/bundle.js",
"scripts": {
"prepare": "npm run build",
"build": "webpack --mode production",
"start": "webpack-dev-server --open --mode development"
},
"devDependencies": {
"webpack": "^4.43.0",
"webpack-cli": "^4.3.0",
"webpack-dev-server": "^3.11.0"
}
}
formMapper.js as 2 functions that I'm trying to export:
export function mapForm() {
// some code
}
export function mapUiFormToBackEnd() {
// some code
}
And index.js:
import * as FormMapper from './form-mapper/formMapper'
export { mapForm, mapUiFormToBackEnd } from './form-mapper/formMapper'
export default FormMapper
I've tried a lot of things in index.js so I let everything here just to show you guys what I've already tried.
In my app that needs to use this module I import the module using npm (git+ssh://...) which is working since I can see my module inside node_modules.
When I try to import using:
import FormMapper from 'my-awesome-module'
componentDidMount() {
FormMapper.mapForm()
}
I have this error:
my-awesome-module__WEBPACK_IMPORTED_MODULE_2___default.a.mapForm is not a function
That's my first time trying to create my own npm module and I clearly don't understand everything. I tried several guide but it seems I'm not abla to make it right.
Thanks for the help.
Edit:
When I log my import in my application
import FormMapper from 'my-awesome-module'
componentDidMount() {
console.log(FormMapper)
FormMapper.mapForm()
}
I see an empty object {} getting logged
update your formMapper.js in a more proper way
const mapForm = () => {
// Code here
}
const mapUiFormToBackEnd = () => {
// Code here
}
module.exports = {mapForm, mapUiFormToBackEnd }
on your index.js
// If you just want the mapForm and mapUiFormToBackEnd
const {mapForm, mapUiFormToBackEnd} = require('./form-mapper/formMapper');
// Or if you just want to get all it's fucntion just import it like this
const FormMapper = require('./form-mapper/formMapper') // No need for *
// export the whole FormMapper
module.exports = FormMapper;
// If you want to export a specific functions inside FormMapper
module.exports = {mapForm, mapUiFormToBackEnd }
My Jest config details are
jest.config.js
module.exports = {
transform: {
'^.+\\.svelte$': 'svelte-jester',
'^.+\\.js$': 'babel-jest',
},
moduleFileExtensions: ['js', 'svelte'],
}
babel.config.js
module.exports = {
presets: [
[
'#babel/preset-env',
{
targets: {
node: 'current',
},
},
],
],
}
package.json
.
.
"#babel/core": "^7.10.2",
"#babel/preset-env": "^7.10.2",
"babel-jest": "^26.0.1",
"jest": "^26.0.1",
"svelte-jester": "^1.0.6",
"#testing-library/svelte": "^3.0.0"
},
"scripts": {
"build": "cross-env NODE_ENV=production webpack",
"dev": "webpack-dev-server --content-base public",
"test": "jest src",
"test:watch": "npm run test -- --watch"
},
.
.
I created src/test folder where my test.spec.js is as follows
import {fireEvent, render} from '#testing-library/svelte';
import App from '../App.svelte';
describe('test', () => {
test('Just a mock test', async () => {
const myMock = jest.fn();
console.log(myMock());
myMock.mockReturnValueOnce(10).mockReturnValueOnce('x').mockReturnValue(true);
console.log(myMock(), myMock(), myMock(), myMock());
});
});
Plz note that this I used a jest mock function just for testing purpose but whenever I import a svelte file as in this case App.svelte I get an error as below
FAIL src/test/test.spec.js
● Test suite failed to run
ParseError: Identifier is expected
I found a possible solution to this parsing error. Apparently, the IDE was unable to resolve certain style classes in the test.svelte file defined inside style tag, which is why it was showing up ParseError.
I would suggest anyone coming across this error to check your svelte file thoroughly for errors since svelte-testing-lib parses through the entire file before executing any test function.
I am using craco with create react app and I would like to add a plugin only in DEV mode or by ENV Var
my craco.config looks is:
const path = require('path');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
module.exports = () => {
return {
webpack: {
alias: {
environment: path.join(
__dirname,
'src',
'environments',
process.env.CLIENT_ENV || 'production'
)
}
// plugins: [new BundleAnalyzerPlugin()]
},
jest: {
configure: {
testPathIgnorePatterns: ['<rootDir>/src/environments/'],
moduleNameMapper: {
environment: '<rootDir>/src/environments/test'
}
}
}
};
};
so I would like this BundleAnalyzerPlugin. only if the ENV param x =true or if NODE_ENV=test
while I trying to push to plugin array I got that plugin I undefined
module.exports.webpack.plugins.push(plugin)
You can set an environment variable right before any script command. For example, in your package.json, add a new line in the scripts paragraph that sets some variables:
"scripts": {
"start": "craco start",
"build": "craco build",
"test": "craco test",
"analyzer": "env NODE_ENV=production ANALYZER=test yarn start"
}
In craco.config.js you can simply use:
plugins: process.env.ANALYZER === 'test' ? [new BundleAnalyzerPlugin()] : []
Now, running npm run analyzer will both, set node env to production, set a variable ANALYZER to test (used later on) and load the craco config, that will start both the webpack server and the analyser.
you can use conditions from craco like when, whenDev, whenProd, whenTest
webpack: {
plugins: [...whenDev(() => [new BundleAnalyzerPlugin()], [])]
},
I have a little not project where I have installed systemJS.
Here is package.json:
{
"name": "mytest",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^15.5.4",
"react-dom": "^15.5.4",
"systemjs": "^0.20.13"
},
"devDependencies": {
"react-scripts": "1.0.7"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
}
In app.js I have done this:
import React, { Component } from 'react';
import './App.css';
var SystemJS = require('systemjs');
When I run the project it's giving me this error:
Error: Cannot find module "."
I'm following the instructions here:
https://github.com/systemjs/systemjs
This part:
var SystemJS = require('systemjs');
// loads './app.js' from the current directory
SystemJS.import('./app.js').then(function (m) {
console.log(m);
});
What I'm I doing wrong?
Your problems could be due to the fact that you have missed to configure systemjs - that is instruct it where to look for modules to load.
For example the configuration can look something like this:
System.config({
baseURL: './lib',
// Set paths your modules
paths: {
'angular': 'mode_modules/angular/angular.js',
'angular-route': 'node_modules/angular-route/angular-route.js'
}
});
If you would like to skip the tedious configuration part - you might want to look at JSMP - it takes care of configuration part automatically.