I added the mterial-components-web.css to the header of my index.html file.
<script src="node_modules/material-components-web/dist/material-components-web.js"></script>
<script src="dist/bundle.js"></script>
the css components work great. Now I added a few javscript components via webpack. Now I thouhgt I could add all vai webpack into my bundle.js.
import 'material-components-web/dist/material-components-web.js';
no error, but no styles loaded! wheres the problem?
regards
my webpack config.
const path = require('path');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
entry: './src/app.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.scss$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader', 'sass-loader']
})
}
]
},
plugins: [
new ExtractTextPlugin('style.css')
],
devServer: {
contentBase: "./build"
}
};
Its difficult to pin down the exact cause without looking at webpack config.
Nevertheless, CSS needs two loaders as suggested in webpack docs. I can only guess that the loaders are not in place.
One can use inline import too as explained here
Though not near to what you are trying feel free to scan through this simple code that have. It basically has bootstrap css bundled via webpack. Note, however though, i have used require() and not import. Shouldnt be difficult to switch with proper js precompiler added in webpack config.
Related
I have a legacy code for my express app that read all routes files in specific dir and require them in a loop. Notice this code cant be changed:
app.js
const normalizedRoutes = fs.readdirSync(__dirname + '/src/routes/')
.map(routeFile => `/src/routes/${routeFile}`);
normalizedRoutes.forEach((normalizedRouteDir: string) => {
require(normalizedRouteDir)(app);
})
Now, I want to combine a Server Side Rendered application with the code above, using some JSX in routes files.
My problem is because the routes files are loaded on run time webpack not recognize them when creating the bundle.js file.
Therefore there are not routes files in the /src/routes/${routeFile} and when I run the bundle.js file I get an error message of:
Error: ENOENT: no such file or directory, scandir '/Users/******/build/src/routes/'
(the stars are for hiding full path)
webpack configs:
webpack.base.js
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
plugins: [new MiniCssExtractPlugin()],
module: { //remain
rules: [
{
test: /\.(ts|js)x?$/,
loader:'babel-loader',
exclude: /node_modules/,
options:{
presets:[
'#babel/react',
['#babel/env',{targets:{browsers:['last 2 versions']}}]
]
}
},
{
test: /\.css$/i,
use: [MiniCssExtractPlugin.loader, "css-loader"],
},
],
}
};
webpack.server.js
const path = require('path')
const {merge} = require('webpack-merge')
const baseConfig = require('./webpack.base.js');
const webpackNodeexternals = require('webpack-node-externals');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const config = {
mode: "development",
entry: {
main:"./app.ts",
},
resolve: {
extensions: [".js", ".jsx", ".json", ".ts"],
},
node: {
__dirname: true
},
output: {
libraryTarget: "commonjs",
path: path.join(__dirname, "build"),
filename: "bundle.js",
},
target: "node",
//Avoid put node modules of server when sending to browser
externals: [webpackNodeexternals()]
}
module.exports = merge(baseConfig,config)
scripts from package.json:
"dev:server": "nodemon --watch build --exec \"node build/bundle.js\" ",
"dev:build-server": "webpack --config webpack.server.js --watch",
When I copy the route files (js files) to the build directory it works of course but that means I don't run webpack on these files and therefore I can't include JSX\es6 features inside these files.
So my question is:
Is there any possible way to make these requires identify by webpack/babel to add them to bundle.js and avoid the need for seperate files (bundle.js and routes files)
If we cant do it, how can I run webpack on a folder seperatly from the bundle.js output and create a route folder in the correct path but after processed by babel?
Thanks!
Instead of using a Webpack you can try using a programmatic interface of babel, and transpile the files before requiring them.
Here is the link https://babeljs.io/docs/en/babel-core
I made a webapp with angular. I want server side rendering with Angular Universal.
The best way to build such a server is by using webpack, this is the standard configuration which works for most of the cases:
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: { server: './server.ts' },
resolve: { extensions: ['.js', '.ts'] },
target: 'node',
externals: [/node_modules/],
mode: 'none',
// this makes sure we include node_modules and other 3rd party libraries
output: {
path: path.join(__dirname, 'dist'),
filename: '[name].js'
},
module: {
rules: [{ test: /\.ts$/, loader: 'ts-loader', exclude: /server-local/ }]
},
plugins: [
// Temporary Fix for issue: https://github.com/angular/angular/issues/11580
// for 'WARNING Critical dependency: the request of a dependency is an expression'
new webpack.ContextReplacementPlugin(
/(.+)?angular(\\|\/)core(.+)?/,
path.join(__dirname, 'src'), // location of your src
{} // a map of your routes
),
new webpack.ContextReplacementPlugin(
/(.+)?express(\\|\/)(.+)?/,
path.join(__dirname, 'src'),
{}
)
]
};
But I got a problem: I use the node module pug-mailer in my server and it uses uglify-js as dependency and not dev dependencies. Webpack has no support in bundling uglify-js, so the only way I found to solve this problem was this:
const nodeExternals = require('webpack-node-externals');
module.exports = {
externals: [nodeExternals()],
... //the rest is unchanged
};
But it cannot be accepted: with this, all node_modules are not bundled and I have to keep the entire node_modules dir in my production server.
Is there a way to bundle all the node_modules in only one file except for uglify-js?
The result I want is this:
dist
----server.js //built with webpack, contains all node_modules except uglify-js
----other dists folder
node_modules
----uglify-js //Only this dependency in node_modules
I'm trying to update my app node backend to typescript and I keep hitting this syntax error:
/Users/Shared/website/src/server.ts:1
(function (exports, require, module, __filename, __dirname) { import *
as express from 'express';
^
SyntaxError: Unexpected token *
I have my tsconfig/webpack/server, etc set up as follows:
server.ts
import * as express from 'express';
import * as path from 'path';
const app = express();
const port = process.env.PORT || 3000;
app.use(express.static(path.join(__dirname, 'dist')));
app.get('*', function(req, res, next){
res.sendFile(path.resolve(__dirname, '/public', 'index.html'));
});
app.listen(port, () => console.log(`Listening on port ${port}!`));
webpack.config.json:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const outputDirectory = 'dist';
module.exports = {
entry: "./src/index.tsx",
output: {
filename: "bundle.js",
path: path.join(__dirname, outputDirectory)
},
mode: 'development',
// Enable sourcemaps for debugging webpack's output.
devtool: "source-map",
resolve: {
// Add '.ts' and '.tsx' as resolvable extensions.
extensions: [".ts", ".tsx", ".js", ".json"]
},
module: {
rules: [
// All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
{ test: /\.tsx?$/, loader: "ts-loader" },
// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
{ enforce: "pre", test: /\.js$/, loader: "source-map-loader" },
{
test: /\.scss$/,
use: [
"style-loader", // creates style nodes from JS strings
"css-loader", // translates CSS into CommonJS
"sass-loader" // compiles Sass to CSS, using Node Sass by default
]
}
]
},
// When importing a module whose path matches one of the following, just
// assume a corresponding global variable exists and use that instead.
// This is important because it allows us to avoid bundling all of our
// dependencies, which allows browsers to cache those libraries between builds.
externals: {
},
plugins: [
new CleanWebpackPlugin([outputDirectory]),
new HtmlWebpackPlugin({
template: './public/index.html',
favicon: './public/favicon.gif'
}),
new CopyWebpackPlugin([
{ from: 'public' }
])
]
};
tsconfig.json:
{
"compilerOptions": {
"outDir": "./dist/",
"sourceMap": true,
"noImplicitAny": false,
"module": "commonjs",
"target": "es6",
"jsx": "react"
},
"include": [
"./src/**/*"
],
}
The build process succeeds, but I hit the syntaxError on run. I have a react front end also set up using typescript / tsx and it works just fine. I seem to just be running into issues with the server.ts / node files. I'm very new to trying to get this all set up, but I wanted practice making a site with numerous technologies (react/node/typescript/sass/webpack/etc). So far I have everything except the typescript/node relationship.
I had the same problem, after I realised that the tsconfig wasn't applied.
If
"module": "commonjs"
was in effect, you wouldn't have this error.
I faced the same problem before. I solve it by changing the import 'call':
From:
import * as express from 'express';
To:
const express = require('express');
As others have stated, the problem is that your tsconfig.json is not applied to server.ts. You have left out important details of your setup which is why others cannot duplicate this problem.
I have a good guess at what the issue is and having struggled with this identical problem myself, I will explain my guess here in the hope of helping some other poor soul being tormented by this issue.
The basic problem is that your server code is in a different tree than your react code. This is why the tsconfig.json is not being applied to it since (I believe) it is outside the "./src/" path specified. (Perhaps "./website/src/").
You haven't shown us the package.json file but very likely the server entry is something like "server": "ts-node ./website/src/server.ts"
To verify that the tsconfig.json application is the issue try this from the command line...
$ ts-node -O '{\"module\":\"commonjs\"}' ./website/src/server.ts
Chances are, things will start working. Now the solution is probably as simple as adding another path your tsconfig.json includes.
So I came across this post on github where basically there are two sort of working methods presented since you’re using a bundling tool targeted to es6 add
"allowSyntheticDefaultImports": true to ”compilerOptions”
Or change
import express from "express";
to
import express = require('express');
This might be happening if your tsconfig.json isn't at the root of your project. Configure webpack to point to your target config file (which you can alter with variables to point to dev and prod configurations).
https://github.com/TypeStrong/ts-loader
If set, will parse the TypeScript configuration file with given absolute path as base path. Per default the directory of the configuration file is used as base path. Relative paths in the configuration file are resolved with respect to the base path when parsed. Option context allows to set option configFile to a path other than the project root (e.g. a NPM package), while the base path for ts-loader can remain the project root.
Try modifying your webpack.config.js file to have this:
module.exports = {
...
module: {
rules: [
{
options: {
configFile: path.join(__dirname, "tsconfig.json")
}
}
]
}
};
Every time I make changes to my website, I fetch them from github. I run webpack in the terminal, which appears to work. Then I run my expressHost.js file to host my site. When i access that site I get the error in the title.
To fix this i delete the folder, git clone, npm install, webpack, node expressHost.js and it works like nothing was ever wrong. any ideas?
Simular issues do not seem to be happening on my dev machine, only my VPS.
my webpack config
module.exports = {
entry: [
'./src/index.js'
],
output: {
path: __dirname,
publicPath: '/',
filename: 'bundle.js'
},
module: {
loaders: [{
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['react', 'es2015', 'stage-1']
}
}]
},
resolve: {
extensions: ['', '.js', '.jsx']
},
devServer: {
historyApiFallback: true,
contentBase: './'
}
};
my expressHost
const express = require('express');
const app = express();
const path = require('path');
app.listen(7070, () => {
console.log('listening 7070...');
})
app.use(express.static(path.join(__dirname, 'public')));
my public folder has index.html, bundle.js, and styles folder. Everything was made using React and is hosted with nginx. I am new to deployment, I have only launched one other site (which works, NG1)
this is the error i get when running webpack... this does not happen on the local machine.
Hash: d437a155a1da4cdfeeeb
Version: webpack 1.14.0
Time: 77ms
Asset Size Chunks Chunk Names
bundle.js 1.51 kB 0 [emitted] main
[0] multi main 28 bytes {0} [built] [1 error]
+ 1 hidden modules
ERROR in The node API for `babel` has been moved to `babel-core`.
# multi main
https://github.com/babel/babel-loader/issues/259
https://www.codementor.io/tamizhvendan/tutorials/beginner-guide-setup-reactjs-environment-npm-babel-6-webpack-du107r9zr
So I was having the error listed above but the page was still working on my local machine. When I posted any changes I would get that error but it seemed to work, When users viewed the machine they would get the error in the title.
to install babel loader correctly I have to change the webpack config to module{ loaders {[ loader: 'babel-loader' this seemed to solve the issue of babel being moved into babel-core's folder
also (probably the real issue) npm needed to install, in terminal
npm i babel-loader babel-preset-es2015 babel-preset-react babel-preset-stage-1 -S
because the webpack config had module{ loaders {[ query: { presets: ['react', 'es2015', 'stage-1']
the website appears to be fetching and compiling websites like normal.
I have an app which folders are structured like this:
/app/
|- /assets/
| |- /css/
| |- myapp.css
|- index.html
|- index.js
/dist/
/node_modules/
.babelrc
package.json
webpack.config.js
myapp.css is a simple, plain css, with nothing special. Just a styling on body to see if it was working.
And my webpack.config.js file has this:
// In webpack.config.js
var HtmlWebpackPlugin = require('html-webpack-plugin');
var HTMLWebpackPluginConfig = new HtmlWebpackPlugin({
template: __dirname + '/app/index.html',
filename: 'index.html',
inject: 'body'
});
module.exports = {
entry: [
'./app/index.js'
],
output: {
path: __dirname + '/dist',
filename: "index_bundle.js"
},
module: {
loaders: [
{test: /\.js$/, exclude: /node_modules/, loader: "babel-loader"},
{test: /\.css$/, loaders: ['style', 'css']}
]
},
plugins: [HTMLWebpackPluginConfig]
};
I have put the required css file on index.js like this:
var React = require('react');
var ReactDOM = require('react-dom');
require('assets/css/myapp.css');
var HelloWorld = React.createClass({
render: function () {
return (
<div> Hello ReactJs</div>
)
}
});
ReactDOM.render(
<HelloWorld />,
document.getElementById('app')
)
I have tried all the ways to get it loaded, adding ../ before assets word, and everythig, but I just keep receiving this error on console:
Error: Cannot find module "assets/css/myapp.css"
I have double check, and css-loader and style-loader are both on /node_modules folder.
What am I doing wrong? I am stuck on it for more than 3 hours, checking tens of tutorials, and I have done all specified. Thanks for the help!
Well... I just needed to add ./ to the require line, like this:
require('./assets/css/myapp.css');
Hope this helps someone else. Thanks, #QoP