how add coffeescript in svelte on Rails 7? - javascript

I have a Rails 7 app with esbuild :
esbuild.config.js :
#!/usr/bin/env node
const watch = process.argv.includes("--watch");
const esbuild = require('esbuild')
const coffeeScriptPlugin = require('esbuild-coffeescript');
const esbuildSvelte = require('esbuild-svelte');
const sveltePreprocess = require('svelte-preprocess');
esbuild
.build({
entryPoints: ["app/javascript/all.js"],
bundle: true,
outfile: "app/assets/builds/all.js",
// outdir: "app/assets/builds/",
plugins: [
esbuildSvelte({
preprocess: sveltePreprocess({coffeescript: { bare: true }}),
}),
// coffeeScriptPlugin({bare: true}), I TRIED THIS TOO...
],
logLevel: "debug",
watch: watch
})
.catch(() => process.exit(1));
my.svelte :
<script lang="coffee">
test = ->
console.log 'test coffee'
test()
</script>
got an error :
$ yarn build --watch yarn run v1.22.19 $ node ./esbuild.config.js
--watch ✘ [ERROR] [plugin esbuild-svelte] Unexpected token
app/javascript/all.js:3:3:
3 │ 1:
╵ ^
2: <script lang="coffee">
3: test = ->
^
4: console.log 'test coffee'
5: test()
The plugin "esbuild-svelte" was triggered by this import
app/javascript/svelte_src.js:6:32:
6 │ import DemoSvelteComponent from './svelte/DemoSvelteComponent.svelte'
╵ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 error [watch] build finished, watching for changes... error Command
failed with exit code 1. info Visit
https://yarnpkg.com/en/docs/cli/run for documentation about this
command.
$ node -v
v18.4.0
package.json :
{
"name": "app",
"private": "true",
"dependencies": {
"#hotwired/stimulus": "^3.0.1",
"#hotwired/turbo-rails": "^7.1.3",
"esbuild": "^0.14.43",
"esbuild-coffeescript": "^2.1.0",
"esbuild-svelte": "^0.7.1",
"sass": "^1.52.3",
"svelte": "^3.48.0",
"svelte-preprocess": "^4.10.7"
},
"scripts": {
"build": "node ./esbuild.config.js"
}
}
How add coffeescript in svelte with Rails ?

This setup works with node v18.4.0 v16.15.1 v14.19.3. It turned out pretty much identical to what you have, except I don't know what's in your all.js file.
// package.json
{
"name": "app",
"private": "true",
"dependencies": {
"#hotwired/stimulus": "^3.0.1",
"#hotwired/turbo-rails": "^7.1.3",
"esbuild": "^0.14.43",
"esbuild-coffeescript": "^2.0.0",
"esbuild-svelte": "^0.7.1",
"svelte": "^3.48.0",
"svelte-preprocess": "^4.10.7"
},
"scripts": {
"build": "node ./esbuild.config.js"
}
}
// esbuild.config.js
const watch = process.argv.includes("--watch");
const esbuild = require("esbuild");
const esbuildSvelte = require("esbuild-svelte");
const sveltePreprocess = require("svelte-preprocess");
esbuild
.build({
entryPoints: ["app/javascript/all.js"],
outdir: "app/assets/builds/",
bundle: true,
sourcemap: true,
plugins: [
esbuildSvelte({
preprocess: sveltePreprocess(),
}),
],
logLevel: "debug",
watch: watch,
})
.catch(() => process.exit(1));
// app/javascript/all.js
import App from "./my.svelte";
new App({ target: document.body });
<!-- app/javascript/my.svelte -->
<script lang="coffee">
test = ->
console.log 'test coffee'
test()
</script>
Compiles:
$ yarn build --watch
yarn run v1.22.19
$ node ./esbuild.config.js --watch
[watch] build finished, watching for changes...
[watch] build started (change: "app/javascript/my.svelte")
[watch] build finished
and shows up in the browser console:
test coffee my.svelte:1
This is a smaller working example, maybe it'll help eliminate the source of the error. It compiles my.svelte file directly and prints out the source.
// package.json
{
"dependencies": {
"esbuild": "^0.14.43",
"esbuild-coffeescript": "^2.1.0",
"esbuild-svelte": "^0.7.1",
"svelte": "^3.48.0",
"svelte-preprocess": "^4.10.7"
}
}
// esbuild.config.js
require("esbuild").build({
entryPoints: ["app/javascript/my.svelte"],
plugins: [require("esbuild-svelte")({ preprocess: require("svelte-preprocess")() })],
}).catch(() => process.exit(1));
$ node --version
v18.4.0
$ node ./esbuild.config.js
import { SvelteComponent, init, safe_not_equal } from "svelte/internal";
function instance($$self) {
var test;
test = function() {
return console.log("test coffee");
};
test();
return [];
}
class My extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance, null, safe_not_equal, {});
}
}
export default My;

I don't find the problem, I make new app and copy files, I don't see when exactly that works, but that works ... ^^
May be a bad invisible character was in file?
So It's works fine with include esbuild-coffeescript ...
That stay a mystery for my use case (I try checkout from git and bug don't come back.... realy strange)

I've met the same problem in my rails app and my solution was using another build script
old:
"build-es": "esbuild app/javascript/*.* --bundle --sourcemap --outdir=app/assets/builds --public-path=assets"
new:
"build": "node ./esbuild.config.js",

Related

Module not found: Can't resolve 'fs

I'm trying to use useDapp and pinata SDK in my next js application.
My package.json file looks like this:
"name": "eternity",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"#pinata/sdk": "^1.1.23",
"#usedapp/core": "^0.10.0",
"antd": "^4.18.5",
"next": "12.0.9",
"react": "17.0.2",
"react-dom": "17.0.2"
},
"devDependencies": {
"eslint": "8.8.0",
"eslint-config-next": "12.0.9"
}
}
The useDapp is working fine but when I try to use pinata api, I get errors. I ran a very basic test code like this:
import pinataSDK from "#pinata/sdk";
const pinataTest = () => {
const pinata = pinataSDK(
"5d349f3841ee16d7e668",
"a6f32583de5736824a606746f0b9b9bc365a5c81b3d1c9f1a98822a39ddfbb6d"
);
pinata
.testAuthentication()
.then((result) => {
console.log(result);
})
.catch((err) => {
console.log(err);
});
};
export default pinataTest;
It is just a test code given in the official docs of pinata SDK. But I run into this error.
https://nextjs.org/docs/messages/module-not-found
wait - compiling...
error - ./node_modules/#pinata/sdk/lib/pinata-sdk.js:24051:0
Module not found: Can't resolve 'fs'
Possible solutions to this error have been proposed here:
Module not found: Error: Can't resolve 'fs' in
The solutions that seems to be working for me is modifying my next.config.js file like this:
module.exports = {
reactStrictMode: true,
externals: {
FileReader: "FileReader",
},
webpack5: true,
webpack: (config, { isServer }) => {
if (!isServer) {
config.resolve.fallback = { fs: false };
}
return config;
},
};
It seems to have solved the 'fs not found error, but then I run into this next error:
ready - started server on 0.0.0.0:3000, url: http://localhost:3000
error - ./node_modules/js-sha3/src/sha3.js:21:0
Module not found: Can't resolve 'process'
Import trace for requested module:
./node_modules/#ethersproject/keccak256/lib.esm/index.js
./node_modules/#ethersproject/abi/lib.esm/interface.js
./node_modules/#ethersproject/abi/lib.esm/index.js
./node_modules/#usedapp/core/dist/esm/src/constants/abi/index.js
./node_modules/#usedapp/core/dist/esm/src/constants/index.js
./node_modules/#usedapp/core/dist/esm/src/index.js
./pages/_app.js
It seems like the #useDapp module is not working without 'fs'.
Is there a way to solve this? Or am I missing something fundamental while using useDapp and pinata SDK in my next js app.

How to add Sapper to existing Svelte project?

I have extensive applications in svelte, later I need to attach a sapper to it for further work, it is possibly? I try do it via:
npm i #sapper
but when I try to import something from this package e.q.:
import { goto } from '#sapper/app';
compiler throw me that i have no dependency to this sapper methods :(
I have no idea how to attach sapper to my project
my rollup
import svelte from "rollup-plugin-svelte";
import resolve from "#rollup/plugin-node-resolve";
import commonjs from "#rollup/plugin-commonjs";
import livereload from "rollup-plugin-livereload";
import { terser } from "rollup-plugin-terser";
// library that helps you import in svelte with
// absolute paths, instead of
// import Component from "../../../../components/Component.svelte";
// we will be able to say
// import Component from "components/Component.svelte";
import alias from "#rollup/plugin-alias";
const production = !process.env.ROLLUP_WATCH;
// configure aliases for absolute imports
const aliases = alias({
resolve: [".svelte", ".js"], //optional, by default this will just look for .js files or folders
entries: [
{ find: "components", replacement: "src/components" },
{ find: "views", replacement: "src/views" },
{ find: "assets", replacement: "src/assets" },
],
});
function serve() {
let server;
function toExit() {
if (server) server.kill(0);
}
return {
writeBundle() {
if (server) return;
server = require("child_process").spawn(
"npm",
["run", "start", "--", "--dev"],
{
stdio: ["ignore", "inherit", "inherit"],
shell: true,
}
);
process.on("SIGTERM", toExit);
process.on("exit", toExit);
},
};
}
export default {
input: "src/main.js",
output: {
sourcemap: true,
format: "iife",
name: "app",
file: "public/build/bundle.js",
},
plugins: [
svelte({
// enable run-time checks when not in production
dev: !production,
// we'll extract any component CSS out into
// a separate file - better for performance
css: (css) => {
css.write("bundle.css");
},
}),
// If you have external dependencies installed from
// npm, you'll most likely need these plugins. In
// some cases you'll need additional configuration -
// consult the documentation for details:
// https://github.com/rollup/plugins/tree/master/packages/commonjs
resolve({
browser: true,
dedupe: ["svelte"],
}),
commonjs(),
// In dev mode, call `npm run start` once
// the bundle has been generated
!production && serve(),
// Watch the `public` directory and refresh the
// browser on changes when not in production
!production && livereload("public"),
// If we're building for production (npm run build
// instead of npm run dev), minify
production && terser(),
// for absolut imports
// i.e., instead of
// import Component from "../../../../components/Component.svelte";
// we will be able to say
// import Component from "components/Component.svelte";
aliases,
],
watch: {
clearScreen: false,
},
};
my package.json:
{
"name": "svelte-app",
"version": "1.0.0",
"scripts": {
"build": "rollup -c",
"dev": "rollup -c -w",
"start": "sirv public -s",
"build:tailwind": "tailwind build public/assets/styles/index.css -o public/assets/styles/tailwind.css",
"build:fontawesome": "mkdir -p public/assets/vendor/#fortawesome/fontawesome-free/webfonts && mkdir -p public/assets/vendor/#fortawesome/fontawesome-free/css && cp -a ./node_modules/#fortawesome/fontawesome-free/webfonts public/assets/vendor/#fortawesome/fontawesome-free/ && cp ./node_modules/#fortawesome/fontawesome-free/css/all.min.css public/assets/vendor/#fortawesome/fontawesome-free/css/all.min.css",
"install:clean": "rm -rf node_modules/ && rm -rf package-lock.json && rm -rf public/build && npm install && npm run build:tailwind && npm run build:fontawesome && npm run dev"
},
"devDependencies": {
"#rollup/plugin-commonjs": "^16.0.0",
"#rollup/plugin-node-resolve": "^10.0.0",
"rollup": "^2.3.4",
"rollup-plugin-commonjs": "^10.1.0",
"rollup-plugin-css-only": "^3.1.0",
"rollup-plugin-livereload": "^2.0.0",
"rollup-plugin-node-polyfills": "^0.2.1",
"rollup-plugin-svelte": "^7.0.0",
"rollup-plugin-terser": "^7.0.0",
"svelte": "^3.0.0",
"webpack": "^5.11.1",
"webpack-cli": "^4.3.1"
},
"dependencies": {
"#fortawesome/fontawesome-free": "5.14.0",
"#popperjs/core": "2.5.1",
"#rollup/plugin-alias": "3.1.1",
"#rollup/plugin-replace": "^2.3.4",
"#tailwindcss/custom-forms": "0.2.1",
"body-parser": "^1.19.0",
"chart.js": "2.9.3",
"compression": "^1.7.4",
"express": "^4.17.1",
"express-session": "^1.17.1",
"fontawesome-svelte": "^2.0.1",
"node-fetch": "^2.6.1",
"node-sass": "^5.0.0",
"page": "^1.11.6",
"polka": "^0.5.2",
"rollup-plugin-scss": "^2.6.1",
"session-file-store": "^1.5.0",
"sirv": "^1.0.10",
"sirv-cli": "1.0.6",
"svelte-routing": "1.4.2",
"tailwindcss": "1.8.10"
}
}
I was looking for this answer, I think the #Romain Durand answer is the closest, I don't think we can add ssaper to an existing svelte project. I would have to initialize project in ssaper and use svelte.

Unable to acess kotlin js from javascript

I'm facing the issue where I'm not able to call any kotlin js function and getting 'something' is not defined.
I've tried compiling project with gradle but ended up following this tutorial and compiling with npm.
I attached my project here
EDIT: tested with maven and worked. However since maven is deprecated, I would like to use gradle or npm.
html code:
<body>
<script src="test.js"></script> //file generated in bin/bundle
<script>
(function() {
let a = new test.Test(); //test - module, Test - my class, error occurrs at this line
a.test(); //test - method in class Test
})()
</script>
</body>
however it always results in
Uncaught ReferenceError: test is not defined
package.json:
{
"name": "test",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"build": "shx rm -rf bin && webpack && shx rm -rf bin/build/kotlin-test*",
"test": "mocha bin/test"
},
"author": "",
"license": "ISC",
"dependencies": {
"kotlin": "^1.3.70"
},
"devDependencies": {
"#jetbrains/kotlin-webpack-plugin": "^3.0.2",
"kotlin-test": "^1.3.70",
"mocha": "^7.1.0",
"shx": "^0.3.2",
"webpack": "^4.42.0",
"webpack-cli": "^3.3.11"
},
"description": ""
}
webpack.config.js:
const KotlinWebpackPlugin = require('#jetbrains/kotlin-webpack-plugin');
module.exports = {
entry: 'test', // This tells webpack where to begin for bundling
resolve: {
modules: ['bin/build', 'node_modules'], // Webpack will use this to look for anything that is required
},
output: {
path: __dirname + '/bin/bundle', // This is where the bundle will go
filename: 'test.js', // The bundle will be called vectron.js
},
plugins: [
//Step one - Create a test build
new KotlinWebpackPlugin({
src: __dirname, // Build Everything
output: 'bin/test', // Output to bin/test
moduleName: 'test', // Will create vectron.js
moduleKind: 'commonjs', // Create commonjs modules
librariesAutoLookup: true, // Uses node_modules for libraries
packagesContents: [require('./package.json')], // Points to package.json for dependencies
}),
// Step two - Create a production build
new KotlinWebpackPlugin({
src: __dirname + '/src', // Build only what is in src
output: 'bin/build', // Output to bin/build
moduleName: 'test', // Create a file called vectron.js
moduleKind: 'commonjs', // Create commonjs modules
metaInfo: true, // Include .meta.js files
sourceMaps: true, // Include Source mappings
librariesAutoLookup: true, // Uses node_modules for libraries
packagesContents: [require('./package.json')], // Points to package.json for dependencies
}),
],
};
my class:
class Test {
fun test() {
println("test")
}
}
EDIT: npm compilation of test.js:
(function (_, Kotlin) {
'use strict';
var println = Kotlin.kotlin.io.println_s8jyv4$;
var Kind_CLASS = Kotlin.Kind.CLASS;
function Test() {
}
Test.prototype.test = function () {
println('test');
};
Test.$metadata$ = {
kind: Kind_CLASS,
simpleName: 'Test',
interfaces: []
};
_.Test = Test;
Kotlin.defineModule('test', _);
return _;
}(module.exports, require('kotlin'))); //error: module is not defined
//# sourceMappingURL=test.js.map
maven kotlin plugin output of test.js:
if (typeof kotlin === 'undefined') {
throw new Error("Error loading module 'test'. Its dependency 'kotlin' was not found. Please, check whether 'kotlin' is loaded prior to 'test'.");
}var test = function (_, Kotlin) {
'use strict';
var println = Kotlin.kotlin.io.println_s8jyv4$;
var Kind_CLASS = Kotlin.Kind.CLASS;
function Test() {
}
Test.prototype.test = function () {
println('test');
};
Test.$metadata$ = {
kind: Kind_CLASS,
simpleName: 'Test',
interfaces: []
};
_.Test = Test;
Kotlin.defineModule('test', _);
return _;
}(typeof test === 'undefined' ? {} : test, kotlin);
moduleKind was wrong in the build.gradle. Setting it to 'plain' fixed the issue.
Thank you

Svelte 3: Could not import modules when unit testing

I'm trying to test a Svelte component with Jest. This component works fine in the browser, but unit test fails with importing modules.
For example, when running Jest, import uuid from 'uuid' compiled as const { default: uuid } = require("uuid");, and calling uuid.v4() causes TypeError: Cannot read property 'v4' of undefined. When I use import * as uuid from 'uuid' or const uuid = require('uuid'), Jest unit test passes, but it doesn't work in the browser.
How can I deal with this issue? Any information would greatly help. Thank you.
package.json:
{
"name": "svelte-app",
"version": "1.0.0",
"scripts": {
"build": "rollup -c",
"dev": "rollup -c -w",
"start": "firebase serve --only hosting"
},
"devDependencies": {
"#rollup/plugin-json": "^4.0.0",
"#testing-library/jest-dom": "^5.1.1",
"#testing-library/svelte": "^1.11.0",
"bulma": "^0.8.0",
"eslint": "^6.7.0",
"eslint-config-standard": "^14.1.0",
"eslint-plugin-import": "^2.18.2",
"eslint-plugin-jest": "^23.0.4",
"eslint-plugin-node": "^10.0.0",
"eslint-plugin-promise": "^4.2.1",
"eslint-plugin-standard": "^4.0.1",
"eslint-plugin-svelte3": "^2.7.3",
"jest-transform-svelte": "^2.1.1",
"node-sass": "^4.13.1",
"rollup": "^1.12.0",
"rollup-jest": "0.0.2",
"rollup-plugin-commonjs": "^10.0.0",
"rollup-plugin-livereload": "^1.0.0",
"rollup-plugin-node-builtins": "^2.1.2",
"rollup-plugin-node-globals": "^1.4.0",
"rollup-plugin-node-resolve": "^5.2.0",
"rollup-plugin-svelte": "^5.0.3",
"rollup-plugin-terser": "^5.1.2",
"sirv-cli": "^0.4.5",
"svelma": "^0.3.2",
"svelte": "^3.18.2",
"svelte-preprocess": "^3.4.0"
},
"dependencies": {
"firebase": "^7.8.2"
},
"private": true
}
rollup.config.js
import json from '#rollup/plugin-json'
import commonjs from 'rollup-plugin-commonjs'
import builtins from 'rollup-plugin-node-builtins'
import globals from 'rollup-plugin-node-globals'
import livereload from 'rollup-plugin-livereload'
import resolve from 'rollup-plugin-node-resolve'
import svelte from 'rollup-plugin-svelte'
import { terser } from 'rollup-plugin-terser'
import preprocess from 'svelte-preprocess'
const production = !process.env.ROLLUP_WATCH
export default {
input: 'src/main.js',
output: {
sourcemap: true,
format: 'iife',
name: 'app',
file: 'public/build/bundle.js',
},
plugins: [
// https://github.com/rollup/plugins/tree/master/packages/json
json(),
svelte({
// enable run-time checks when not in production
dev: !production,
// we'll extract any component CSS out into
// a separate file — better for performance
css: css => {
css.write('public/build/bundle.css')
},
preprocess: preprocess(),
}),
// If you have external dependencies installed from
// npm, you'll most likely need these plugins. In
// some cases you'll need additional configuration —
// consult the documentation for details:
// https://github.com/rollup/rollup-plugin-commonjs
resolve({
browser: true,
dedupe: importee => importee === 'svelte' || importee.startsWith('svelte/'),
}),
commonjs(),
globals(),
builtins(),
// In dev mode, call `npm run start` once
// the bundle has been generated
!production && serve(),
// Watch the `public` directory and refresh the
// browser on changes when not in production
!production && livereload('public'),
// If we're building for production (npm run build
// instead of npm run dev), minify
production && terser(),
],
watch: {
clearScreen: false,
},
}
function serve () {
let started = false
return {
writeBundle () {
if (!started) {
started = true
require('child_process').spawn('npm', ['run', 'start'], {
stdio: ['ignore', 'inherit', 'inherit'],
shell: true,
})
}
},
}
}
jest.config.js
const sveltePreprocess = require('svelte-preprocess')
module.exports = {
displayName: { name: 'web', color: 'magentaBright' },
moduleFileExtensions: [
'js',
'json',
'svelte',
],
preset: 'rollup-jest',
transform: {
'\\.js$': 'rollup-jest',
'\\.svelte$': ['jest-transform-svelte', { preprocess: sveltePreprocess(), debug: true }],
},
setupFilesAfterEnv: ['#testing-library/jest-dom/extend-expect'],
}
It worked for me.
The issue seems like jest unable to resolve uuid while building the code at runtime.
Which is quite obvious because by default jest ignore node_modules packages.
I faced similar issues and resolved it. The approach is by configuration inform JEST that it has to include node_modules packages as well. In my project i used rollup-plugin-babel.
This is the babel plugin configuration
...
...
babel({
extensions: [ '.js', '.mjs', '.html', '.svelte' ],
runtimeHelpers: true,
exclude: [ 'node_modules/#babel/**', 'node_modules/core-js/**' ],
presets: [
[
'#babel/preset-env',
{
targets: '> 0.25%, not dead',
useBuiltIns: 'usage',
corejs: 3
}
]
]
})
And I've added babel-jest for transforming the jest.config.js
module.exports = {
preset: 'jest-puppeteer', //ignore the preset part, I used for puppeteer
transform: {
'^.+\\.js?$': require.resolve('babel-jest'),
"^.+\\.ts?$": "ts-jest" // this part is only required if you have typescript project
}
};
DO Not forget to install this packages like babel-jest, rollup-plugin-babel before using it.
I have been facing this same issue and have a work around by mocking the module in the test file and giving it a default key.
jest.mock('uuid', () => ({
default: {
v4: jest.fn(),
},
}))
Another way that seems to work is to destructure the import in the component file.
import { v4 as uuidv4 } from 'uuid'
Self answer:
Finally, I wrote a little preprocessor to replace import foo from 'foo' -> import * as foo from 'foo'
svelteJestPreprocessor.js
const svelteJestPreprocessor = () => ({
// replace `import foo from 'foo'` -> `import * as foo from 'foo'`
script: ({ content }) => ({
// process each line of code
code: content.split('\n').map(line =>
// pass: no import, import with {}, import svelte component
(!line.match(/\s*import/)) || (line.match(/{/)) || (line.match(/\.svelte/)) ? line
: line.replace(/import/, 'import * as'),
).join('\n'),
}),
})
module.exports = svelteJestPreprocessor
jest.config.js
const svelteJestPreprocessor = require('./svelteJestPreprocessor')
const sveltePreprocess = require('svelte-preprocess')
module.exports = {
moduleFileExtensions: [
'js',
'json',
'svelte',
],
preset: 'rollup-jest',
transform: {
'\\.js$': 'rollup-jest',
'\\.svelte$': ['jest-transform-svelte', {
preprocess: [
svelteJestPreprocessor(),
sveltePreprocess(),
],
}],
},
setupFilesAfterEnv: ['#testing-library/jest-dom/extend-expect'],
}
This is an unwanted workaround, but it works for now.

Uncaught ReferenceError: Main is not defined with webpack/react in Rails 4.2.4

I'm facing the error below from Chrome Canary even the webpack works. By the way "Main" is my component created with React 0.14.6
VM601:1 Uncaught ReferenceError: Main is not defined
(anonymous function) # VM601:1
mountComponents # react_ujs_mount.self-69e74f4….js?body=1:56
(anonymous function) # react_ujs_native.self-69da92a….js?body=1:9
fire # jquery.self-660adc5….js?body=1:3233
fireWith # jquery.self-660adc5….js?body=1:3363
ready # jquery.self-660adc5….js?body=1:3583
completed # jquery.self-660adc5….js?body=1:3618
Do you know if I need to install or set up something else?
Below, you can find installation and configuration that I have in my OS X Yosemite 10.10.5
Webpack
When I run the "webpack" inside my test app, i got the message below. Seems to be that it looks good.
ash: f9147c799d98d76fbd61
Version: webpack 1.12.14
Time: 624ms
Asset Size Chunks Chunk Names
bundle.js 5.76 kB 0 [emitted] main
+ 2 hidden modules
Babel installation
babel-core#6.7.4
babel-code-frame#6.7.4
babel-generator#6.7.2
babel-helpers#6.6.0
babel-messages#6.7.2
babel-register#6.7.2
babel-runtime#5.8.38
babel-template#6.7.0
babel-traverse#6.7.4
babel-types#6.7.2
babel-loader#6.2.4
babel-preset-es2015#6.6.0 extraneous
babel-preset-react#6.5.0 extraneous
babel-preset-stage-0#6.5.0 extraneous
During my babel installation, i got the message below.
npm ERR! peer dep missing: webpack#1 || ^2.1.0-beta, required by babel
loader#6.2.4
That appeared when I installed
webpack
babel-loader
babel-preset-es2015
babel-preset-react
babel-preset-stage-0
babel loader through
Another question. Do you know if this could be affecting the generation of the bundle?
.babelrc
{
"presets": ["es2015", "stage-0", "react"]
}
webpack.config.js
module.exports = {
entry: "./app/assets/frontend/main.jsx",
output: {
path: __dirname + "/app/assets/javascripts",
filename: "bundle.js"
},
resolve: {
extensions: ['','.js','.jsx']
},
module: {
loaders: [
{ test: /\.jsx$/, loader: "babel-loader" }
]
}
};
greet.jsx
export default class Greet extends React.Component {
render() {
return <h2>Hello World</h2>;
}
}
main.jsx
import Greet from './greet';
class Main extends React.Component {
render() {
return (
<Greet />
);
}
}
let documentReady = () => {
ReactDOM.render(
<Main />,
document.getElementById('react')
);
};
$(documentReady);
index.html.erb
<div id="react"/>
<%= react_component("Main") %>
package.json
{
"name": "twitter-clone",
"version": "1.0.0",
"description": "Twitter clone, written in React, Flux, and Rails",
"main": "index.js",
"directories": {
"test": "test"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Jose Alanya",
"license": "ISC",
"dependencies": {
"babel-core": "^6.7.4",
"babel-loader": "^6.2.4"
},
"devDependencies": {
"babel-core": "^6.7.4",
"babel-loader": "^6.2.4"
}
}
Thanks for your prompt answer.
You'll need to do few things to get the react-rails gem working with Webpack, you might be able to get it done by adding this line at the end of your Main.jsx
window.Main = Main;
However, I think the gem needs all files in a certain location if I remember correctly.
There is another gem that supports Webpack out of the box: react_on_rails
Do you have configured:
Rails.application.config.assets.precompile += %w( bundle.js)
in your assets initilizer file? Besides I think you need the "export default" statement for the Main component.

Categories

Resources