How can I move "index.html" when using webpack? - javascript

Generally,when will "index.html" be loaded using webpack?
I want to move "index.html" to in build/.
I'm in trouble over data flow from npm start using webpack.
In package.json, "start" is defined as:
"node ./node_modules/webpack-dev-server/bin/webpack-dev-server.js".
However,I couldn't find where it would jump from "webpack-dev-server.js".
I found two description about "index.html" in it as below:
.boolean("history-api-fallback").describe("history-api-fallback", "Fallback to /index.html for Single Page Applications.")
and
console.log("404s will fallback to %s", options.historyApiFallback.index || "/index.html");
when I try moving "index.html" to in build/, browser returned "Cannot Get error".
"index.html" and webpack.config.js are in same folder now.
./ index.html package.json src/ test/
../ build/ node_modules/ public/ style/
webpack.config.js

One way is to update the script (in package.json) so it copies index.html to the destination folder:
"scripts": {
"start": "node node_modules/.bin/webpack-dev-server --content-base src",
"build": "node node_modules/.bin/webpack && cp src/index.html build/index.html"
}
npm run build should now also copy src/index.html to build/index.html.

I'm not a webpack expert, but I faced the same issue, and was able to solve it using a plugin: html-webpack-plugin
First install it: npm install html-webpack-plugin --save-dev
Then edit your webpack.config.js:
var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
//Your config here (entry, module, resolve, etc.)
devServer: {
contentBase: './build' //Or any other path you build into
},
plugins: [
//other plugins if any
new HtmlWebpackPlugin({
template: './index.template.html', //your template file
filename: 'index.html',
inject: 'body'
})
]
};
This is going to copy your index.template.html to ./build/index.html and serve files from there.
It will also inject all assets at the bottom of the <body> tag.
You can further costumize this setup to fit your need of course, just refer to the plugin docs.

Related

how to make a file in src at webpack file

when i put "webpack" file in a new folder and extract it in new folder i go to the "src" file and then go to the terminal of "VSCODE" and write "npm install" after that "npm run build" so i can see every things in "src" file that copied in "dist" file , but my question is that : when i create a new folder in "src" and write "npm run build" in vscode , that new folder wont build in "dist" . in "dist" folder there is just "src" files . how can i put new folder that i have made in "src" , at "dist" file . thanks . i made a new folder in "src" and i cant see this file in "dist"
By default, webpack will use index.js file in src/index.js. This may vary depending on the webpack version.
Generally, its preferred to specify the entry files. Based on your question, I'm assuming you are trying to add additional files to webpack entry that would be parsed and build by webpack.
This is handled by defining additional entry in webpack.config.js
https://webpack.js.org/concepts/entry-points/
module.exports = {
...
entry: {
main: './src/index.js',
vendors: './src/vendors.js',
},
...
};
In the example above, webpack will generate two files in dist/.
dist/main.js
dist/vendors.js
Here is the question I am getting from this:
How can I configure my webpack config so that a new file created in a given src folder will be processed and moved to a given dist folder when running npm run build?
Solution:
For a new source file to be recognized by webpack, you will either need to create a new entry in your webpack.config.js or you will need to import some exported function from your new file into an existing entry.
Here is an example scenario:
I have a directory app containing: app/src/, app/dist/, app/webpack.config.js, app/src/index.js
And when I run npm run build, a file called index.bundle.js is generated in me app/dist folder
I now want a new script contact.bundle.js generated in my app/dist folder when I run npm run build
My existing webpack.cofig.js file looks something like this:
module.exports = {
entry: {
index: "./src/index.js",
},
output: {
filename: "[name].bundle.js",
path: path.resolve(__dirname, "dist")
},
}
But I want to modify it so now my src/contact.js is recognized by webpack and processed as dist/contact.bundle.js
So I update my webpack.config.js file as follows:
module.exports = {
entry: {
index: "./src/index.js",
contact: "./src/contact.js"
},
output: {
filename: "[name].bundle.js",
path: path.resolve(__dirname, "dist")
},
}
Please comment if the answer needs to be clarified any further.

Build index.html with webpack to use with dev server

Im using webpack for running my Three.js application with the following configuration in the webpack.config file:
module.exports = {
entry: `${__dirname}/src/tut15.js`,
output: {
path: __dirname + '/dist',
filename: 'index_bundle.js'
},
devtool: 'inline-source-map',
devServer: {
contentBase: path.join(__dirname, 'dist'),
compress: true,
port: 9000
},
plugins: [
new HtmlWebpackPlugin()
]
}
package.json
"scripts": {
"start": "webpack-dev-server --open",
"build": "webpack --config webpack.config.babel.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
With the HtmlWebpackPlugin it autogenerates the html for me. But since I want to create a custom html index file with some new tags this doesnt work for me. So I build the project
npm run-script build
and runs the index.html in the dist folder manually with my applied edits and everything works.
If I remove the HtmlWebpackPlugin from the webpack.config and build the project again and then run:
npm start
livereload works for my js files together with my new index.html with custom tags in the distfolder.
Questions:
It doesnt feels correct to create the changes in the dist folder. How can I generate a index.html straight from source? I guess that might solve all my problems being able to run dev server with a custom index.html
Or is it possible to get some livereload for the build as well?
after I have built my project it generates index.html and index.bundle in my distfolder. If I remove the index.bundle the project works anyway. What exactly does index.bundle do?
What is the best approach or do I need to build my project each time Im doing an update in my index file?
Thanks!
For questions regarding custom index.html and hot-reloading at least.
The plugin has some config you can add for templating.
new HtmlWebPackPlugin({
filename: 'index.html',
template: './public/index.html',
}),

How to explicitly share files part of a NPM package? [duplicate]

I would like to publish a npm package that contains my source as well as distribution files. My GitHub repository contains src folder which contains JavaScript source files. The build process generates dist folder that contains the distribution files. Of course, the dist folder is not checked into the GitHub repository.
How do I publish a npm package in a way that when someone does npm install, they get src as well as dist folder? Currently when I run npm publish from my Git repository, it results in only the src folder being published.
My package.json file looks like this:
{
"name": "join-js",
"version": "0.0.1",
"homepage": "https://github.com/archfirst/joinjs",
"repository": {
"type": "git",
"url": "https://github.com/archfirst/joinjs.git"
},
"main": "dist/index.js",
"scripts": {
"test": "gulp",
"build": "gulp build",
"prepublish": "npm run build"
},
"dependencies": {
...
},
"devDependencies": {
...
}
}
When you npm publish, if you don't have an .npmignore file, npm will use your .gitignore file (in your case you excluded the dist folder).
To solve your problem, create a .npmignore file based on your .gitignore file, without ignoring the dist folder.
Source: Keeping files out of your Package
Take a look at the "files" field of package.json file:
package.json, files
From the documentation:
The "files" field is an array of files to include in your project. If you name a folder in the array, then it will also include the files inside that folder. (Unless they would be ignored by another rule.)
Minimal example of how to use data files from a script
Another common use case is to have data files that your scripts need to use.
This can be done easily by using the techniques mentioned at: How can I get the path of a module I have loaded via require that is *not* mine (i.e. in some node_module)
The full example can be found at:
Source: cirosantilli/linux-kernel-module-cheat/npm/data-files/
Published: cirosantilli-data-files
With this setup, the file mydata.txt gets put into node_modules/cirosantilli-data-files/mydata.txt after installation, because we added it to our files: entry of package.json.
Our function myfunc can then find that file and use its contents by using require.resolve. It also just works on the executable ./cirosantilli-data-files of course.
package.json
{
"bin": {
"cirosantilli-data-files": "cirosantilli-data-files"
},
"license": "MIT",
"files": [
"cirosantilli-data-files",
"mydata.txt",
"index.js"
],
"name": "cirosantilli-data-files",
"repository": "cirosantilli/linux-kernel-module-cheat",
"version": "0.1.0"
}
mydata.txt
hello world
index.js
const fs = require('fs');
const path = require('path');
function myfunc() {
const package_path = path.dirname(require.resolve(
path.join('cirosantilli-data-files', 'package.json')));
return fs.readFileSync(path.join(package_path, 'mydata.txt'), 'utf-8');
}
exports.myfunc = myfunc;
cirosantilli-data-files
#!/usr/bin/env node
const cirosantilli_data_files = require('cirosantilli-data-files');
console.log(cirosantilli_data_files.myfunc());
The is-installed-globally package is then useful if you want to generate relative paths to the distributed files depending if they are installed locally or globally: How to tell if an npm package was installed globally or locally
just don't mention src and dist inside the .npmignore file to get the scr and dist inside the node_modules ... that's it
Another point is if there is a .gitignore file, and .npmignore is missing, .gitignore's contents will be used instead.

Webpack 4 ./src directory not found

I am trying to split the webpack config to base, dev and prod configs. Here is my entry section of webpack.base.babel.js file
module.exports = options => ({
mode: options.mode,
entry: options.entry,
output: Object.assign(
{
// Compile into js/build.js
path: path.resolve(process.cwd(), 'build'),
publicPath: '/',
},
options.output,
), // Merge with env dependent settings
Here is the entry section of webpackdev.babel.js file:
module.exports = require('./webpack.base.babel')({
mode: 'development',
// Add hot reloading in development
entry: [
require.resolve('react-app-polyfill/ie11'),
'webpack-hot-middleware/client?reload=true',
path.join(process.cwd(), 'app/app.js'),
],
// Don't use hashes in dev mode for better performance
output: {
filename: '[name].js',
chunkFilename: '[name].chunk.js',
},
My start script in package.json looks like: "start": "webpack-dev-server --mode development"
But when I run npm start I get the bellow error:
ERROR in Entry module not found: Error: Can't resolve './src'
. I am on Windows 10. Could anybody explain what's wrong with my webpack config. I am specifying the entry file as app/app.js but still webpack is defaulting to src/index.js.
Thanks in advance.
Just hand in your webpack config explicitely by changing your npm start script to:
"start": "webpack-dev-server --config webpackdev.babel.js"
Webpack searches for webpack.config.js in the root folder automatically. Starting with v4, Webpack also claims to be a zero config bundler, so it will use opinionated defaults, if no config can be located. E.g.:
entry point of your project is assumed to be src/index
output will be put in dist/main.js
production mode will minify and do optimizations
Your config seems to be right, but Webpack can't find it and assumes the default entry, thus your error Can't resolve './src'.

Webpack: How to compile, write on disk and serve static content (js/css) using webpack-dev-server

I want to build my js/css code, write it on disk and serve it using webpack-dev-server in a single command. I don't want to set-up another server for production mode. How do we do it? Sharing my webpack.config.js file content below:
module.exports = {
watch: true,
entry: [
'./src/index.js'
],
output: {
path: __dirname +'/dist/',
publicPath: '/dist/',
filename: 'bundle.js'
},
module: {
loaders: [
{
exclude:/(node_modules)/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}
]
},
devServer: {
historyApiFallback: true,
contentBase: './'
}
};
Please find the start script used in package.json below:
"start": "webpack-dev-server --progress --colors"
I am running "npm run start". Please help.
New webpack-dev-server is released, and it supports writeToDisk option.
devServer: {
writeToDisk: true
}
With webpack-dev-server v4.0.0+, devMiddleware is used:
devServer: {
devMiddleware: {
writeToDisk: true
}
}
webpack-dev-server uses a "virtual" Express server in conjunction with Sock.js to emulate a server running on your machine. Regarding compilation, webpack-dev-server does recompile the bundle whenever it detects code changes. This recompilation is served from memory, however, as opposed to the project's build directory (or, in your case, the dist directory). From the docs:
Using this configuration, webpack-dev-server will serve the static files in your build folder. It’ll watch your source files, and recompile the bundle whenever they are changed.
Regarding writing to your disk, webpack-dev-server does not do this. This is partially addressed by what's been written above. Additionally, note the following, also from the Webpack docs:
This modified bundle is served from memory at the relative path specified in publicPath (see API). It will not be written to your configured output directory. Where a bundle already exists at the same URL path, the bundle in memory takes precedence (by default).
To write to your disk, use the ordinary webpack module. Of course, as your question hints at, manual recompilation after every change is tedious. To address that chore, include the watch flag. From the Terminal, you could execute the command:
$ webpack --watch
I prefer to delegate this to an NPM script, however. Note that the -w flag below is equivalent to writing --watch.
// NPM `scripts` field:
"watch": "webpack -w"
If you want to run webpack-dev-server while also having your changes get recompiled and written to your output directory, you can add an additional NPM script like so:
"scripts": {
"serve": "npm run watch && npm run start",
"start": "webpack-dev-server --progress --colors",
"watch": "webpack -w"
}
Then, in your Terminal, just execute $ npm run serve to accomplish this.
If you're interested in the added convenience of automatic reload, you can do so by defining the following within the plugins field of your Webpack config file:
new webpack.HotModuleReplacementPlugin()
Note: This will likely require additional configuration settings for Babel. If I were you, I would take out the query field from your babel loader and, instead, delegate your Babel configuration to an external .babelrc file. A good one to use that is compatible with hot reloading might look like this:
{
"presets": ["env", "es2015", "react"],
"plugins": ["react-hot-loader/babel"]
}
On a side note, I've created a boilerplate repo for easily starting out projects with my desired structure. The Webpack configuration may of interest to, specifically. In particular, it employs Webpack 2 and includes other build tools like Babel (for transpilation), ESLint (syntax checker) as well as support for CSS/Sass and a variety of other file formats.
You can change your start script definition to this:
"start": "webpack --watch & webpack-dev-server --inline --progress --colors".
This sends the webpack watch-and-rebuild process to the background so that you can also hot-reload your modified modules as you change them with webpack-dev-server.
EDIT:
Either of these plugins may do what you want:
https://github.com/gajus/write-file-webpack-plugin
https://github.com/FormidableLabs/webpack-disk-plugin
webpack-dev-server serve files from memory, you can replace webpack-dev-server with webpack-simple-serve, it use webpack's watch feature, write the compiled files to disk and use serve-handler to serve.

Categories