Getting error : Support for the experimental syntax 'jsx' isn't currently enabled . When trying to add animation in react-native-web project - react-native-web

In my project, I'm using the reanimate library to add animations, but I'm receiving an error
https://stackoverflow.com/questions/63005011/support-for-the-experimental-syntax-jsx-isnt-currently-enabled
I follow all the steps mention in the link but none of them work for me
My package.json file
{
"name": "animation",
"version": "0.1.0",
"private": true,
"dependencies": {
"#react-spring/native": "^9.6.1",
"#react-spring/web": "^9.6.1",
"#testing-library/jest-dom": "^5.16.5",
"#testing-library/react": "^13.4.0",
"#testing-library/user-event": "^13.5.0",
"babel-polyfill": "^6.26.0",
"lodash": "^4.17.21",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-native-reanimated": "^2.14.4",
"react-native-web": "^0.18.10",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"#babel/plugin-syntax-jsx": "^7.18.6",
"#babel/preset-env": "^7.20.2",
"#babel/preset-react": "^7.18.6",
"babel-loader": "^9.1.2",
"url-loader": "^4.1.1",
"webpack": "^5.75.0",
"webpack-cli": "^5.0.1",
"webpack-dev-server": "^4.11.1"
}
}
webpack.config.js
// web/webpack.config.js
const path = require("path");
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const appDirectory = path.resolve(__dirname, "../");
// This is needed for webpack to compile JavaScript.
// Many OSS React Native packages are not compiled to ES5 before being
// published. If you depend on uncompiled packages they may cause webpack build
// errors. To fix this webpack can be configured to compile to the necessary
// `node_module`.
const babelLoaderConfiguration = {
test: /\.js$/,
// Add every directory that needs to be compiled by Babel during the build.
include: [
path.resolve(appDirectory, "index.web.js"),
path.resolve(appDirectory, "src"),
path.resolve(appDirectory, "node_modules/react-native-uncompiled"),
],
use: {
loader: "babel-loader",
options: {
cacheDirectory: true,
// The 'metro-react-native-babel-preset' preset is recommended to match React Native's packager
presets: [
"#babel/preset-react",
"module:metro-react-native-babel-preset",
],
// Re-write paths to import only the modules needed by the app
plugins: [
"#babel/plugin-syntax-jsx",
"react-native-web",
"react-native-reanimated/plugin",
],
},
},
};
// This is needed for webpack to import static images in JavaScript files.
const imageLoaderConfiguration = {
test: /\.(gif|jpe?g|png|svg)$/,
use: {
loader: "url-loader",
options: {
name: "[name].[ext]",
esModule: false,
},
},
};
module.exports = {
entry: [
// load any web API polyfills
path.resolve(appDirectory, "polyfills-web.js"),
// your web-specific entry file
path.resolve(appDirectory, "index.web.js"),
],
// configures where the build ends up
output: {
filename: "bundle.web.js",
path: path.resolve(appDirectory, "dist"),
},
// ...the rest of your config
plugins: [
new HtmlWebpackPlugin({
filename: "index.html",
template: "./index.html",
}),
new webpack.EnvironmentPlugin({ JEST_WORKER_ID: null }),
new webpack.DefinePlugin({ process: { env: {} } }),
],
module: {
rules: [babelLoaderConfiguration, imageLoaderConfiguration],
},
resolve: {
// This will only alias the exact import "react-native"
alias: {
"react-native$": "react-native-web",
},
// If you're working on a multi-platform React Native app, web-specific
// module implementations should be written in files using the extension
// `.web.js`.
extensions: [".web.js", ".js"],
},
};

Related

Webpack module federation error: Cannot destructure property `ModuleFederationPlugin` of 'undefined' or 'null'

I am currently modifying the configuration file a Vue app (acting here as a host app) to implement the plugin of webpack : ModuleFederationPlugin.
The goal for me is to set up a micro-frontend architecture by getting a component from a remote app called "foo".
Here is the code to reproduce the issue :
config file host app :
const path = require("path");
const helpers = require("./config/helpers");
const { ModuleFederationPlugin } = require("webpack").container;
const config = {
configureWebpack: {
entry: {
polyfill: "#babel/polyfill",
},
stats: {
cached: false,
cachedAssets: false,
chunks: false,
chunkModules: false,
chunkOrigins: false,
modules: false,
},
devServer: {
historyApiFallback: true,
port: 8765,
},
plugins: [
new ModuleFederationPlugin({
name: "vue",
remotes: {
foo: "foo#http://localhost:5173/remoteEntry.js",
},
}),
],
},
pluginOptions: {
"style-resources-loader": {
preProcessor: "scss",
patterns: [],
},
},
};
module.exports = config;
package.json host app :
{
"name": "Test",
"version": "1.0.0",
"description": "Test",
"author": "Test",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build"
},
"dependencies": {
"vue": "^2.6.10"
},
"devDependencies": {
"#babel/core": "7.7.2",
"#babel/plugin-transform-runtime": "7.6.2",
"#babel/preset-env": "7.7.1",
"#babel/register": "7.7.0",
"#vue/cli-plugin-babel": "^4.0.5",
"#vue/cli-plugin-eslint": "^4.0.5",
"#vue/cli-service": "^4.0.5",
"#vue/eslint-config-airbnb": "^5.0.0",
"babel-plugin-istanbul": "5.2.0",
"cache-loader": "^4.1.0",
"eventsource-polyfill": "0.9.6",
"image-webpack-loader": "^6.0.0",
"karma-webpack": "4.0.2",
"selenium-server": "3.141.59",
"url-loader": "^2.2.0",
"vue-cli-plugin-style-resources-loader": "^0.1.4",
"vue-loader": "15.7.2",
"vue-style-loader": "4.1.2",
"vue-template-compiler": "2.6.10",
"webpack": "^4.41.2",
"webpack-merge": "4.2.2"
},
"engines": {
"node": ">= 8.0.0",
"npm": ">= 5.0.0"
}
}
yarn version host app : 1.22.19
node version host app : v12.0.0
config file remote app :
import svgr from "vite-plugin-svgr"
import { defineConfig } from "vite"
import react from "#vitejs/plugin-react"
import * as path from "path"
import federation from "#originjs/vite-plugin-federation"
export default defineConfig({
plugins: [
svgr(),
react(),
federation({
name: "foo",
filename: "remoteEntry.js",
exposes: {
"./App": "./src/App.tsx",
},
}),
],
build: {
target: "esnext",
assetsDir: "assets",
},
server: {
host: "0.0.0.0",
port: 5173,
},
})
package.json file of the remote app :
{
"name": "test",
"version": "1.0.0",
"description": "test",
"author": "test",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"build:prod": "tsc && vite build",
"build:demo": "tsc && vite build --mode demo",
"preview": "vite preview",
"lint:check": "eslint \"./src/**/*.{ts,tsx}\"",
"lint:fix": "eslint --fix \"./src/**/*.{ts,tsx}\"",
"prettier:check": "prettier --check .",
"prettier:fix": "prettier --write ."
},
"dependencies": {
"#emotion/react": "^11.10.0",
"#emotion/styled": "^11.10.0",
"#mui/icons-material": "^5.10.9",
"#mui/material": "^5.10.0",
"#mui/x-date-pickers": "^5.0.0",
"#originjs/vite-plugin-federation": "^1.1.11",
"axios": "^0.27.2",
"classnames": "^2.3.1",
"dayjs": "^1.11.5",
"i18next": "^21.8.14",
"moment": "^2.29.4",
"npm": "^8.19.2",
"react": "^18.2.0",
"react-charts": "=3.0.0-beta.30",
"react-confetti": "^6.1.0",
"react-dom": "^18.2.0",
"react-hook-form": "^7.33.1",
"react-i18next": "^11.18.1",
"react-number-format": "^5.0.1",
"react-router-dom": "^6.3.0"
},
"devDependencies": {
"#types/node": "^18.7.18",
"#types/react": "^18.0.15",
"#types/react-dom": "^18.0.6",
"#typescript-eslint/eslint-plugin": "^5.30.7",
"#typescript-eslint/parser": "^5.30.7",
"#vitejs/plugin-react": "^2.0.0",
"eslint": "^8.20.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-react": "^7.30.1",
"prettier": "^2.7.1",
"sass": "^1.55.0",
"typescript": "^4.6.4",
"vite": "^3.0.0",
"vite-plugin-svgr": "^2.2.1"
}
}
yarn version of the remote app : 1.22.19
node version of the remote app : v12.0.0
Here is what I get when running the host app with "yarn serve" :
error logs when launching the app
My goal is then to be able to use the component App from the remote app in the host app by importing it like that :
Vue.component("App", () => import("foo/App"));

Webpack 5 + Angular 11 Error: ./node_modules/msnodesqlv8/build/Release/sqlserverv8.node 1:2

I'm using Webpack 5 and Angular 11
when I execute the command
ng build --prod && ng run test-app:server:production
In the console it gives me an error message:
Error: ./node_modules/msnodesqlv8/build/Release/sqlserverv8.node 1:2
Module parse failed: Unexpected character '�' (1: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
and directory is not being built: dist/test-app/server/main.js it only creates itself: dist/test-app/browser/
I don't know where I have badly configured files.
Please help. I don't know what I'm doing wrong.
package.json:
{
"name": "test-app",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e",
"dev:ssr": "ng run test-app:serve-ssr",
"serve:ssr": "node dist/test-app/server/main.js",
"build:ssr": "ng build --prod && ng run test-app:server:production",
"prerender": "ng run test-app:prerender",
"start-webpack:server": "webpack --config webpack.server.config.js "
},
"private": true,
"resolution": {
"webpack": "^5.0.0"
},
"dependencies": {
"#angular/animations": "~11.0.5",
"#angular/common": "~11.0.5",
"#angular/compiler": "~11.0.5",
"#angular/core": "~11.0.5",
"#angular/forms": "~11.0.5",
"#angular/platform-browser": "~11.0.5",
"#angular/platform-browser-dynamic": "~11.0.5",
"#angular/platform-server": "^11.0.7",
"#angular/router": "~11.0.5",
"#nguniversal/express-engine": "^11.0.1",
"express": "^4.17.1",
"msnodesqlv8": "^2.0.8",
"mssql": "^6.3.1",
"rxjs": "~6.6.0",
"tslib": "^2.0.0",
"zone.js": "~0.10.2"
},
"devDependencies": {
"#angular-devkit/build-angular": "~0.1100.5",
"#angular/cli": "~11.0.5",
"#angular/compiler-cli": "~11.0.5",
"#nguniversal/builders": "^11.0.1",
"#types/express": "^4.17.9",
"#types/jasmine": "~3.6.0",
"#types/node": "^12.11.1",
"codelyzer": "^6.0.0",
"jasmine-core": "~3.6.0",
"jasmine-spec-reporter": "~5.0.0",
"karma": "~5.1.0",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage": "~2.0.3",
"karma-jasmine": "~4.0.0",
"karma-jasmine-html-reporter": "^1.5.0",
"protractor": "~7.0.0",
"ts-loader": "^8.0.14",
"ts-node": "^8.3.0",
"tslint": "~6.1.0",
"typescript": "~4.0.2",
"webpack-cli": "^4.3.1"
},
"description": "This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 11.0.5.",
"main": "karma.conf.js",
"keywords": [],
"author": "",
"license": "ISC"
}
angular.json:
{
"$schema": "./node_modules/#angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"test-app": {
"projectType": "application",
"schematics": {
"#schematics/angular:component": {
"style": "scss"
},
"#schematics/angular:application": {
"strict": true
}
},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "#angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/test-app/browser",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.app.json",
"aot": true,
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.scss"
],
"scripts": []
},
"configurations": {
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"namedChunks": false,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true,
"budgets": [
{
"type": "initial",
"maximumWarning": "2mb",
"maximumError": "5mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "6kb",
"maximumError": "10kb"
}
]
}
}
},
"serve": {
"builder": "#angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "test-app:build"
},
"configurations": {
"production": {
"browserTarget": "test-app:build:production"
}
}
},
"extract-i18n": {
"builder": "#angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "test-app:build"
}
},
"test": {
"builder": "#angular-devkit/build-angular:karma",
"options": {
"main": "src/test.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.spec.json",
"karmaConfig": "karma.conf.js",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.scss"
],
"scripts": []
}
},
"lint": {
"builder": "#angular-devkit/build-angular:tslint",
"options": {
"tsConfig": [
"tsconfig.app.json",
"tsconfig.spec.json",
"e2e/tsconfig.json",
"tsconfig.server.json"
],
"exclude": [
"**/node_modules/**"
]
}
},
"e2e": {
"builder": "#angular-devkit/build-angular:protractor",
"options": {
"protractorConfig": "e2e/protractor.conf.js",
"devServerTarget": "test-app:serve"
},
"configurations": {
"production": {
"devServerTarget": "test-app:serve:production"
}
}
},
"server": {
"builder": "#angular-devkit/build-angular:server",
"options": {
"outputPath": "dist/test-app/server",
"main": "server.ts",
"tsConfig": "tsconfig.server.json"
},
"configurations": {
"production": {
"outputHashing": "media",
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
"sourceMap": false,
"optimization": true
}
}
},
"serve-ssr": {
"builder": "#nguniversal/builders:ssr-dev-server",
"options": {
"browserTarget": "test-app:build",
"serverTarget": "test-app:server"
},
"configurations": {
"production": {
"browserTarget": "test-app:build:production",
"serverTarget": "test-app:server:production"
}
}
},
"prerender": {
"builder": "#nguniversal/builders:prerender",
"options": {
"browserTarget": "test-app:build:production",
"serverTarget": "test-app:server:production",
"routes": [
"/"
]
},
"configurations": {
"production": {}
}
}
}
}
},
"defaultProject": "test-app",
"cli": {
"analytics": "e9a52f4c-af8d-4030-8d24-ba3f4b17ec39"
}
}
server.ts:
import 'zone.js/dist/zone-node';
import { ngExpressEngine } from '#nguniversal/express-engine';
import * as express from 'express';
import { join } from 'path';
import { AppServerModule } from './src/main.server';
import { APP_BASE_HREF } from '#angular/common';
import { existsSync } from 'fs';
import { TestRoute } from './server/router/test';
const testRoute: TestRoute = new TestRoute();
export function app(): express.Express {
const server = express();
const distFolder = join(process.cwd(), 'dist/test-app/browser');
const indexHtml = existsSync(join(distFolder, 'index.original.html')) ? 'index.original.html' : 'index';
server.engine('html', ngExpressEngine({
bootstrap: AppServerModule,
}));
server.set('view engine', 'html');
server.set('views', distFolder);
server.get('*.*', express.static(distFolder, {
maxAge: '1y'
}));
server.get('*', (req, res) => {
res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] });
});
return server;
}
function run(): void {
const port = process.env.PORT || 4000;
const server = app();
server.listen(port, () => {
console.log(`Node Express server listening on http://localhost:${port}`);
});
}
// Webpack will replace 'require' with '__webpack_require__'
// '__non_webpack_require__' is a proxy to Node 'require'
// The below code is to ensure that the server is run only when not requiring the bundle.
declare const __non_webpack_require__: NodeRequire;
const mainModule = __non_webpack_require__.main;
const moduleFilename = mainModule && mainModule.filename || '';
if (moduleFilename === __filename || moduleFilename.includes('iisnode')) {
run();
}
export * from './src/main.server';
commented out on this line of code:
const testRoute: TestRoute = new TestRoute();
and execute the command
ng build --prod && ng run test-app: server: production
does not display errors.
The TestRoute class contains a reference to the library and connecting to the database:
import { Request, Response, NextFunction, response } from 'express';
export class TestRoute {
contractorRoute(app: any): void {
app.route('/api/get-test').get((req: Request, res: Response, next: NextFunction) => {
var sql = require("mssql/msnodesqlv8");
let config = {
server: 'SQLDXXX\\XXX',
database: 'XXX',
driver: "msnodesqlv8",
options: {
trustedConnection: true
}
};
let connect = new sql.ConnectionPool(config);
connect.connect().then(() => {
connect.request().query('select * from [test].[dbo].[test]', (err: TypeError, recordset: any) => {
if (err) {
console.error(" Error: " + err );
return;
} else {
res.send(recordset);
}
connect.close();
})
}).catch((err: any) => {
console.error(" Error: " + err );
});
})
}
}
tsconfig.app.json
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": [
"node"
]
},
"files": [
"src/main.ts",
"src/polyfills.ts"
],
"include": [
"src/**/*.d.ts"
]
}
tsconfig.json
{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"sourceMap": true,
"declaration": false,
"downlevelIteration": true,
"experimentalDecorators": true,
"moduleResolution": "node",
"importHelpers": true,
"target": "es2015",
"module": "es2020",
"lib": [
"es2018",
"dom"
]
},
"angularCompilerOptions": {
"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"strictTemplates": true
}
}
tsconfig.server.json
{
"extends": "./tsconfig.app.json",
"compilerOptions": {
"outDir": "./out-tsc/app",
"target": "es2020",
"module": "commonjs",
"types": [
"node"
]
},
"files": [
"src/main.server.ts",
"server.ts"
],
"angularCompilerOptions": {
"entryModule": "./src/app/app.server.module#AppServerModule"
}
}
webpack.server.config.js
const path = require("path");
const webpack = require("webpack");
module.exports = {
entry: { server: "./server.ts" },
resolve: { extensions: [".js", ".ts"] },
target: "node",
mode: "none",
// this makes sure we include node_modules and other 3rd party libraries
externals: [/node_modules/],
output: {
path: path.join(__dirname, "dist"),
filename: "[name].js"
},
module: {
rules: [
{ test: /\.ts$/, loader: "ts-loader" },
{ test: /\.node$/, use: "node-loader" },
]
},
plugins: [
// Temporary Fix for issue: https://github.com/angular/angular/issues/11580
// for 'WARNING Critical dependency: the request of a dependency is an expression'
new webpack.ContextReplacementPlugin(
/(.+)?angular(\\|\/)core(.+)?/,
path.join(__dirname, "src"), // location of your src
{} // a map of your routes
),
new webpack.ContextReplacementPlugin(
/(.+)?express(\\|\/)(.+)?/,
path.join(__dirname, "src"),
{}
)
]
};
the documentation https://www.npmjs.com/package/msnodesqlv8 says about adding a line I added it:
{ test: /\.node$/, use: 'node-loader' }
but the error is still there:
Error: ./node_modules/msnodesqlv8/build/Release/sqlserverv8.node 1:2
Module parse failed: Unexpected character '�' (1: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
I don't know what else I should improve.
Thank you for your help
the application example is based on:
https://www.ganatan.com/tutorials/server-side-rendering-with-angular-universal

How to use Typescript in Laravel Project with Vue as frontend?

I want to use typescript in Vue in Laravel project.
I already checked all tutorials for that but none of them works for me give below
teej.
Titas Gailius.
sebastiandedeyne.
when ever i run 'npm run dev' i get this error
ERROR in ./resources/js/app.ts
Module build failed: Error: You may be using an old version of webpack; please check you're using at least version 4
at successfulTypeScriptInstance (E:\PersonalProjects\web_dev\blog\node_modules\ts-loader\dist\instances.js:144:15)
at Object.getTypeScriptInstance (E:\PersonalProjects\web_dev\blog\node_modules\ts-loader\dist\instances.js:34:12)
at Object.loader (E:\PersonalProjects\web_dev\blog\node_modules\ts-loader\dist\index.js:17:41)
# multi ./resources/js/app.ts ./resources/sass/app.scss
Im facing this problem from quite some days but i was finally be able to find the solution for that so im Sharing my exp to folks who want to use typescript instead of javascript in vue in laravel. so here is the instruction
here the intruction
Laravel 5.7 uses Laravel-mix which down the line uses webpack 3 . Which is not what we want for typescript to work in laravel project.
Initialize your project
Let's create a new Project. You can also do this on Existing project just make sure to convert js code to ts.
First make sure you have composer and laravel installed
sh
laravel new Laravel-Vue-Typecript
Open the project in your any favraite code editor.
Open the package.json and add these packages to devdependencies
{
"devDependencies": {
"auto-loader": "^0.2.0",
"autoprefixer": "^9.4.1",
"axios": "^0.18",
"bootstrap": "^4.0.0",
"lodash": "^4.17.5",
"popper.js": "^1.12",
"jquery": "^3.2",
"cross-env": "^5.1",
"css-loader": "^1.0.1",
"mini-css-extract-plugin": "^0.4.5",
"node-sass": "^4.10.0",
"optimize-css-assets-webpack-plugin": "^5.0.1",
"postcss-loader": "^3.0.0",
"sass-loader": "^7.1.0",
"ts-loader": "^5.3.1",
"typescript": "^3.2.1",
"uglifyjs-webpack-plugin": "^2.0.1",
"vue": "^2.5.17",
"vue-class-component": "^6.3.2",
"vue-property-decorator": "^7.2.0",
"webpack": "^4.26.1",
"webpack-cli": "^3.1.2",
"vue-loader": "^15.4.2",
"vue-template-compiler": "^2.5.17"
}
}
Now install these npm packages with
npm install
Add Typescript Support
Then rename these files
Laravel-Vue-Typecript/
├─ resources/js/app.js => resources/js/app.ts
└─ resources/js/bootstrap.js => resources/js/bootstrap.ts
Now Change the Code in app.ts, bootstrap.ts and
resources/js/components/ExampleComponent.vue
// app.ts
import "./bootstrap"
import Vue from "vue"
import ExampleComponent from "./components/ExampleComponent.vue"
Vue.component('example', ExampleComponent)
new Vue({
el: '#app'
})
// bootstrap.ts
import axios from 'axios';
import * as _ from 'lodash';
import jQuery from 'jquery';
import * as Popper from 'popper.js';
import 'bootstrap';
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
let token : HTMLMetaElement | null = document.head!.querySelector('meta[name="csrf-token"]');
if (token) {
axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}
// resources/js/components/ExampleComponent.vue
<template>
<h1>This is an example component</h1>
</template>
<script lang="ts">
import Vue from 'vue'
import Component from "vue-class-component"
#Component
export default class ExampleComponent extends Vue {
mounted() : void {
console.log("hello");
}
}
</script>
```
Create typings.d.ts file inside resources/js and add these lines.
declare module '*.vue' {
import Vue from 'vue'
export default Vue
}
declare module 'jquery';
declare module 'lodash';
Now Create tsconfig.json, webpack.config.js and postcss.config.js in the root of your project and these lines of code to them respectivly
tsconfig.json
{
"compilerOptions": {
"target": "es5",
"strict": true,
"module": "es2015",
"moduleResolution": "node",
"experimentalDecorators": true,
"skipLibCheck": true
},
"include": [
"resources/js/**/*"
],
"exclude": [
"node_modules",
"vendor"
]
}
webpack.config.json
const path = require('path')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin')
const VueLoaderPlugin = require('vue-loader/lib/plugin')
const autoprefixer = require('autoprefixer');
const webpack = require('webpack');
let env = process.env.NODE_ENV
let isDev = env === 'development'
const WEBPACK_CONFIG = {
mode: env,
entry: {
app: ['./resources/js/app.ts', './resources/sass/app.scss'],
},
output: {
publicPath: './public',
path: path.resolve(__dirname, 'public'),
filename: 'js/[name].js',
chunkFilename: 'js/chunks/app.js'
},
module: {
rules: [{
test: /\.tsx?$/,
loader: 'ts-loader',
options: { appendTsSuffixTo: [/\.vue$/] },
exclude: /node_modules/,
},
{
test: /\.vue$/,
loader: 'vue-loader'
},
{
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'postcss-loader',
'sass-loader'
],
exclude: /node_modules/,
}
],
},
plugins: [
new MiniCssExtractPlugin({
filename: 'css/[name].css'
}),
new VueLoaderPlugin(),
new webpack.LoaderOptionsPlugin({
options: {
postcss: [
autoprefixer()
]
}
})
],
resolve: {
extensions: ['.js', '.jsx', '.vue', '.ts', '.tsx'],
alias: {
vue$: 'vue/dist/vue.esm.js',
},
},
optimization: {
splitChunks: {
chunks: 'async',
minSize: 30000,
maxSize: 0,
minChunks: 1,
maxAsyncRequests: 5,
maxInitialRequests: 3,
automaticNameDelimiter: '~',
name: true,
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
priority: -10
},
default: {
minChunks: 2,
priority: -20,
reuseExistingChunk: true
}
}
}
}
}
if (!isDev) {
WEBPACK_CONFIG.optimization = {
minimizer: [
new UglifyJsPlugin({
cache: true,
parallel: true,
sourceMap: true
}),
new OptimizeCSSAssetsPlugin({})
]
}
WEBPACK_CONFIG.plugins.push(
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: 'production'
}
})
)
}
module.exports = WEBPACK_CONFIG
postcss.config.js
module.exports = {
plugins: {
'autoprefixer': {}
} }
Now finally change the "scripts" in package.json
"scripts": {
"dev": "npm run development",
"development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=webpack.config.js",
"watch": "npm run development -- --watch",
"watch-poll": "npm run watch -- --watch-poll",
"prod": "npm run production",
"production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=webpack.config.js"
},
Finally build the project
and run the npm scripts by
npm run dev // To build the Project
npm run watch // To build and watch for files changes and build automagically
npm run prod // for production

React-redux app is no longer auto updating

I had a react-redux app working perfectly fine with the UI being auto updated after every file change, then I decided to plugin sass into my app and the auto-reloading stopped working. So in order to get sass in my app, I had to install sass-loader, node-sass, css-loader, etc. But one of the loaders needed webpack 2, so I switched from 1.15 to 2.0, now when I run "npm run dev" I see webpack recompile after every file change, but my UI isn't being auto reloaded in my browser. Can anyone help me troubleshoot this?
Here is my webpack config file:
var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
var path = require('path');
module.exports = {
context: path.join(__dirname, "src"),
devtool: debug ? "inline-sourcemap" : null,
entry: "./js/app.js",
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules)/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-0'],
plugins: ['react-html-attrs', 'transform-class-properties', 'transform-decorators-legacy', "transform-object-rest-spread"],
}
},
{
test: /\.scss$/,
loader: 'style-loader!css-loader!sass-loader'
}
]
},
output: {
path: __dirname + "/src/",
filename: "app.min.js"
},
plugins: debug ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
],
};
An here is my package.json file:
{
"name": "campaign-viewer",
"version": "0.0.0",
"description": "Code challenge from MediaMath",
"main": "webpack.config.js",
"dependencies": {
"axios": "^0.12.0",
"babel-core": "^6.18.2",
"babel-loader": "^6.2.0",
"babel-plugin-add-module-exports": "^0.1.2",
"babel-plugin-react-html-attrs": "^2.0.0",
"babel-plugin-transform-class-properties": "^6.3.13",
"babel-plugin-transform-decorators-legacy": "^1.3.4",
"babel-plugin-transform-object-rest-spread": "^6.23.0",
"babel-preset-es2015": "^6.3.13",
"babel-preset-react": "^6.3.13",
"babel-preset-stage-0": "^6.3.13",
"css-loader": "^0.28.4",
"moment": "^2.18.1",
"node-sass": "^4.5.3",
"react": "^0.14.6",
"react-datetime": "^2.8.10",
"react-dom": "^0.14.6",
"react-redux": "^4.4.5",
"redux": "^3.6.0",
"redux-logger": "^2.6.1",
"redux-promise-middleware": "^3.2.0",
"redux-thunk": "^2.1.0",
"sass-loader": "^6.0.6",
"style-loader": "^0.18.2",
"webpack": "^2.0.0",
"webpack-dev-server": "^1.14.1"
},
"devDependencies": {},
"scripts": {
"dev": "./node_modules/.bin/webpack-dev-server --content-base src --inline --hot",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Chris Stephenson",
"license": "ISC"
}
Looks like the problem was with using webpack-dev-server. When I used version 2.0.0 instead of 1.14.1 it started auto reloading again.

Webpack sass to css specify a specific folder?

I've been looking over the docs and checking other people's questions but I can't find the simple answer to how to compile all my sass down to a simple css file and specify the directory I want the resulting css file to output to.
For quick context:
I have a public directory with a stylesheets directory and a build directory in it. webpack compiles the app into build, and I'd like to have the sass compile style.css into the stylesheets directory.
Here's a screenshot of my public directory:
public dir img
I'd like to be able to do something like this in my webpack.config.js (only showing pertinent code for brevity):
const ExtractTextPlugin = require('extract-text-webpack-plugin');
...
// To be called in plugins:
const cssOutput = new ExtractTextPlugin('./public/stylesheets/style.css');
inside module loaders:
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract('style-loader', 'css-loader!sass-loader'),
},
In plugins:
plugins: [
.
.
.
cssOutput,
],
I'd like to be able to access the output file with this line in my index.html file located in the public directory:
<link rel="stylesheet" href="/stylesheets/style.css" />
I'm currently doing this using gulp and it works fine, I'm just trying to transition everything into webpack. Any help would be greatly appreciated!
Turns out you can just set the output file like this:
const cssOutput = new ExtractTextPlugin('../stylesheets/style.css', { allChunks: true });
I made the noob mistake of forgetting to add:
require('_scss/style.scss');
in my index.jsx file.
For anyone who runs into this issue, I still had trouble with fonts and images, so inside module loaders in the webpack.config.js I had to add:
{
test: /\.(eot|woff|woff2|ttf|svg|png|jpe?g|gif)(\?\S*)?$/,
loader: 'file',
},
and since this output everything into my build directory, I just changed the css to output everything in the build directory as well to prevent path errors. I changed it to this:
const cssOutput = new ExtractTextPlugin('style.css', { allChunks: true });
Hopefully this helps someone else who runs into this type of issue!
Work for Me::
webpack.config.js
module.exports = {
entry: ['./src/app.ts', './src/sass/style.scss'],
module:{
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
include: [path.resolve(__dirname, 'src', 'src/class')]
},
{
test: /\.scss$/,
use: [
{
loader: 'file-loader',
options: {
name: '/css/[name].css'
}
},
{
loader: 'extract-loader'
},
{
loader: 'css-loader?-url'
},
{
loader: 'postcss-loader'
},
{
loader: 'sass-loader'
}
],
include: [path.resolve(__dirname, 'src/sass')]
}
]
},
output: {
filename: 'js/app.js',
path: path.resolve(__dirname, 'public')
}
}
postcss.config.js
module.exports = {
plugins: {
'autoprefixer': {}
}
}
package.json
{
"name": "tsscript",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"nov": "webpack",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"autoprefixer": "^9.8.5",
"css": "^3.0.0",
"css-loader": "^3.6.0",
"extract-loader": "^5.1.0",
"postcss-loader": "^3.0.0",
"sass": "^1.26.10",
"sass-loader": "^9.0.2",
"style-loader": "^1.2.1",
"ts-loader": "^8.0.0",
"typescript": "^3.9.6",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.12"
}
}
Directory Snap:
Have you take a look at https://www.npmjs.com/package/extract-text-webpack-plugin?
you'll probably need it.
Recent solution, you can use mini-css-extract-plugin, css-loader, and sass-loader. mini-css-extract-plugin can create a CSS file per JS file which contains CSS.
Install dependencies:
npm i -D mini-css-extract-plugin css-loader sass-loader
For example, your main JS file that includes a style is ./src/index.js:
...
import './src/style.scss';
...
Configure webpack.config.js:
...
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
...
entry: {
main: './src/index.js',
},
plugins: [
new MiniCssExtractPlugin(),
],
...
module: {
rules: [
...
{
test: /\.s[ac]ss$/i,
use: [
MiniCssExtractPlugin.loader,
"css-loader",
"sass-loader",
],
},
...
]
},
resolve: {
modules: ["node_modules", path.resolve(__dirname, "src")],
extensions: ['.js', '.scss', ...]
}
}
Then, you can check your output directory, there will be main.css. The plugin set default name to [name].css (entry name).

Resources