Require file with a variable in React JS
Asked Answered
M

3

11

I'm trying to require a file with a variable in the path. Something like

const langCode = this.props.langCode; // en
let languageFile = require('../common/languages/' + langCode);

Where langCode can be fr, en, de, nl. Thus what I'm trying to get is for example

require('../common/languages/en'); 

When I type it without variable at the end, thus require('../common/languages/en'); it works good. But when I try with require('../common/languages/' + langCode); it won't work, doesn't matter that the value of the langCode is also en.

I get next error :

bundle.js:1 Uncaught Error: Cannot find module '../common/languages/en'

UPDATE

    'use strict';

var gulp = require('gulp');
var connect = require('gulp-connect');
var open = require('gulp-open');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var concat = require('gulp-concat');
var babelify = require('babelify');
var sass = require('gulp-sass');
var merge = require('merge-stream'); // Merge all styles (css, sass and less) in one big bundle
var lint = require("gulp-eslint");

var config = {
    port: 8001,
    devBaseUrl: 'http://localhost',
    paths: {
        html: "./src/*.html",
        externals: "./src/assets/externals/*.js",
        js: "./src/**/*.js",
        images: './src/assets/images/**/*',
        fonts: './src/assets/css/fonts/*',
        css: [
            "./src/assets/css/*.css",
            "./node_modules/toastr/package/toastr.css"
        ],
        sass: './src/assets/css/*.scss',
        dist: "./dist",
        mainJS: "./src/main.js"
    }
};


gulp.task('connect', ['watch'], function () {
    connect.server({
        root: ['dist'],
        port: config.port,
        base: config.devBaseUrl,
        livereload: true,
        fallback: './dist/index.html'
    })
});

gulp.task('open', ['connect'], function () {
    gulp.src('dist/index.html')
        .pipe(open({uri: config.devBaseUrl + ":" + config.port + "/"}));
});


gulp.task('html', function () {
    gulp.src(config.paths.html)
        .pipe(gulp.dest(config.paths.dist))
        .pipe(connect.reload());
});


gulp.task('externals', function () {
    gulp.src(config.paths.externals)
        .on('error', console.error.bind(console))
        .pipe(concat('external.js'))
        .pipe(gulp.dest(config.paths.dist + '/externals'))
        .pipe(connect.reload());
});


gulp.task('js', function () {
    browserify(config.paths.mainJS)
        .transform('babelify', {presets: ['es2015', 'react']})
        .bundle()
        .on('error', console.error.bind(console))
        .pipe(source('bundle.js'))
        .pipe(gulp.dest(config.paths.dist + '/scripts'))
        .pipe(connect.reload());
});


gulp.task('images', function () {
    gulp.src(config.paths.images)
        .pipe(gulp.dest(config.paths.dist + '/images'));
});


gulp.task('styles', function () {
    var cssStyles = gulp.src(config.paths.css)
        .pipe(concat('styles.css'));

    var sassStyles = gulp.src(config.paths.sass)
        .pipe(sass())
        .pipe(concat('styles.scss'));

    var mergedStream = merge(cssStyles, sassStyles)
        .pipe(concat('bundle.css'))
        .pipe(gulp.dest(config.paths.dist + '/css'))
        .pipe(connect.reload());

    return mergedStream;
});

gulp.task('fonts', function () {
    gulp.src(config.paths.fonts)
        .pipe(gulp.dest(config.paths.dist + '/css/fonts'));
});

gulp.task('lint', function () {
    return gulp.src(config.paths.js)
        .pipe(lint())
        .pipe(lint.format());
});


gulp.task('watch', function () {
    gulp.watch(config.paths.html, ['html']);
    gulp.watch(config.paths.js, ['js', 'lint']);
    gulp.watch(config.paths.externals, ['externals', 'lint']);
    gulp.watch([config.paths.css, config.paths.sass], ['styles']);
    gulp.watch(config.paths.images, ['images']);
});

gulp.task('default', ['html', 'js', 'styles', 'externals', 'images', 'fonts', 'lint', 'open', 'watch']);
Meeting answered 14/7, 2016 at 12:34 Comment(2)
Can you share the gulp code you are running?Benedicto
I updated my question.Meeting
S
14

Most of JS bundlers cannot handle dynamic require mechanism. Try to load all languages and switch them in runtime

let languages = {
    en:  require('../common/languages/en'),
    ru: require('../common/languages/ru'),
    de: require('../common/languages/de')
}
const langCode = this.props.langCode; // en
let languageFile = languages[langCode];
Sachsse answered 15/7, 2016 at 13:42 Comment(1)
it's perfect solution for me. I use this solution in React NativeHalsy
C
2

Are you using webpack as your bundler?

If so you need to be aware of it's dynamic requires mechanism.

Here is an issue that discusses it.

Catfish answered 14/7, 2016 at 12:38 Comment(3)
@Meeting that's not a bundler, how are you doing the bundling if not webpack? is it browserify?Lifeordeath
@Lifeordeath Yes. With browserify.Meeting
similar case with webpack then, as what ctrlplusb explainsLifeordeath
D
0

in your express.js server, set up a static directory containing any static.file:

const express = require('express')
const app = express()
app.use(express.static(path.join(__dirname, '../path_to/..', staticImages)))

react native component:

return <Image source={{ uri: `http://192.168.0.1:3345/${'staticImage.jpg'}`}} />
Disingenuous answered 18/3, 2022 at 4:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.