I have lots of .js files to import in Vue components in my project. Some of these JavaScript files are meant to be used in development mode and they won't be included in production but I am not allowed to delete these files in project. For example;
There are two JavaScript files called authDev.js and authProd.js. Their usage is basically the same but their content are different from each other. Inside of these JavaScript files there are functions and I export them to be able to import in several Vue components.
The first question, If I dynamically export or import them, will webpack include these files when I run npm run build? In other words, let's say I created a JavaScript file but I didn't export it, so I didn't import it to anywhere either. Does webpack understand that this JavaScript file is not used in anywhere of these Vue project and discard it when it builds my project to production? Or does it include every single file that existed in the project?
The second question, is there a way to tell the webpack that those JavaScript files will not be included in dist folder these will... I mean, can I specify files for development and production?
First I thought I could import or export them based on a condition but when I try to put my imports in if statements, it gives me an error and says "imports must be at the top level". So I tried to export them dynamically but couldn't do it either.
Then I try to remove specific blocks of codes in files. There are packages and plugins to remove every console outputs from Vue projects but I couldn't find anything to remove or discard specific lines of codes.
At last, I decided to took a way to include and exclude specific files. Is there a way to do it? If it is, how do I do that? Thanks in advance.
THE SOLUTION (EDITED)
For a quick test, I created two .js files called auth-development.js and auth-production.js in src/assets/js/filename.js location. Here are the contents of them;
auth-production.js
export const auth = {
authLink: "http://production.authlink/something/v1/",
authText: "Production Mode"
}
auth-development.js
export const auth = {
authLink: "http://localhost:8080/something/v1/",
authText: "Development Mode"
}
Then I modified my webpack config which is in the vue.config.js file;
const path = require('path');
module.exports = {
configureWebpack: {
resolve: {
alias: {
'conditionalAuth': path.resolve(__dirname, `src/assets/js/auth-${process.env.NODE_ENV}.js`)
}
}
}
}
Vue was giving "path is undefined" error, I added the top part of the code to handle that error. I used process.env.NODE_ENV to get the words development and production to add the end of my javascript files so that I can define their path.
Then I dynamically imported this conditionalAuth to a test component called "HelloWorld" as follows;
<script>
import * as auth from 'conditionalAuth';
export default {
name: 'HelloWorld',
data(){
return {
auth: auth
}
}
}
</script>
And I used them like this;
<template>
<div>
<p>You are in the {{ auth.auth.authText}}</p>
<p>{{ auth.auth.authLink }}</p>
</div>
</template>
In this way when I npm run serve it imports auth-development.js but if I npm run build and try the index.html in the dist folder on a live server, it only imports the auth-production.js.
At last, when I check the final build, auth-development.js is not built for my dist version of the project. It only imports the production javascript file in the chunk.
Assuming the file names are: auth-development.js and auth-production.js, you can use webpack alias to import file according to environment.
resolve: {
alias: {
'conditionalAuth': path.resolve(__dirname, `path/to/js/auth-${process.env.NODE_ENV}.js`)
},
extensions: ['.js', '.vue', '.json']
}
then you should be able to import the desired file like:
import * as auth from 'conditionalAuth';
Related
I'm trying to import an HTML file to render it inside of a react component.
I'm getting the following typescript error:
Cannot find module './privacy_policy.html' or its corresponding type declarations.ts(2307)
What could I do to get rid of it (other then use #ts-ignore)?
You can consider declaring a *.html module in a file named custom.d.ts in your project (at the same place where you defined your tsconfig.json).
For example, I've used this configuration on a web application (essentially Vanilla JS + TS for newer code) bundled with webpack, to handle import of types of file different from JS(x) or TS(x).
The alternative, as you said, is to use #ts-ignore approach when it's for a single specific need.
Note for this approach: in my case, the TypeScript transpilation is handled via webpack (with the babel-loader), and the imports as well are handled via webpack (via specific loaders, which for HTML is html-loader).
The html-loader lets you import a HTML file as it was a string in your TypeScript / JavaScript file.
Normally, if you use the ReactApp template, you should have the html-loader included in the build pipeline (which runs webpack behind the scene), so you should be able to use it.
Here is how it looks my custom.d.ts file:
/*
* Tells the IntelliSense to allow import of the following file extensions in TypeScript.
* Current Webpack config for these files doesn't embed their content, but provides the file path inside the Webpack bundle.
*/
declare module "*.svg" {
const content: string;
export default content;
}
declare module "*.png" {
const content: string;
export default content;
}
declare module "*.html" {
const content: string;
export default content;
}
You have to transform your HTML code to JSX (or TSX if you are using Typescript). Check online, there are few tools that might help you !
Then you will be able to import your HTML (converted to JSX) into your script:
import PrivacyPolicy from 'privacy-policy.jsx'
return (
<PrivacyPolicy />
)
I'm very new to nuxt and javascript and I'm trying to figure out how to use my app's dependencies client-side. I have them listed in my nuxt.config.js and installed with npm. I also have a file in the /plugins directory that imports them (not sure if this is good or not). Here is where I run into trouble: I have two scripts located in my /static directory that need to take advantage of my npm packages. Putting an import statement in those scripts causes an error. Importing the packages in the script section of the page vue file also doesn't work. How can I use npm packages in scripts that are included in pages client-side?
Can you provide a more information, about which kind of error is happening and which kind of packages did you try to install?
In this example I am going to show you how I included in my nuxt project npm package vuelidate
after installing vuelidate:
add to nuxt.config.js
plugins: [
{ src: "~/plugins/vuelidate", mode: "client" },
],
create vuelidate.js file in my plugin folder (plugin/vuelidate.js)
import Vue from 'vue'
import Vuelidate from 'vuelidate'
Vue.use(Vuelidate);
after that I can use vuelidate in my .vue components (no always necessary to import something because in our 2 stage Vue.use(Vuelidate) we already installed vuelidate globally)
<script>
import { required, minLength } from "vuelidate/lib/validators";
export default {
name: "OrderByLinkForm",
components: {},
...
};
</script>
I am trying to use create-react-app to create a simple web-app. I have moved the pages and components into separate directories under src labeled pages and components. I would like to change/add the entry point for index.js from src/index.js to src/pages/index.js. Another option would be to keep index.js in src/ and import from pages and component directories. Can someone help me to find how i can change the entry point path?
I can't seem to find the location of the default html-webpack-plugin config file.
Here is what I would like the structure to be:
(in src)
...
pages/
- App.js
- Home.js
components/
- Filter.js
serviceWorker.js
I used react-rewired to achieve something like this:
https://github.com/timarney/react-app-rewired/issues/189
in my config-overrides.js
console.log("#######################");
console.log("# using react-rewired #");
console.log("#######################");
module.exports = {
// The Webpack config to use when compiling your react app for development or production.
webpack: function(config, env) {
// ...add your webpack config
console.log("###########");
console.log("# webpack #");
console.log("###########");
console.log({config, env});
if (env === 'development') {
config.entry = config.entry.replace(new RegExp("index.ts$"), 'runApp.tsx');
console.log("entry point changed:", config.entry);
}
return config;
},
}
I needed to run on a different file but only when running the development server
the link above has the full solution
Try using npm run eject.
this will take all script from node_module/react-script in the project folder. There you will be able to access webpack.config.js file in config folder. you can search for html-webpack-plugin and get the access point.
I have added my access point to config/paths.js and used as default access point which worked for me.
NOTE: make sure you don't have any different configuration setting as it gets very difficult to manage, if environment setup changes or doesn't match.
After I change all file from jsx to tsx, I get this error:
./src/components/index.js Module not found: Can't resolve './Header'
in '/Users/khuongpham/WebFrontEnd/home/src/components'
You need to do correct Webpack configuration, add .tsx under resolve property:
....
resolve: {
extensions: ['.js', '.jsx', '.tsx']
}
....
FYI: It seems if you want to integrate TypeScript into React, you still need to install some libraries and development dependencies to let Webpack and React play well.
If you changed all files from jsx to tsx then what is the reason for leaving index.js?
Why don't you change it to index.tsx or at least index.ts?
As far as I'm concerned, ts and js can't directly interact with each other.
If you are writting a ts or tsx file and you want to import a js file (or js library) you will need something called type declaration file which, most of the time, can be found here: https://microsoft.github.io/TypeSearch/
In your case, you are trying to import typescript from javascript and that is probably the problem. Changing index.js to index.ts may help.
I have a Webpack angular 2 application and I have a date picker module dependency with a library using Moment. The thing is that if I don't import it like :
<script src="./../node_modules/moment/min/moment.min.js"></script>
a moment is not defined error is raised if I want to use it. I tried to import moment with require but it's not taken into account.
The problem is that the script src tag works in local but in the webpack builded version we need to deploy the path with node_modules doesn't exist anymore. Is there a way to do it other than hard paste moment.min.js in a lib folder?
Add the following code in webpack.conf.js:
resolve: {
alias: {
'moment': 'moment/min/moment.min'
}
}
Now you can simply do, require('moment') in your js file.
Note: By default webpack searches the file in node_modules folder. You can instruct it to look into specific places using modules property of resolve object.
The resulting code would look like:
resolve: {
modules: ['lib/','some_folder/node_modules'...],
alias: {
'moment': 'moment/min/moment.min'
}
}