I am using VueJS3 cli. New in VueJS here :)
I have a csv file in my folder:
/src/db/example.csv
I would like to load it and use it as data structure, in the same way I do it with json files:
import jsonExample from "#/db/example.json";
If I try to do it with a csv file I get this:
import csvExample from "#/db/example.csv";
// 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 tried to install the csv-loader
yarn add csv-loader
But I don't know where to add the configuration (https://www.npmjs.com/package/csv-loader#user-content-usage) I don't have any webpack configuration file :/, I have:
babel.config.js
jsconfig.json
package.json
vue.config.js
yarn.lock
I also tried to use papaparse directly:
this.$papa.parse("#/db/example.csv");
But I get this error:
{
"data": [
[
"#/db/exaple.csv"
]
],
"errors": [
{
"type": "Delimiter",
"code": "UndetectableDelimiter",
"message": "Unable to auto-detect delimiting character; defaulted to ','"
}
],
"meta": {
"delimiter": ",",
"linebreak": "\n",
"aborted": false,
"truncated": false,
"cursor": 19
}
}
Obviously it is interpreting the Path as a the Data.
Following instructions here: https://cli.vuejs.org/guide/webpack.html#working-with-webpack
I configured the loader like this:
// vue.config.js
const { defineConfig } = require('#vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
chainWebpack: config => {
// csv-loader
config.module
.rule('csv-loader')
.test(/\.csv$/)
.use('csv-loader')
.loader('csv-loader')
.end()
}
})
Now this is working:
import data from "#/db/example.csv";
PD: I had to restart yarn serve
Related
I started learning Gulp by repeating a YouTube video. So far, I have not reached the conversion of files, but copying files from the scr folder to the dist folder has already been implemented. But that doesn't work for me either.
In order not to lose heart, I began to study this error and other examples. But nothing helped me. This is the first time I've come across this. I even tried downloading other 100% working projects, but they can't do anything and don't work as I expect. The funny thing is that gulp doesn't throw any errors or anything, it sends a successful response and the execution time is around 30 milliseconds.
I have a desire to return to laravel or start learning laravel mix, but I can't let go of the gulp convenience that I want to learn. To some extent, we can say that I tried to create sites myself and everything in a similar spirit. In web programming for about 3 years and several times created their own sites. Each time I tried to use new technologies, here is the same story.
P.S. I am currently using macOS Catalina. Also tried to do it on Windows 10 - no positive result.
Project.
- gulp
-- config
--- ftp.js
--- path.js
--- plugins.js
-- tasks
--- copy.js
- node_modules
- scr
-- files
--- index.txt
- gulpfile.js
- package.json
Files.
gulpfile.js
import gulp from "gulp";
import { path } from "./gulp/config/path.js";
global.app = {
path: path,
gulp: gulp,
};
import { copy } from "./gulp/tasks/copy.js";
function watcher(){
gulp.watch(path.watch.files, copy);
}
const dev = gulp.series(copy, watcher);
gulp.task("default", dev);
path.js
import * as nodePath from "path";
const rootFolder = nodePath.basename(nodePath.resolve());
const buildFolder = "./dist";
const srcFolder = "./src";
export const path = {
build: {
files: "${buildFolder}/files"
},
src: {
files: "${srcFolder}/files/**/*.*"
},
watch: {
files: "${srcFolder}/files/**/*.*"
},
clean: buildFolder,
buildFolder: buildFolder,
srcFolder: srcFolder,
rootFolder: rootFolder,
ftp: ""
};
copy.js
export const copy = () => {
return app.gulp.src(app.path.src.files)
.pipe(app.gulp.dest(app.path.build.files));
}
package.json
{
"name": "<name>",
"version": "1.0.0",
"description": "",
"main": "gulpfile.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "<url>"
},
"author": "<author>",
"license": "ISC",
"bugs": {
"url": "<url>"
},
"homepage": "<url>",
"devDependencies": {
"gulp": "^4.0.2"
}
}
P.S.S. A watcher was added to the project, earlier the copy function was performed as the main task, but nothing worked there either. watcher itself does not create a dist folder.
I have a valid appsettings.json file (according to jsonlint.com), I've set the tsconfig resolveJsonModule option to true. I'm importing #rollup/plugin-json and I've tried calling it at every position in the plugins chain. But I always get:
(!) Plugin json: Could not parse JSON file
appsettings.json
[!] Error: Unexpected token (Note that you need #rollup/plugin-json to import JSON files)
appsettings.json (2:10)
So the plugin is firing (I think), but it can't parse the file, which seems to be valid. Rollup config looks like this:
import typescript from '#rollup/plugin-typescript';
import resolve from '#rollup/plugin-node-resolve';
import commonjs from "#rollup/plugin-commonjs";
import dev from 'rollup-plugin-dev';
import copy from 'rollup-plugin-copy';
import replace from '#rollup/plugin-replace';
// Loaders for non-ts/js file types
import postcss from 'rollup-plugin-postcss';
import image from '#rollup/plugin-image';
import json from '#rollup/plugin-json';
console.log(`Node env is ${process.env.NODE_ENV}`);
// console.debug(process);
let isDevEnv = process.env.NODE_ENV === 'development';
let useMsw = process.env.USE_MSW;
const extensions = ['.cjs', '.js', '.jsx', '.json', '.ts', '.tsx', '.css', '.png'];
// const intro = useMsw
// ? 'global = window; window.NODE_ENV = process.env.NODE_ENV; window.USE_MSW = true'
// : 'global = window; window.NODE_ENV = process.env.NODE_ENV; window.USE_MSW = false';
const intro = `global = window; window.NODE_ENV = process.env.NODE_ENV; ${useMsw ? 'window.USE_MSW = true;' : ''}`;
export default {
input: [
'src/index.tsx'
],
output: {
intro: intro,
file: './dist/bundle.js',
format: 'es',
sourcemap: isDevEnv,
inlineDynamicImports: true,
},
plugins: [
postcss({}),
resolve({
extensions: extensions,
browser: true
}),
commonjs(),
typescript(),
replace({
'process.env.NODE_ENV': JSON.stringify('development')
}),
image(),
copy({
targets: [
{src: './src/index.html', dest: './dist/'},
{src: './src/mockServiceWorker.js', dest: './dist/'}
],
verbose: true
}),
isDevEnv && dev('dist', {
host: 'localhost'
}),
json(),
]
};
tsconfig looks like this:
{
"compilerOptions": {
"declaration": false,
"module": "ESNext",
"noImplicitAny": true,
"target": "ES2015",
"jsx": "react",
"allowSyntheticDefaultImports": true,
"allowJs": true,
"moduleResolution": "Node",
"esModuleInterop": true,
"resolveJsonModule": true
},
"include": [
"src/**/*.tsx",
"src/**/*.ts",
"declaration.d.ts",
"src/components/TabularVIew/GridContainer/hooks"
],
"exclude": ["node_modules"]
}
and the actual json file looks like this:
{
"HUB_URL": "theHubUrl",
"AUTH_ENDPOINT": "https://localhost:44330/API/Dispatch/Authentication/v1.0/authenticate",
"POSITION_ENDPOINT": "https://localhost:44330/API/Dispatch/Data/v1.0/position",
"SUMMARY_ENDPOINT": "https://localhost:44330/API/Dispatch/Data/v1.0/summaries",
"GLOBAL_TLM": 1,
"PERIOD_LENGTH_MINUTES": 30,
"EFA_BLOCKS": [
[23,0,1,2],
[3,4,5,6],
[7,8,9,10],
[11,12,13,14],
[15,16,17,18],
[19,20,21,22]
]
}
and the rollup output is this:
(!) Plugin json: Could not parse JSON file
appsettings.json
[!] Error: Unexpected token (Note that you need #rollup/plugin-json to import JSON files)
appsettings.json (2:10)
Pretty frustrating because on one line it says 'plugin json can't parse', then the next log line tells me I need plugin json???. Invalid file, file not found, plugin not installed, these I could understand. Possibly a clash between tsc and the plugin. Out of ideas..
Suggestions welcome.
Thanks.
The reason for that can be the json file encoding is utf8withbom. Try to encode the file as utf8.
Not really an answer, but the behaviour appears to be linked to some aggressive caching. Either by npm or typescript. I opened up the project in vscode, hosed node_modules, ran npm install, usual drill.. created a new JSON file, installed the rollup json plugin, and it built. Sum total of learning: 0;
I'm trying to cover basic reducer with a test but it throws the error for export in my constants file:
FAIL jest/spec/reducers/RootReducer.spec.js
● Test suite failed to run
Jest encountered an unexpected token
Details:
project-root\js\src\constants\ActionTypes.js:2
export const LOCALE_REQUEST = 'ROOT/LOCALE_REQUEST';
^^^^^^
SyntaxError: Unexpected token export
1 | 'use strict';
2 |
> 3 | import { LOCALE_REQUEST_SUCCESS, ROUTING_REQUEST_SUCCESS } from '/js/src/constants/ActionTypes';
| ^
4 |
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
at Object.<anonymous> (jest/spec/reducers/RootReducer.spec.js:3:1)
I'm running the tests from 'project-root\tests' folder
The js files that I want to test are located in 'project-root\js' folder
I believe this is the reason for the bug. Because the file I'm trying to import is outside of the tests folder it looks like it's not being transpiled
this is my package.json:
{
"name": "jest",
"version": "0.0.0",
"scripts": {
"test": "jest"
},
"devDependencies": {
"#babel/core": "^7.2.2",
"#babel/plugin-transform-modules-commonjs": "^7.2.0",
"#babel/preset-env": "^7.2.3",
"babel-core": "7.0.0-bridge.0",
"jest": "^23.6.0"
}
}
this is .babelrc:
{
"presets": [
"#babel/preset-env"
],
"plugins": [
"#babel/plugin-transform-modules-commonjs"
]
}
this is jest.config.js:
module.exports = {
verbose: true,
transform: {
"^.+\\.jsx?$": "babel-jest"
},
bail: true,
browser: true,
cacheDirectory: '/tmp/jest',
collectCoverage: false,
roots: [
'<rootDir>/../js',
'<rootDir>/jest'
],
moduleNameMapper: {
'^(.*)/js/(.*)$': '<rootDir>/../js/$2'
},
testRegex: '(jest/spec/.*|(\\.|/)(test|spec))\\.js$',
testPathIgnorePatterns: [
'<rootDir>/node_modules'
],
transformIgnorePatterns: [
'/node_modules/'
]
};
So I've tried to look for similar cases around the web but in most cases the problems come from /node_modules or something missing in the jest config. But I can't find what's wrong in my case, would really appreciate any hints what can I try
up: someone suggested that I need to add babel-jest to my package.json but it's already in /node_modules - it is added with jest package
The problem surrounds the fact that you have no babel-loader setup so the project will blow up on import and export commands that do not get removed from the source code during compilation as babel has no idea how to handle that without babel-loader installed and configured.
For a quick example of how to get started with ES6 transpiling and module loading you can check out this example.
youtube.com/watch?v=X5wTsHRsbIA
I seem to have encountered a problem similar to this.
file my-app.js:
import {PolymerElement, html} from "../node_modules/#polymer/polymer/polymer-element.js";
import "../node_modules/#polymer/polymer/lib/elements/dom-if.js";
import "../node_modules/#polymer/app-route/app-location.js";
import "../node_modules/#polymer/app-route/app-route.js";
class MyApp extends PolymerElement {
...
}
customElements.define('my-app',MyApp);
file polymer.json:
{
"entrypoint":"index.html"
,"shell":"src/my-app.js"
,"builds":[
{
"preset":"es5-bundled"
,"addServiceWorker": false
}
]
}
command polymer build produces file my-app.js with 0 byte. All other built files look correct according to my naked eyes (at least they are not truncated to 0 byte).
I then re-built the application with the following "dev" polymer.json:
"builds":[
{
"name": "dev",
"addServiceWorker": false,
"js": {"minify": false, "compile": false},
"css": {"minify": false},
"html": {"minify": false},
"bundle": false,
"addPushManifest": false
}
]
The built my-app.js looks correct with this "dev" configuration. However, browser's sources window highlights with red under score the first of the followings lines:
import {PolymerElement, html} from "../node_modules/#polymer/polymer/polymer-element.js";
import "../node_modules/#polymer/polymer/lib/elements/dom-if.js";
import "../node_modules/#polymer/app-route/app-location.js";
import "../node_modules/#polymer/app-route/app-route.js";
and console window prints this strange message:
Uncaught TypeError: Failed to resolve module specifier "#polymer/polymer/polymer-legacy.js". Relative references must start with either "/", "./", or "../". (index):1
I have searched all my .js files and directory ../node_modules/ and have not found any file containing polymer-legacy.js.
Helps will be much appreciated.
EDIT
Thank you for the attention!
These weird symptoms are caused by the stale polymer 1.6.0 which was installed in /usr/local/bin/polymer using yarn .
These issues are gone with polymer 1.7.2.
Based on this answer here https://stackoverflow.com/a/22524056/777700 I have set exactly the same configuration options, but it doesn't work.
My (partial) app.js file:
console.log('environment: '+process.env.NODE_ENV);
const config = require('./config/db.json')[process.env.NODE_ENV || "development"];
console.log(config);
My ./config/db.json file:
{
"development":{
"host":"localhost",
"port":"3306",
"username":"root",
"password":"",
"database":"dbname"
},
"production":{
"host":"production-host",
"port":"3306",
"username":"user",
"password":"pwd",
"database":"dbname"
}
}
Console.log outputs:
environment: development
undefined
and app crashes. Any idea why? File is there, if I remove the [...] part of require(), it does print out the db.json file, with it, it prints out undefined.
EDIT
I tried to add console.log(typeof config) just after require() to see what I'm getting and I have noticed that if I require('./config/db.json')[process.env.NODE_ENV] I get undefined, but if I require('./config/db.json')["development"] I get back proper object.
Versions:
nodeJS 6.11.4
express 4.16.2
After more debugging and searching online, I have finally found the solution. The problem is that I'm on Windows machine and I was using npm run dev command while my "dev" command looked like SET NODE_ENV=development && nodemon server.js.
Experienced eye will notice a space before &&, which added a space behind the variable development, so the variable I was comparing against was "development " and not "development" as I was thinking.
So, the original answer from other question does work and it does load proper config!
You should export configuration as a variable:
const config = {
"development":{
"host":"localhost",
"port":"3306",
"username":"root",
"password":"",
"database":"dbname"
},
"production":{
"host":"production-host",
"port":"3306",
"username":"user",
"password":"pwd",
"database":"dbname"
}
};
module.exports = config;
This way it will be found :)
If you want to do it via JSON:
const fs = require('fs')
let localConfig
try {
localConfig = JSON.parse((fs.readFileSync('./config/db.json', 'utf-8'))
} catch (e) {
console.log('Could not parse local config.')
localConfig = false
}
module.exports = localConfig
You could then add logic for production, if there's no local configuration localConfig will return false and you can look for environment variables injected at that point.
Update:
I see that you're giving the production config yourself, in that case you can just access the key you need based on the environment. Just import localConfig and use the keys you need.
Its better to use dotenv package for this
npm i dotenv
Step 1: In package.json add this
"scripts": {
"start": "nodemon app.js",
"dev": "NODE_ENV=dev nodemon app.js"
"prod": "NODE_ENV=prod nodemon app.js"
},
Step 2: Add .env.prod and .env.dev files
.env.dev
PORT=7200
# Set your database/API connection information here
DB_URI=localhost
DB_USERNAME=root
DB_PASSWORD=password
DB_DEFAULT=dbName
Step 3: Add this in config.js
const dotenv = require('dotenv').config({ path: `.env.${process.env.NODE_ENV}` });
const result = dotenv;
if (result.error) {
throw result.error;
}
const { parsed: envs } = result;
// console.log(envs);
module.exports = envs;
Step 4: Use like this when needed
const {
DB_URI, DB_USERNAME, DB_PASSWORD, DB_DEFAULT,
} = require('../config');
Now if u want for development, run
npm run dev
For prod, use
npm run prod