How to import HTML files in dist folder? - html

In my development environment I give
res.sendFile(path.resolve(__dirname,'../Views/setpwd.html');
and it is working well in development environment.
But in production Views are not moving to dist folder even though I have added html loader in webpack. Could you guys please help me on this?
Thanks in advance
## Webpack config##
var path = require('path');
var webpack=require('webpack');
var nodeExternals = require('webpack-node-externals');
module.exports = {
entry: './src/app.js',
output: {
path: path.resolve(__dirname,'dist'),
filename: 'src/server.js',
},
target: 'node',
externals: [nodeExternals()],
module: {
loaders: [{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader'}],
loaders: [
{ test: /\.(html)$/, loader: "file" }
]
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
},
output: {
comments: false,
},
}),
]
}
deVdependencies
"devDependencies": {
"babel-core": "^6.24.1",
"babel-loader": "^7.0.0",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-env": "^1.5.1",
"babel-preset-es2015": "^6.24.1",
"file-loader": "^0.11.2",
"webpack": "^2.6.1",
"webpack-node-externals": "^1.6.0"
},

If I'm understanding this correctly, you want to copy over the HTML files in ../Views/*.html to a dist/ directory using webpack. If so, then you need to use the copy-webpack-plugin:
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../path/to/views/directory'),
to: path.resolve(__dirname, '../path/to/dist')
ignore: ['.*']
}
])

Related

Webpack images path in build

webpack break my image paths
This is my code
and it is error
Refused to apply style from 'http://localhost:8080/style.css' because
its MIME type ('text/html') is not a supported stylesheet MIME type,
and strict MIME checking is enabled.
webpack.config.js
i use file-loader but this not help me
const path = require('path');
const HtmlWebpackPlugin = require('*html-webpack-plugin*');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const devServer = (isDev) => !isDev ? {} : {
devServer: {
open: true,
port: 8080,
static: {
watch: true,
directory: '**/*.html',
},
},
};
module.exports = ({development}) => ({
mode: development ? 'development' : 'production',
devtool: development ? 'inline-source-map' : false,
entry: {
app:'./src/index.js',
main: './src/shelter/pages/main/index.js',
pets: './src/shelter/pages/pets/index.js'
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].[contenthash].js',
assetModuleFilename: 'assets/images/[hash][ext]',
},
module: {
rules: [
{
test: /\.(?:ico|gif|png|jpg|jpeg|svg|html|text)$/i,
use: ['file-loader']
},
{
test: /\.(woff(2)?|eot|ttf|otf)$/i,
type: 'asset/resource',
},
{
test: /\.css$/i,
use: [MiniCssExtractPlugin.loader, 'css-loader'],
},
{
test: /\.s[ac]ss$/i,
use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader']
},
{
loader: 'file-loader',
options: {
publicPath: '/../../image',
name: `assets/images/[hash].[ext]`,
}
},
]
},
resolve: {
extensions: ['.ts', '.js']
},
plugins: [
new MiniCssExtractPlugin({ filename: '[name].[contenthash].css' }),
new HtmlWebpackPlugin({ template: './src/shelter/pages/main/index.html' }),
],
...devServer(development)
});
package.json
it is my package.json
{
"name": "webpack",
"scripts": {
"build": "webpack",
"dev": "webpack server --env development"
},
"devDependencies": {
"css-loader": "^6.7.1",
"html-webpack-plugin": "^5.5.0",
"mini-css-extract-plugin": "^2.6.0",
"sass": "^1.50.0",
"sass-loader": "^12.6.0",
"webpack": "^5.72.0",
"webpack-cli": "^4.9.2"
},
"dependencies": {
"file-loader": "^6.2.0",
"resolve-url-loader": "^5.0.0",
"webpack-dev-server": "^4.8.1"
}
}
My structure fails enter image description here

Webpack, babelrc dynamic import not working

I spent quite some time trying to figure this out myself but here I am, with no more options to consider than to reach out to the community for some guidance.
I am trying to do something very simple in principle, dynamically import a component with WebPack, using ES6 modules and babelrc.
I have the following app architecture:
-root
-- root/.webpack.dev.js
-- root/.webpack.prod.js
-- root/.babelrc
-- root/package.json
-- root/node_modules/
-- root/dist/
-- root/src/
--- root/src/index.js
--- root/src/modules/
--- root/src/modules/module1.js
--- root/src/modules/module2.js
--- root/src/modules/module3.js
--- root/src/modules/module4.js
--- root/src/modules/module5.js
In my module1.js (not the real name) I am using the following code to dynamically import module2.js:
async function load(configObject) {
const {
init,
requestPermissions
} = await import( /* webpackChunkName: "chunkname" */ `./module2.js`)
init(configObject)
_namespace.requestPermissions = requestPermissions;
}
My .babelrc file:
{
"presets": [
["#babel/preset-env", {
"targets": "> 0.25%, not dead"
}]
],
"plugins": ["#babel/plugin-syntax-dynamic-import",
["#babel/plugin-transform-runtime",
{
"regenerator": true
}
],
],
"comments": true
}
// "#babel/preset-env"
My Webpack config:
const path = require('path');
const webpack = require('webpack')
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin
const WorkboxPlugin = require('workbox-webpack-plugin');
const {
InjectManifest
} = require('workbox-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
module.exports = {
entry: {
lib: "./src/index.js"
},
mode: 'development',
module: {
rules: [{
test: /\.js$/,
use: [{
loader: "babel-loader"
}],
exclude: /node_modules/
}]
},
optimization: {
minimizer: [new TerserPlugin({
test: /\.js(\?.*)?$/i,
parallel: true,
cache: true,
terserOptions: {
ecma: 8,
warnings: false,
parse: {
ecma: 8,
},
compress: {
warnings: false,
comparisons: false,
},
mangle: {
safari10: true,
},
module: false,
output: {
ecma: 5,
comments: false,
ascii_only: true,
},
toplevel: false,
nameCache: null,
ie8: false,
keep_classnames: undefined,
keep_fnames: false,
safari10: false,
},
})],
},
output: {
filename: '[name].js',
chunkFilename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
publicPath: "/"
},
devServer: {
contentBase: "dist",
compress: true,
stats: {
colors: true
},
overlay: true
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('development'),
'API_URL': JSON.stringify('ENDPOINT')
}
}),
new BundleAnalyzerPlugin({
generateStatsFile: true
}),
new WorkboxPlugin.GenerateSW({
"swDest": "firebase-messaging-sw.js",
}),
new InjectManifest({
"swSrc": path.join('src', 'firebase-messaging-sw.js')
})
]
};
My package.json:
{
"name": "refactor",
"version": "1.0.0",
"description": "",
"main": "backuprefacto.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "NODE_ENV=production webpack --config=webpack.prod.js",
"build:dev": "webpack --config=webpack.dev.js",
"start": "webpack-dev-server --config=webpack.dev.js"
},
"keywords": [],
"private": true,
"license": "ISC",
"devDependencies": {
"#babel/plugin-syntax-dynamic-import": "^7.2.0",
"#babel/preset-env": "^7.5.5",
"babel-loader": "^8.0.6",
"babel-minify": "^0.5.1",
"babel-minify-webpack-plugin": "^0.3.1",
"babel-plugin-syntax-dynamic-import": "^6.18.0",
"terser-webpack-plugin": "^1.4.1",
"uglifyjs-webpack-plugin": "^2.2.0",
"webpack": "^4.39.2",
"webpack-bundle-analyzer": "^3.4.1",
"webpack-cli": "^3.3.7",
"webpack-dev-server": "^3.8.0",
"workbox-webpack-plugin": "^4.3.1"
},
"dependencies": {
"#babel/core": "^7.5.5",
"#babel/plugin-transform-runtime": "^7.5.5",
"#babel/runtime": "^7.5.5",
"firebase": "^6.4.0",
"save": "^2.4.0"
}
}
I have checked all my modules, none of them expect for module1.js are calling module2.js.
I have also explored the option of webpack comments being deleted by babel and therefore added a comments: true to make sure the webpackChunkName is not being deleted but in the end, the only thing that gets built is my lib.js, not the lib.bundle.js that I expect.
I have also tried to remove all the TerserPlugin bit to check if that could have the same impact but nothing changed there.
In the need, what I am looking for is simply to have the module2.js loaded whenever it is invoked, and I therefore expect a new network request to materialise this.
Well, it turns out that if you want to use dynamic imports you need to make sure first that you are not importing at all the module at the top....
In module1.js I was importing twice, once at the top, the "regular way", once the dynamic way which was obviously leading to module2.js being consistently loaded.
I resolve my problem by modify .babelrc, modules: false
["#babel/preset-env", {
"loose": true,
"useBuiltIns": "usage",
"corejs": 3,
"modules": false
}],

Add assets folder in mern io

i am using mern.io my web pack config is looks like :
var webpack = require('webpack');
var cssnext = require('postcss-cssnext');
var postcssFocus = require('postcss-focus');
var postcssReporter = require('postcss-reporter');
module.exports = {
devtool: 'cheap-module-eval-source-map',
entry: {
app: [
'eventsource-polyfill',
'webpack-hot-middleware/client',
'webpack/hot/only-dev-server',
'react-hot-loader/patch',
'./client/index.js',
],
vendor: [
'react',
'react-dom',
],
},
output: {
path: __dirname,
filename: 'app.js',
publicPath: 'http://0.0.0.0:8888/',
},
resolve: {
extensions: ['', '.js', '.jsx'],
modules: [
'client',
'node_modules',
],
},
module: {
loaders: [
{
test: /\.css$/,
exclude: /node_modules/,
loader: 'style-loader!css-loader?localIdentName=[name]__[local]__[hash:base64:5]&modules&importLoaders=1&sourceMap!postcss-loader',
}
, {
test: /\.css$/,
include: /node_modules/ ,
loaders: ['style-loader', 'css-loader'],
}
, {
test: /\.jsx*$/,
exclude: [/node_modules/, /.+\.config.js/],
loader: 'babel',
}, {
test: /\.(jpe?g|gif|png|svg)$/i,
loader: 'url-loader?limit=10000',
}, {
test: /\.json$/,
loader: 'json-loader',
},
{ test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "url-loader?limit=1&minetype=application/font-woff" },
{ test: /\.(ttf|eot)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "url-loader?limit=1&minetype=application/font-woff" },
{ test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'url-loader?limit=1' }
],
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks: Infinity,
filename: 'vendor.js',
}),
new webpack.DefinePlugin({
'process.env': {
CLIENT: JSON.stringify(true),
'NODE_ENV': JSON.stringify('development'),
}
}),
],
postcss: () => [
postcssFocus(),
cssnext({
browsers: ['last 2 versions', 'IE > 10'],
}),
postcssReporter({
clearMessages: true,
}),
],
};
i would like to add a custom css file which resides in : /public/assets/css/custom.css; Then what would be my configurations?
i can import css file in node_modules eg : require('rc-slider/assets/index.css');
as it says in the config :
{
test: /\.css$/,
include: /node_modules/ ,
loaders: ['style-loader', 'css-loader'],
}
i have replicated the entry with :
{
test: /\.css$/,
include: /public/ ,
loaders: ['style-loader', 'css-loader'],
}
but not working
There can be two approach to handle this situation.
1.
You can use the following to add public folder to serve static files.
app.use(express.static('public'));
And then you can add the file in the html if you are using server side rendering.
2.
You can put this file on client side and simply import the file at the entry point of webpack on client side.
And webpack will automatically include it using style loader.

How can I configure the webpack or typescript that changes are made immediately?

I've implemented webpack so that it generates one file from my angular application. webpack.js
Now the problem is whenever I change the TypeScript file, I'd have to re-run the webpack to see the effect.
That's slowed the development dramatically.
How can I configure the webpack or typescript that changes are made immediately?
webpack.config.js:
const webpack = require('webpack');
module.exports = {
entry: {
app: './app/main.js',
vendor: './app/vendor.js'
},
output: {
//path: './bin',
filename: 'webpack/webpack-[name].js'
},
resolve: {
extensions: ['', '.js', '.ts']
},
devtool: 'source-map',
module: {
loaders: [
{ test: /\.ts$/, loader: 'ts-loader' },
{ test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ },
{ test: /\.css$/, loaders: ['style', 'css'] },
{ test: /\.json/, loaders: ['json-loader'] },
{ test: /\.html/, loaders: ['raw-loader'] },
{ test: /\.(jpg|png|gif)$/, loaders: ['file-loader'] }
]}
// Add minification
, plugins: [
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
},
output: {
comments: false
}
})
]
};
tsconfig.json
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true
}
}
How can I configure the webpack or typescript that changes are made immediately
Actually configure how you run webpack. If you use webpack --watch it automatically updates the bundle as soon as you make a change, but then you still need to refresh the browser page. Even better if you use webpack-dev-server as webpack-dev-server --hot --inline will even reload your browser page immediately.

How to load fonts in css while using webpack?

My relevant portion of my project directory looks like this:
root
--src
--js
--styles
--less
--main.less
--fonts
--Pixelated.tff
--webpack.config.js
This is the relevant portion of my webpack.config.js
var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'cheap-module-eval-source-map',
entry: [
'webpack-hot-middleware/client',
'./src/js'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
module: {
loaders: [{
test: /\.js$/,
loaders: [ 'babel' ],
exclude: /node_modules/,
include: __dirname
}, {
test: /\.less?$/,
loaders: [ 'style', 'css', 'less' ],
include: __dirname
},
{test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "file-loader" }]
}
};
In main.less, this is the relevant #font-face portion:
#font-face {
font-family: 'Pixelated';
src: url('../fonts/Pixelated.ttf');
}
I've tried a couple of variations on the webpack loader with various github issues I've looked over to no avail. I've also tried using the absolute path to my tff font file just for proof of concept and that isn't working either, which I imagine must be related to my webpack setup.
Change your
{
test: /\.less?$/,
loaders: [ 'style', 'css', 'less' ],
include: __dirname
},
to
{
test: /(\.less|\.css)$/,
loaders: [ 'style', 'css', 'less' ],
}
It should work, the main.css file is a css and you need to use an appropriate loader for that type of files.