I can't find the vender.js when I use webpack - reactjs

I am using webpack and having a problem.I want to product a html in the public but I can't succeed.
when I use npm run dev ,I encounter a problem
this is my github
https://github.com/wohuifude123/webpack20180315
supplement
I have read you answer many times, and then I modidy webpack.dll.js
output: {
path: __dirname + 'public/dist',
filename: '[name].[chunkhash:8].js',
library: '[name]_[chunkhash:8]'
},
and then I modify the webpack.dev.js
const path = require('path');
const merge = require('webpack-merge');
const common = require('./webpack.common.js');
// 引入dev-server配置文件
let BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
// a third party
const manifest = require('./vender-manifest.json');
const _venderName = manifest.name.split('_');
const venderName = _venderName[0] + '.' + _venderName[1];
module.exports = merge(common, {
output: { //打包路径
//filename: '[name].bundle.js', //出口文件名
// filename: '[name].[chunkhash].js',
// 可以使用__dirname变量获取当前模块文件所在目录的完整绝对路径
path: __dirname + 'dist', //打包路径
publicPath:'dist/', // 指定publicPath
filename: '[name].bundle.js',
chunkFilename: '[name].bundle.js',
library: '[venderName].js'
},
devtool: 'source-map',
devServer: {
contentBase: [path.join(__dirname, "./public")], // 本地服务器 加载页面 所在的目录
host: '127.0.0.1',
compress: true,
port: 6600,
open: false // 将自动打开浏览器
},
plugins:[
new BundleAnalyzerPlugin({
analyzerMode: 'server', // static/disabled
analyzerHost: '127.0.0.1',
analyzerPort: 9900,
openAnalyzer: false
})
]
});
finally I modify the webpack.common.js
plugins: [
new CleanWebpackPlugin(['dist'], { // 清除 dist 文件中的内容
exclude: [venderName + '.js'] // 排除 提取出的 第三方的 js
}),
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./vender-manifest.json') // 加载 manifest.json
}),
new HtmlWebpackPlugin({
filename: './index.html',
template: './src/index.html',
//favicon: './src/favicon.ico',
alwaysWriteToDisk: true // 是否开启 new HtmlWebpackHarddiskPlugin()
}),
new HtmlWebpackIncludeAssetsPlugin({
assets: [venderName + '.js'],
append: false // 不会被 webpack 自动打包
}),
// new HtmlWebpackIncludeAssetsPlugin({
// assets: ['config/env-config.js'],
// append: false, // 不会被 webpack 自动打包
// hash: true
// }),
new HtmlWebpackHarddiskPlugin(), // 将[venderName + '.js']和['env-config.js']放进 index.html 中
new webpack.DefinePlugin({ // 创建一个编译时可以配置的全局常量
PRODUCTION: JSON.stringify(true),
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
})
]
Although I have read your answer carefully, I can't understand details.
I try to modify many places ,but the product can't work .

There are 2 problems in your code:
You are not matching the dll library to your app's output library:
Your webpack.dll.js:
output: {
// some properties
library: '[name]_[chunkhash:8]'
}
//...
new webpack.DllPlugin({
name: '[name]_[chunkhash:8]'
})
Your webpack.dev.js:
const manifest = require('./vender-manifest.json');
//...
module.exports = merge(common, {
output: {
// some properties
library: manifest.name // this was missing
}
}
What I see you were doing was matching the DllPlugin name to the dll output file library, which is not the case.
The webpack dll plugin docs inform to Keep the name consistent with output.library, but applying to where you are using the dll (while using DllReferencePlugin), not where you are creating them (DllPlugin).
You are not creating the dll in the dist folder:
Your webpack dll config looks like:
output: {
path: __dirname + '/dist'
}
which writes your dll file into rootDir/dist and not rootDir/public/dist as you rather wanted.
So the fix for this one would be to just change it to path: __dirname + 'public/dist'.
After those fixes your code started to work for me. If you have any more questions feel free to ask ;)

Related

remove absulte path from webpack output

Well, I build my app using webpack in production mode, I have the output files containing absolute paths like :
E:/xxxx/xxxx/src/app/core/components/lib/RadioButtonGroupEntry.js
This is my webpack configuration:
resolve: {
//When require, do not have to add these extensions to file's name
extensions: ["", ".js", ".jsx"],
},
//Render source-map file for final build
//output config
output: {
path: buildPath, //Path of output file
filename: '[name]-[chunkhash].js', //Name of output file
publicPath: '/'
},
node: {
fs: 'empty'
},
plugins: [
//Minify the bundle
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'production')
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
//supresses warnings, usually from module minification
warnings: false
}
}),
//Allows error warnings but does not stop compiling. Will remove when eslint is added
new webpack.NoErrorsPlugin(),
new webpack.optimize.CommonsChunkPlugin({
name: "vendor",
minChunks: Infinity,
}),
// new InlineManifestWebpackPlugin({
// name: 'webpackManifest'
// }),
new WebpackMd5Hash(),
// new ManifestPlugin(),
// new ChunkManifestPlugin({
// filename: "chunk-manifest.json",
// manifestVariable: "webpackManifest"
// }),
new HtmlWebpackPlugin({template: 'src/www/index.ejs'}),
//Transfer Files
new TransferWebpackPlugin([{from: 'www'}], path.resolve(__dirname,'src'))]
I think my webpack.config is messed up and I would like some help to figure out what is wrong with it so that the absolute path will be removed.
Thanks.
Maybe you could try to configure the output path property of your webpack configuration object with path and the node __dirname global object, as this:
output: {
path: path.resolve(__dirname, 'yourBuildFolder')
}
I had a similar issue (I use multiple entries) and solved it with path.relative():
{
entry: {
'head': [
`./${path.relative(__dirname, 'my/source/path.js')}`,
...
]
},
...
}

Multiple Entry Point on Webpack by express js

I want to use multiple entry point of webpack using express js instances in react boilerplate for two different application with sharable codebase
I have two html and two js files
vendor.html for vendor.js and
settings.html for settings.js.
One Server.js with two instances of express
`Server.js
const appVendor = express();
const appSetting = express();
setup(appVendor, {
domain: 'Vendor',
outputPath: resolve(process.cwd(), 'build_vendor'),
publicPath: '/',
});
setup(appSetting, {
domain: 'Setting',
outputPath: resolve(process.cwd(), 'build_setting'),
publicPath: '/',
});
// Start your Vendor app.
appVendor.listen('3000', host, (err) => {
if (err) {
return logger.error(err.message);
}
console.log('Server listing to port ', 3000);
});
// Start your Setting app.
appSetting.listen('5000', host, (err) => {
if (err) {
return logger.error(err.message);
}
console.log('Server listing to port ', 5000);
});
webpack.dev.babel.js
const plugins = [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new HtmlWebpackPlugin({
template: 'app/indexVendor.html',
chunk: ['vendor'],
}),
new HtmlWebpackPlugin({
template: 'app/indexSetting.html',
chunk: ['setting'],
}),
new CircularDependencyPlugin({
exclude: /a\.js|node_modules/,
failOnError: false,
}),
];
if (dllPlugin) {
glob.sync(`${dllPlugin.path}/*.dll.js`).forEach((dllPath) => {
plugins.push(new AddAssetHtmlPlugin({
filepath: dllPath,
includeSourcemap: false,
}));
});
}
module.exports = require('./webpack.base.babel')({
entry: {
vendor: [
'eventsource-polyfill',
'webpack-hot-middleware/client?reload=true',
path.join(process.cwd(), 'app/appVendor.js'),
],
setting: [
'eventsource-polyfill',
'webpack-hot-middleware/client?reload=true',
path.join(process.cwd(), 'app/appSetting.js'),
],
},
output: {
// path: path.resolve(__dirname, 'build'),
filename: '[name].js',
chunkFilename: '[name].chunk.js',
},
// Add development plugins
plugins: dependencyHandlers().concat(plugins),
// Emit a source map for easier debugging
// See https://webpack.js.org/configuration/devtool/#devtool
devtool: 'eval-source-map',
performance: {
hints: false,
},
});
How can i communication server.js(IP and port) with webpack multiple entry point

webpack DefinePlugin use external config.js

I am new in webpack
I have this code in webpack.config.js
var path = require('path');
var webpack = require('webpack');
var pkg = require('./package.json');
var myconfig = require('./webpack.myconfig.js');
// bundle dependencies in separate vendor bundle
var dependencies = Object.keys(pkg.dependencies).filter(function (el) {
//exclude font packages from vendor bundle & css-toggle-switch
if (el.indexOf('font') !== -1 || el.indexOf('css-toggle-switch') !== -1) {
return false;
}
else return true;
});
module.exports = {
entry: {
libs: dependencies,
main: './src/index'
},
output: {
path: path.join(__dirname, myconfig.buildPath),
publicPath: myconfig.uiURL,
filename: 'dist/js/[name].js',
chunkFilename: '[id].[name].js'
},
plugins: [
new webpack.DefinePlugin({
DEBUG_MODE: JSON.stringify(false),
TIMEOUT: JSON.stringify(30000),
API_URL: JSON.stringify(myconfig.apiUrl),
"process.env": {
NODE_ENV: JSON.stringify("production")
}
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'libs',
filename: 'dist/js/libs.js',
minChunks: Infinity
})
],
};
and this is myconfig.js
myconfig = {
uiURL: 'http://example.com/',
apiUrl: 'http://api.example.com/api/'
};
module.exports = myconfig;
and if I run this syntax
webpack -p --config webpack.config.js --progress --colors
I will get the result like
/dist/js/libs.js
/dist/js/main.js
but I want the result not like this, I want the result to be:
/dist/js/myconfig.js
/dist/js/libs.js
/dist/js/main.js
What really I want is,
I want in main.js file, it will use myconfig.apiUrl as depedencies,
so when I deployed to production or qserver, I just change myconfig.js.
Thank you
webpack.myconfig.js is used in webpack config file so you have to rebuild every time when webpack.myconfig.js is changed.
You could use myconfig.json and send http request to get it dynamically.
If you just want to get myconfig.js in /dist/js/, you can use CopyWebpackPlugin. It can copy static files from one path to another.
Add a new new line plugins section like :
plugins: [
new CopyWebpackPlugin([{ from: APP_DIR + '\\images', to: APP_DIR + '\\build\\images' }]),
new webpack.DefinePlugin({
DEBUG_MODE: JSON.stringify(false),
TIMEOUT: JSON.stringify(30000),
API_URL: JSON.stringify(myconfig.apiUrl),
"process.env": {
NODE_ENV: JSON.stringify("production")
}
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'libs',
filename: 'dist/js/libs.js',
minChunks: Infinity
})
],
Here CopyWebpackPlugin copies file from one path to another.
Make sure you var CopyWebpackPlugin = require('copy-webpack-plugin');at top of webpack.config.js & added same in package.json & installed via npm.

Webpack2 can't resolve file in pathname

I have having a strange issue I can't seem to resolve.
I am getting this error:
Error: Can't resolve 'store/configureStore' in '/Users/samboy/company/oh-frontend/app'
My webpack file looks like this:
name: 'browser',
context: path.join(__dirname, '..', '..', '..', 'app'),
entry: {
app: './client'
},
output: {
// The output directory as absolute path
path: assetsPath,
// The filename of the entry chunk as relative path inside the output.path directory
filename: '[name].js',
// The output path from the view of the Javascript
publicPath: publicPath
},
module: {
loaders: commonLoaders
},
resolve: {
modules: [
path.resolve(__dirname, '..', '..', '..', 'app'),
'node_modules'
],
extensions: ['', '.js', '.jsx', '.css']
},
plugins: [
// extract inline css from modules into separate files
new ExtractTextPlugin('styles/bundled-modules.css'),
// files in global directory should be concatenated into one file for prod
new CopyWebpackPlugin([
{ from: 'fonts/', to: 'fonts/' }
, { from: '_web/css/global/fonts.css', to: 'styles/fonts.css' }
, { from: '_web/css/vendors', to: 'styles/vendors' }
]),
new webpack.optimize.UglifyJsPlugin({
compressor: {
warnings: false
}
}),
new webpack.DefinePlugin({
__DEVCLIENT__: false,
__DEVSERVER__: false,
__PLATFORM_WEB__: true,
__PLATFORM_IOS__: false
}),
new InlineEnviromentVariablesPlugin({ NODE_ENV: 'production' }),function()
{
this.plugin("done", function(stats)
{
if (stats.compilation.errors && stats.compilation.errors.length)
{
console.log(stats.compilation.errors);
process.exit(1);
}
// ...
});
}
],
postcss: postCSSConfig
}
The file is certainly present in that folder. It worked fine with webpack. It doesn't seem to work with webpack2 though.
I'm guessing because you didn't post your app file, but can you change the import statement in the app file to "./store/configureStore"?

Webpack server configuration + external libs

I have the following webpack configuration file:
const webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const LiveReloadPlugin = require('webpack-livereload-plugin');
const path = require('path');
module.exports = {
entry: [
'webpack-dev-server/client?http://0.0.0.0:2000', // WebpackDevServer host and port
'webpack/hot/only-dev-server', // "only" prevents reload on syntax errors
'./app/index.tsx'
],
output: {
path: __dirname + '/dist/',
filename: 'bundle.js'
},
devtool: 'source-map',
resolve: {
extensions: ['', '.webpack.js', '.web.js', '.ts', '.tsx', '.js']
},
module: {
loaders: [
{
test: /\.tsx?$/,
loaders: ['react-hot', 'ts'],
include: path.join(__dirname, 'app')
}
],
preLoaders: [
'source-map-loader'.
{test: /\.js$/, loader: 'source-map-loader'}
]
},
plugins: [
new CopyWebpackPlugin([
{from: './app/index.html', to: './dist/index.html'}
]),
new webpack.HotModuleReplacementPlugin()
],
builds.
externals: {
'react': 'React',
'react-dom': 'ReactDOM'
}
};
and here is my server configuration:
const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const config = require('./webpack.config');
new WebpackDevServer(webpack(config), {
contentBase: './dist',
publicPath: config.output.publicPath,
hot: true,
historyApiFallback: true,
open: 'http://localhost:2000'
}).listen(2000, 'localhost', function (err, result) {
if (err) {
return console.log(err);
}
console.log('Listening at http://localhost:2000/');
});
I want to be able to access the application from root path: http://localhost:2000 and not http://localhost:2000/dist.
One more thing, is there any way to move all the external dependancies from node_modules to dist with webpack (without the need to include the script tag in the index.html file)?
First of all for set application start point you need to set publicPath to "/" or publicPath: 'http://localhost:2000'
Your second question
Is there any way to move all the external dependancies from node_modules to dist with webpack?
Yes
You can use different file just for external modules and bundle that file. You don't need to take care of index.html file let webpack plugin HtmlWebpackPlugin take care of it.
First step set entry points for your app
entry: {
'vendors': './src/vendors.ts',//your external libraries
'app': './src/main.ts' //your app
}
and out put
output: {
publicPath: '/',
filename: '[name].js'//this will generate two different files app.js, vendor.js
}
How to add HtmlWebpackPlugin?
Add this in you plugins
new HtmlWebpackPlugin({
template: "./src/index.html",
minify:false
})
Now it will place script tags for you
on you server configuration change your public path to
publicPath: '/',

Resources