I am trying to use vue js in rails.
Everything works, except when I tried to use <style> inside .vue component
The exact error is:
./app/javascript/layouts/dashboard.vue?vue&type=style&index=0&lang=scss& (./node_modules/css-loader/dist/cjs.js!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/sass-loader/dist/cjs.js??ref--1-2!./node_modules/style-loader/dist!./node_modules/css-loader/dist/cjs.js??ref--5-1!./node_modules/postcss-loader/src??ref--5-2!./node_modules/sass-loader/dist/cjs.js??ref--5-3!./node_modules/vue-loader/lib??vue-loader-options!./app/javascript/layouts/dashboard.vue?vue&type=style&index=0&lang=scss&)
Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
SassError: Expected newline.
My environment.js file
const { environment } = require('#rails/webpacker')
const { VueLoaderPlugin } = require('vue-loader')
const vueLoader = require('./loaders/vueLoader')
const vuetifyLoader = require('./loaders/vuetifyLoader')
environment.plugins.prepend('VueLoaderPlugin', new VueLoaderPlugin())
environment.loaders.prepend('vue', vueLoader)
environment.loaders.prepend('vuetify', vuetifyLoader)
const resolver = {
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js'
}
}
}
environment.config.merge(resolver)
module.exports = environment
VuetifyLoader.js file
module.exports = {
test: /\.s(c|a)ss$/,
use: [
'vue-style-loader',
'css-loader',
{
loader: 'sass-loader',
// Requires sass-loader#^7.0.0
options: {
implementation: require('sass'),
fiber: require('fibers'),
indentedSyntax: true // optional
},
// Requires sass-loader#^8.0.0
options: {
implementation: require('sass'),
sassOptions: {
fiber: require('fibers'),
indentedSyntax: true // optional
},
},
},
],
}
install these two plugins.
npm install --save node-sass
npm install --save sass-loader
So, the problem was with fiber and indentedSyntax. After removing those two, everything works as expected. I was getting lots of error related to scss like
like
expected new line
in sass files inside node_modules. I don't know, why vuetify recommends to use fiber in sass loader.
In electron, how can I write a file when the app is packaged using electron packager.
The following will create and update the file in development. But once I package the app using electron-packager, the file will no longer be created. What do I need to change?
// imports
const path = require('path');
const fs = require('fs');
// create stream for appending to the log file
stream = fs.createWriteStream(
path.join(__dirname, 'logfile.log'),
{
flags:'a'
}
);
// append content to the log file
stream.write('test');
Here's how I package it:
"scripts": {
"start": "electron .",
"pack:win64": "electron-packager . my-app --out=dist/win64 --platform=win32 --arch=x64 --icon=assets/icon.png --prune=true --overwrite --asar"
},
I haven't tried this but perhaps you could use the afterCopy hook to call the function you need?
afterCopy
Array of Functions
An array of functions to be called after your app directory has been
copied to a temporary directory. Each function is called with five
parameters:
buildPath (String): The path to the temporary folder where your app has been copied to
electronVersion (String): The version of electron you are packaging for
platform (String): The target platform you are packaging for
arch (String): The target architecture you are packaging for
callback (Function): Must be called once you have completed your actions
const packager = require('electron-packager')
const { serialHooks } = require('electron-packager/hooks')
packager({
// ...
afterCopy: [serialHooks([
(buildPath, electronVersion, platform, arch) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log('first function')
resolve()
}, 1000)
})
},
(buildPath, electronVersion, platform, arch) => {
console.log('second function')
}
])],
// ...
})
I am trying to use Webpack with Babel to compile ES6 assets, but I am getting the following error message:
You may need an appropriate loader to handle this file type.
| import React from 'react';
| /*
| import { render } from 'react-dom'
Here is what my Webpack config looks like:
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: './index',
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/dist/'
},
module: {
loaders: [
{
test: /\.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/
}
]
}
}
Here is the middleware step that makes use of Webpack:
var webpack = require('webpack');
var webpackDevMiddleware = require('webpack-dev-middleware');
var config = require('./webpack.config');
var express = require('express');
var app = express();
var port = 3000;
var compiler = webpack(config);
app.use(webpackDevMiddleware(compiler, {
noInfo: true,
publicPath: config.output.publicPath
}));
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
app.listen(port, function(err) {
console.log('Server started on http://localhost:%s', port);
});
All my index.js file is doing is importing react, but it seems like the 'babel-loader' is not working.
I am using 'babel-loader' 6.0.0.
You need to install the es2015 preset:
npm install babel-preset-es2015
and then configure babel-loader:
{
test: /\.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015']
}
}
Make sure you have the es2015 babel preset installed.
An example package.json devDependencies is:
"devDependencies": {
"babel-core": "^6.0.20",
"babel-loader": "^6.0.1",
"babel-preset-es2015": "^6.0.15",
"babel-preset-react": "^6.0.15",
"babel-preset-stage-0": "^6.0.15",
"webpack": "^1.9.6",
"webpack-dev-middleware": "^1.2.0",
"webpack-hot-middleware": "^2.0.0"
},
Now configure babel-loader in your webpack config:
{ test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }
add a .babelrc file to the root of your project where the node modules are:
{
"presets": ["es2015", "stage-0", "react"]
}
More info:
babeljs.io - using babel with webpack
babeljs.io - docs on .babelrc
react-webpack-cookbook - configure react with webpack
a react-webpack-example repo
If you are using Webpack > 3 then you only need to install babel-preset-env, since this preset accounts for es2015, es2016 and es2017.
var path = require('path');
let webpack = require("webpack");
module.exports = {
entry: {
app: './app/App.js',
vendor: ["react","react-dom"]
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, '../public')
},
module: {
rules: [{
test: /\.jsx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader?cacheDirectory=true',
}
}]
}
};
This picks up its configuration from my .babelrc file:
{
"presets": [
[
"env",
{
"targets": {
"browsers":["last 2 versions"],
"node":"current"
}
}
],["react"]
]
}
BABEL TEAM UPDATE:
We're super 😸 excited that you're trying to use ES2015 syntax, but instead of continuing yearly presets, the team recommends using babel-preset-env. By default, it has the same behavior as previous presets to compile ES2015+ to ES5
If you are using Babel version 7 you will need to run npm install #babel/preset-env and have "presets": ["#babel/preset-env"] in your .babelrc configuration.
This will compile all latest features to es5 transpiled code:
Prerequisites:
Webpack 4+
Babel 7+
Step-1:: npm install --save-dev #babel/preset-env
Step-2: In order to compile JSX code to es5 babel provides #babel/preset-react package to convert reactjsx extension file to native browser understandable code.
Step-3: npm install --save-dev #babel/preset-react
Step-4: create .babelrc file inside root path path of your project where webpack.config.js exists.
{
"presets": ["#babel/preset-env", "#babel/preset-react"]
}
Step-5: webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
mode: 'development',
entry: path.resolve(__dirname, 'src/index.js'),
output: {
path: path.resolve(__dirname, 'output'),
filename: 'bundle.js'
},
resolve: {
extensions: ['.js', '.jsx']
},
module: {
rules: [{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
},
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: "./public/index.html",
filename: "./index.html"
})
]
}
In my case, I had such error since import path was wrong:
Wrong:
import Select from "react-select/src/Select"; // it was auto-generated by IDE ;)
Correct:
import Select from "react-select";
Due to updates and changes overtime, version compatibility start causing issues with configuration.
Your webpack.config.js should be like this you can also configure how ever you dim fit.
var path = require('path');
var webpack = require("webpack");
module.exports = {
entry: './src/js/app.js',
devtool: 'source-map',
mode: 'development',
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
use: ["babel-loader"]
},{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}]
},
output: {
path: path.resolve(__dirname, './src/vendor'),
filename: 'bundle.min.js'
}
};
Another Thing to notice it's the change of args, you should read babel documentation https://babeljs.io/docs/en/presets
.babelrc
{
"presets": ["#babel/preset-env", "#babel/preset-react"]
}
NB: you have to make sure you have the above #babel/preset-env & #babel/preset-react installed in your package.json dependencies
You probably forgot to add .js extension to your file.
Component -> Component.js
This makes me feel stupid, but I want to share for anyone that got frustrated like me: I used webpack.dev.js but didn't specify that as the config file! When running Webpack run with:
webpack --config webpack.dev.js
And it suddenly worked ;)
Just adding on another reason such error showed up in Angular.. was because I checked for html file in list of styles:
#Component({
selector: ...,
templateUrls: 'xyz.html',
stylesUrls: ['xyz.html'] // problem
})
Addressing wrong file type raises this error
As question doesn't specify if it was for angular, react, or react-native. I am posting this for react-native and it may be implied on others too. The reason was that it wasn't able to understand the syntax specified by loader. e.g. tsx, jsx. One solution I found in this article after lots of exploration. When we use external library that was using jsx and you configured your project with tsx, it won't understand jsx and will give you to add appropriate loader. So, you can fix that by following code in your app.json file.
"web": {
"build": {
"babel": {
"include": [
"name-of-my-shared-package-here"
]
}
}
}
By replacing name-of-my-shared-package-here with your package name that is causing the issue will solve this issue. You can check the package name in error that is causing this issue.
Outdated babel packages on Jan 3, 2023
Please install these list of packages for configuration with babel.
$ npm add -D #babel/core babel-loader #babel/preset-env #babel/preset-react
and add below code .babelrc file
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
]
}
I used #khizer webpack configuration in my application
Credit goes to This answer. As I have have been gone through the best answer of this solution and it tooks my 2-3 hours. I hope other don't waste same amount of time.
When using Typescript:
In my case I used the newer syntax of webpack v3.11 from their documentation page
I just copied the css and style loaders configuration form their website.
The commented out code (newer API) causes this error, see below.
module: {
loaders: [{
test: /\.ts$/,
loaders: ['ts-loader']
},
{
test: /\.css$/,
loaders: [
'style-loader',
'css-loader'
]
}
]
// ,
// rules: [{
// test: /\.css$/,
// use: [
// 'style-loader',
// 'css-loader'
// ]
// }]
}
The right way is to put this:
{
test: /\.css$/,
loaders: [
'style-loader',
'css-loader'
]
}
in the array of the loaders property.
This one throw me for a spin.
Angular 7, Webpack
I found this article so I want to give credit to the Article
https://www.edc4it.com/blog/web/helloworld-angular2.html
What the solution is:
//on your component file. use template as webpack will treat it as text
template: require('./process.component.html')
for karma to interpret it
npm install add html-loader --save-dev
{
test: /.html$/,
use: "html-loader"
},
Hope this helps somebody
Just add this code webpackmix.js
mix.js('resources/js/app.js', 'public/js')
.postCss('resources/css/app.css', 'public/css', [
require('tailwindcss'),
]).vue();
When I run the application from command prompt using npm start command it works well. It returning the result from speech api.
I am using binaryServer and binaryclient to stream audio to google cloud API.
When I create package for electron application everything works but it not returning the result from speech api.
Here are my code snippe:
Package.json
{
"name": "test",
"version": "1.0.0",
"description": "test Web Server",
"main": "main.js",
"scripts": {
"start": "electron main.js"
},
"devDependencies": {
"electron": "^1.4.12"
},
"dependencies": {
"binaryjs": "^0.2.1",
"connect": "^3.3.4",
"biased-opener": "^0.2.8",
"serve-static": "^1.9.1",
"uaparser": "^0.0.2",
"#google-cloud/speech" : "^0.5.0"
}
}
Here is my main.js
app.on('ready', function () {
load_app();
});
var workerProcess = child_process.spawn('node', __dirname + '/binaryServer.js');
workerProcess.stdout.on('data', function (data) {
console.log('stdout: ' + data);
});
workerProcess.stderr.on('data', function (data) {
console.log('stderr: ' + data);
});
workerProcess.on('close', function (code) {
console.log('child process exited with code ' + code);
});
processes.push(workerProcess);
function load_app () {
// Launches the browser window
mainWindow = new BrowserWindow({ width: 1080, height: 1920 });
// Load just launched server in browser window
mainWindow.loadURL("http://localhost:" + config.port);
if (config.devMode) {
mainWindow.webContents.openDevTools();
}
else {
mainWindow.setFullScreen(true);
}
}
here is my binary server
var binaryServer = require('binaryjs').BinaryServer,
https = require('http'),
connect = require('connect'),
serveStatic = require('serve-static');
var config = require('./config');
var server = connect()
.use(serveStatic(__dirname));
var speech = require('#google-cloud/speech')({
projectId: config.speech.projectId,
keyFilename: config.speech.keyFilename
});
httpServer = https.createServer(server);
httpServer.timeout = 0;
httpServer.listen(config.port);
var binarySer = binaryServer({ server: httpServer });
console.log("server pid" + process.pid);
binarySer.on('connection', function (client) {
console.log("new connection...");
client.on('stream', function (stream, meta) {
var options = {
config: {
encoding: 'LINEAR16',
sampleRate: meta.sampleRate,
languageCode: "en-IN"
},
singleUtterance: false,
interimResults: true,
verbose: true
};
// Create a recognize stream
const recognizeStream = speech.createRecognizeStream(options)
.on('error', console.error)
.on('data', function (data) { if (stream.writable && !stream.destroyed) stream.write(data) }); // send data to client
if (recognizeStream.writable && !recognizeStream.destroyed && stream.readable && !stream.destroyed)
stream.pipe(recognizeStream); // pipe audio to cloud speech
});
client.on('close', function () {
console.log("Connection Closed");
});
});
Thanks for your help
Taking a shot in the dark here (without much familiarity with binaryServer, which realistically could be the issue). I'm also a bit unclear about where the audio stream actually comes from:
Electron packages its own version of V8. When you run npm install it will install (or compile on the fly) the native binaries targeted for the version of V8 that are installed on your machine (local version). When you spawn the child process it uses that same local version.
However, when you package your electron app it will try to spawn the process with Electron's version of V8 and there will be binary incompatibilities.
Put simply
[Your version of V8] != [Electron's version of V8]
On to potential solutions
Sonus is compatible with
Electron provided that you
Re-compile dependencies with
electron-recompile
Lets say I have a project that uses bower, grunt, bowerify(with shim) and since I love Jest so much I want to test with that. How in the world do I get jest to see my browserify shim modules when it runs tests. I use grunt, to kick off the npm test command.
Here is my package.json file.
"browser": {
"jquery": "./bower_components/jquery/dist/jquery.js",
"foundation": "./bower_components/foundation/js/foundation/foundation.js",
"fastclick": "./bower_components/fastclick/lib/fastclick.js",
"greensock-tm": "./bower_components/gsap/src/uncompressed/TweenMax.js",
"greensock-css": "./bower_components/gsap/src/uncompressed/plugins/CSSPlugin.js",
"greensock-time": "./bower_components/gsap/src/uncompressed/TimelineMax.js",
"scrollmagic": "./bower_components/ScrollMagic/js/jquery.scrollmagic.js",
"handlebars": "./bower_components/handlebars/handlebars.runtime.js"
},
"browserify-shim": {
"jquery": "$",
"greensock-css": "CSSPlugin",
"fastclick": "FastClick",
"greensock-tm": "TweenMax",
"greensock-time": "TimelineMax",
"scrollmagic": "ScrollMagic",
"foundation": "foundation",
"handlebars": "Handlebars"
},
"browserify": {
"transform": [
"browserify-shim"
]
},
Right now I almost have this worked out by doing this in my grunt file before I run the test.
grunt.registerTask("shimBowerForTests",function(){
var readJson = require('read-package-json');
var fs = require('fs');
var remapify = require('remapify');
readJson('./package.json', console.error, false, function (er, data) {
if (er) {
throw "There was an error reading the file";
}
var packages = data.browser;
var browserify = require('browserify');
for (var key in packages){
var b = browserify();
var wstream = fs.createWriteStream("devjs/test/modules/"+key+'.js');
b.add(packages[key]);
b.bundle().pipe(wstream);
}
});
});
and.
exec: {
jestTest: {
command: 'cp -r devjs/modules devjs/test/modules && npm test'
}
}
The problem is that using browserify so combine everything for the browser works great with my setup and I can require my shimmed modules like this.
require('jquery') //example but in the jest cli the test fail because they can find the module unless I somehow prefix it with ./, like so require('./jquery')
I'm guessing that the problem is that you've only installed your shimmed modules with bower. If you want them to work in node/jest, you'll have to install them with npm as well. Then just make sure Jest isn't mocking anything in the node_modules directory, and it should find all the required modules in there as long as the names match up.
Your Jest config in package.json should look like:
"jest": {
"unmockedModulePathPatterns": [
"./node_modules"
]
}
And then just download all the dependencies.
npm install jquery --save-dev
UPDATE
Instead of using my below solution you should opt for using Karma,karma browserify. I have converted the below solution into using karma and it is working much much better.
----------------------OLD ANSWER
What I actually did to solve this was, used the Jest source preprocessor to rewrite the require statement to look for a module in a certain directory in my /tests/ folder that I have created using grunt. The Folder contains the files listed in my browserify-shim, browser section of the package.json file.
EDIT: Here is how I shim bower, I made this script in the Gruntfile.js that puts all the bower modules and any commonjs modules that I need into an accessible directory.
grunt.registerTask("shimBowerForTests", function() {
var readJson = require('read-package-json');
var fs = require('fs');
readJson('./package.json', console.error, false, function(er, data) {
if (er) {
throw "There was an error reading the file";
}
var packages = data.browser;
var shim = data['browserify-shim'];
var browserify = require('browserify');
var exclude = ["jquery.maskedinput", "jquery"];
for (var key in packages) {
var b = browserify();
var wstream = fs.createWriteStream("devjs/test/modules/" + key + '.js');
if (shim[key] !== undefined && exclude.indexOf(key) === -1) {
b.add(packages[key]);
b.bundle().pipe(wstream);
} else {
var rstream = fs.createReadStream(packages[key]);
rstream.pipe(wstream);
}
}
});
});
Then in the Jest pre processor file I do this.
module.exports = {
process: function(src, path) {
var src2= src.replace(/require\([\"\']([^\.\'\"]+)[\"\']\)/g, "require(\'../modules/$1\')");
src2= src2.replace(/jest\.dontMock\([\"\']([^\.\'\"]+)[\"\']\)/g, "jest.dontMock(\'../modules/$1\')");
return src2;
}
};